diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java index 53ad436b64a..cba7c8f6c44 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java @@ -7,11 +7,8 @@ package com.evolveum.midpoint.gui.api.component; import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.model.api.ModelAuthorizationAction; import com.evolveum.midpoint.prism.Containerable; -import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectPaging; import com.evolveum.midpoint.prism.query.ObjectQuery; @@ -126,6 +123,7 @@ protected void saveProviderPaging(ObjectQuery query, ObjectPaging paging) { @Override public ObjectQuery getQuery() { try { + // TODO this seems to throw now checked exception (see unused throws lower) return createQuery(); } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException | ConfigurationException | SecurityViolationException e) { @@ -141,7 +139,7 @@ public ObjectQuery getQuery() { protected abstract Class getType(); protected void setDefaultSorting(ContainerListDataProvider provider){ - //should be overridded if needed + //should be overridden if needed } public long getItemsPerPage() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java index 7fda0b71731..321c2e97290 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java @@ -62,7 +62,7 @@ protected IColumn, String> createCheckboxColumn() { protected void onUpdateRow(AjaxRequestTarget target, DataTable table, IModel> rowModel, IModel selected) { super.onUpdateRow(target, table, rowModel, selected); onUpdateCheckbox(target, rowModel); - }; + } @Override protected void onUpdateHeader(AjaxRequestTarget target, boolean selected, DataTable table) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java index ab4dec89393..07021336d90 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java @@ -15,13 +15,10 @@ import javax.management.ObjectName; import javax.xml.namespace.QName; -import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; - import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.commons.lang3.ObjectUtils; import org.apache.wicket.*; -import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxChannel; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -35,8 +32,6 @@ import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.CssHeaderItem; import org.apache.wicket.markup.head.IHeaderResponse; -import org.apache.wicket.markup.head.JavaScriptHeaderItem; -import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebPage; @@ -80,10 +75,14 @@ import com.evolveum.midpoint.gui.impl.factory.ItemWrapperFactory; import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettings; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValuePanel; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; +import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper; import com.evolveum.midpoint.model.api.*; -import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; +import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; import com.evolveum.midpoint.model.api.expr.MidpointFunctions; import com.evolveum.midpoint.model.api.interaction.DashboardService; import com.evolveum.midpoint.model.api.validator.ResourceValidator; @@ -159,15 +158,16 @@ import com.evolveum.midpoint.web.page.admin.resources.*; import com.evolveum.midpoint.web.page.admin.roles.PageRole; import com.evolveum.midpoint.web.page.admin.roles.PageRoles; -import com.evolveum.midpoint.web.page.admin.server.*; +import com.evolveum.midpoint.web.page.admin.server.PageNodes; +import com.evolveum.midpoint.web.page.admin.server.PageTask; +import com.evolveum.midpoint.web.page.admin.server.PageTasks; +import com.evolveum.midpoint.web.page.admin.server.PageTasksCertScheduling; import com.evolveum.midpoint.web.page.admin.services.PageService; import com.evolveum.midpoint.web.page.admin.services.PageServices; import com.evolveum.midpoint.web.page.admin.users.PageOrgTree; import com.evolveum.midpoint.web.page.admin.users.PageOrgUnit; import com.evolveum.midpoint.web.page.admin.users.PageUser; import com.evolveum.midpoint.web.page.admin.users.PageUsers; -import com.evolveum.midpoint.web.page.admin.valuePolicy.PageValuePolicies; -import com.evolveum.midpoint.web.page.admin.valuePolicy.PageValuePolicy; import com.evolveum.midpoint.web.page.admin.workflow.PageAttorneySelection; import com.evolveum.midpoint.web.page.admin.workflow.PageWorkItemsAttorney; import com.evolveum.midpoint.web.page.login.PageLogin; @@ -686,19 +686,6 @@ public void authorize(String operat getSecurityEnforcer().authorize(operationUrl, phase, params, ownerResolver, getPageTask(), result); } - public void authorize(String operationUrl, AuthorizationPhaseType phase, - PrismObject object, ObjectDelta delta, PrismObject target, OwnerResolver ownerResolver) - throws SecurityViolationException, SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException { - Task task = getPageTask(); - AuthorizationParameters params = new AuthorizationParameters.Builder() - .oldObject(object) - .delta(delta) - .target(target) - .build(); - getSecurityEnforcer().authorize(operationUrl, phase, params, ownerResolver, task, task.getResult()); - } - - public MidpointFormValidatorRegistry getFormValidatorRegistry() { return formValidatorRegistry; } @@ -1185,10 +1172,6 @@ public String getMainPopupBodyId() { return getMainPopup().getContentId(); } - public void setMainPopupTitle(IModel title) { - getMainPopup().setTitle(title); - } - public void showMainPopup(Popupable popupable, AjaxRequestTarget target) { getMainPopup().setTitle(popupable.getTitle()); getMainPopup().setInitialHeight(popupable.getHeight()); @@ -1542,61 +1525,6 @@ public String getDescribe() { return getString("pageBase.unknownBuildNumber"); } - protected ModalWindow createModalWindow(final String id, IModel title, int width, int height) { - final ModalWindow modal = new ModalWindow(id); - add(modal); - - modal.setResizable(false); - modal.setTitle(title); - modal.setCookieName(PageBase.class.getSimpleName() + ((int) (Math.random() * 100))); - - modal.setInitialWidth(width); - modal.setWidthUnit("px"); - modal.setInitialHeight(height); - modal.setHeightUnit("px"); - - modal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { - - private static final long serialVersionUID = 1L; - - @Override - public boolean onCloseButtonClicked(AjaxRequestTarget target) { - return true; - } - }); - - modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { - - private static final long serialVersionUID = 1L; - - @Override - public void onClose(AjaxRequestTarget target) { - modal.close(target); - } - }); - - modal.add(new AbstractDefaultAjaxBehavior() { - - private static final long serialVersionUID = 1L; - - @Override - public void renderHead(Component component, IHeaderResponse response) { - response.render(OnDomReadyHeaderItem.forScript("Wicket.Window.unloadConfirmation = false;")); - response.render(JavaScriptHeaderItem - .forScript("$(document).ready(function() {\n" + " $(document).bind('keyup', function(evt) {\n" - + " if (evt.keyCode == 27) {\n" + getCallbackScript() + "\n" - + " evt.preventDefault();\n" + " }\n" + " });\n" + "});", id)); - } - - @Override - protected void respond(AjaxRequestTarget target) { - modal.close(target); - } - }); - - return modal; - } - // returns to previous page via restart response exception public RestartResponseException getRestartResponseException(Class defaultBackPageClass) { return new RestartResponseException(defaultBackPageClass); @@ -1755,11 +1683,6 @@ protected List createMenuItems() { AuthorizationConstants.AUTZ_UI_RESOURCE_EDIT_URL, AuthorizationConstants.AUTZ_UI_RESOURCES_VIEW_URL)) { items.add(createResourcesItems()); } - //TODO uncomment after ValuePolicies pages are finished -// if (WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_VALUE_POLICIES_URL, AuthorizationConstants.AUTZ_GUI_ALL_URL, -// AuthorizationConstants.AUTZ_UI_VALUE_POLICIES_ALL_URL, AuthorizationConstants.AUTZ_GUI_ALL_DEPRECATED_URL)) { -// items.add(createValuePolicieItems()); -// } if (WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_MY_WORK_ITEMS_URL, AuthorizationConstants.AUTZ_UI_ATTORNEY_WORK_ITEMS_URL, @@ -1953,8 +1876,6 @@ private MainMenuItem createServerTasksItems() { addMenuItem(item, "PageAdmin.menu.top.serverTasks.nodes", PageNodes.class); - //should we support archetype view for TaskType? -// addCollectionsMenuItems(item.getItems(), TaskType.COMPLEX_TYPE); MenuItem newTaskMenu = new MenuItem(createStringResource("PageAdmin.menu.top.serverTasks.new"), GuiStyleConstants.CLASS_PLUS_CIRCLE, PageTask.class, null, new VisibleEnableBehaviour()); item.getItems().add(newTaskMenu); @@ -1990,16 +1911,6 @@ private MainMenuItem createResourcesItems() { return item; } - // Izolated until the referenced value policies pages are fully implemented - private MainMenuItem createValuePolicieItems() { - MainMenuItem item = new MainMenuItem("fa fa-asterisk", createStringResource("PageAdmin.menu.top.valuePolicies"), null); - - addMenuItem(item, "PageAdmin.menu.top.valuePolicies.list", PageValuePolicies.class); - addMenuItem(item, "PageAdmin.menu.top.valuePolicies.new", PageValuePolicy.class); - - return item; - } - private MainMenuItem createReportsItems() { MainMenuItem item = new MainMenuItem("fa fa-pie-chart", createStringResource("PageAdmin.menu.top.reports"), null); @@ -2428,20 +2339,6 @@ public boolean isEnabled() { }; } - public DeploymentInformationType loadDeploymentInformationType() { - DeploymentInformationType deploymentInformationType = null; - OperationResult result = new OperationResult(OPERATION_GET_DEPLOYMENT_INFORMATION); - try { - deploymentInformationType = getModelInteractionService().getDeploymentInformationConfiguration(result); - LOGGER.trace("Deployment information : {}", deploymentInformationType); - result.recordSuccess(); - } catch (Exception ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load deployment information", ex); - result.recordFatalError(createStringResource("PageBase.message.loadDeploymentInformationType.fatalError").getString(), ex); - } - return deploymentInformationType; - } - public boolean canRedirectBack() { return canRedirectBack(DEFAULT_BREADCRUMB_STEP); } @@ -2777,16 +2674,10 @@ public Panel initItemPanel(String panelId, QName typeNa public , C extends Containerable> Panel initContainerValuePanel(String id, IModel model, ItemPanelSettings settings) { - //ItemVisibilityHandler visibilityHandler, ItemEditabilityHandler editabilityHandler) { //TODO find from registry first return new PrismContainerValuePanel<>(id, model, settings); } - public Panel getBasicContainerValuePanel(String idPanel, IModel> model, ItemPanelSettings settings){ - Panel containerValue = initContainerValuePanel(idPanel, model, settings); - return containerValue; - } - public Clock getClock() { return clock; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java index 909fa9a5666..f453815ab48 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java @@ -1,81 +1,83 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.gui.api.prism; - -import java.io.Serializable; -import java.util.Collection; -import java.util.List; - -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper; -import com.evolveum.midpoint.prism.Item; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.Revivable; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.util.DebugDumpable; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -/** - * @author katka - * - */ -public interface ItemWrapper, ID extends ItemDefinition, VW extends PrismValueWrapper> extends ItemDefinition, Revivable, DebugDumpable, Serializable { - - - String debugDump(int indent); - - boolean isVisible(PrismContainerValueWrapper parentContainer, ItemVisibilityHandler visibilityHandler); - - boolean checkRequired(PageBase pageBase); - - PrismContainerValueWrapper getParent(); - - boolean isShowEmpty(); - - void setShowEmpty(boolean isShowEmpty, boolean recursive); - - boolean isShowInVirtualContainer(); - - void setShowInVirtualContainer(boolean showInVirtualContainer); - - ItemPath getPath(); - - //NEW - - boolean isReadOnly(); - - void setReadOnly(boolean readOnly); - - ExpressionType getFormComponentValidator(); - - List getValues(); - VW getValue() throws SchemaException; - - boolean isStripe(); - void setStripe(boolean stripe); - - I getItem(); - - boolean isColumn(); - void setColumn(boolean column); - - > void applyDelta(D delta) throws SchemaException; - - > Collection getDelta() throws SchemaException; - - ItemStatus findObjectStatus(); - - , O extends ObjectType> OW findObjectWrapper(); - - ItemStatus getStatus(); -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.gui.api.prism; + +import java.io.Serializable; +import java.util.Collection; +import java.util.List; + +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; +import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper; +import com.evolveum.midpoint.prism.Item; +import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismValue; +import com.evolveum.midpoint.prism.Revivable; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.util.DebugDumpable; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserInterfaceElementVisibilityType; + +/** + * @author katka + * + */ +public interface ItemWrapper, ID extends ItemDefinition, VW extends PrismValueWrapper> extends ItemDefinition, Revivable, DebugDumpable, Serializable { + + + String debugDump(int indent); + + void setVisibleOverwrite(UserInterfaceElementVisibilityType visible); + boolean isVisible(PrismContainerValueWrapper parentContainer, ItemVisibilityHandler visibilityHandler); + + boolean checkRequired(PageBase pageBase); + + PrismContainerValueWrapper getParent(); + + boolean isShowEmpty(); + + void setShowEmpty(boolean isShowEmpty, boolean recursive); + + boolean isShowInVirtualContainer(); + + void setShowInVirtualContainer(boolean showInVirtualContainer); + + ItemPath getPath(); + + //NEW + + boolean isReadOnly(); + + void setReadOnly(boolean readOnly); + + ExpressionType getFormComponentValidator(); + + List getValues(); + VW getValue() throws SchemaException; + + boolean isStripe(); + void setStripe(boolean stripe); + + I getItem(); + + boolean isColumn(); + void setColumn(boolean column); + + > void applyDelta(D delta) throws SchemaException; + + > Collection getDelta() throws SchemaException; + + ItemStatus findObjectStatus(); + + , O extends ObjectType> OW findObjectWrapper(); + + ItemStatus getStatus(); +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java index 6b0f295f6ad..24be4a53ff9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java @@ -1,145 +1,112 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.gui.api.util; - -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.security.MidPointApplication; -import com.evolveum.midpoint.web.security.util.SecurityUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.model.IModel; - -import javax.xml.namespace.QName; -import java.util.ArrayList; -import java.util.List; - -/** - * Created by Viliam Repan (lazyman). - */ -public class ObjectTabVisibleBehavior extends VisibleEnableBehaviour { - private static final long serialVersionUID = 1L; - - private static final String OPERATION_LOAD_GUI_CONFIGURATION = ObjectTabVisibleBehavior.class.getName() + ".loadGuiConfiguration"; - - private IModel> objectModel; - private String uiAuthorizationUrl; - private PageBase pageBase; - - public ObjectTabVisibleBehavior(IModel> objectModel, String uiAuthorizationUrl, PageBase pageBase) { - this.objectModel = objectModel; - this.uiAuthorizationUrl = uiAuthorizationUrl; - this.pageBase = pageBase; - } - - private ModelInteractionService getModelInteractionService() { - return ((MidPointApplication) MidPointApplication.get()).getModelInteractionService(); - } - - private TaskManager getTaskManager() { - return ((MidPointApplication) MidPointApplication.get()).getTaskManager(); - } - - @Override - public boolean isVisible() { - PrismObject object = objectModel.getObject(); - if (object == null) { - return true; - } - - Task task = WebModelServiceUtils.createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION, - SecurityUtils.getPrincipalUser().getFocus().asPrismObject(), getTaskManager()); - OperationResult result = task.getResult(); - - CompiledGuiProfile config; - try { - config = getModelInteractionService().getCompiledGuiProfile(task, result); - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { - throw new SystemException("Cannot load GUI configuration: " + e.getMessage(), e); - } - - // find all object form definitions for specified type, if there is none we'll show all default tabs - List forms = findObjectForm(config, object); - if (forms.isEmpty()) { - return true; - } - - // we'll try to find includeDefault, if there is includeDefault=true, we can return true (all tabs visible) - for (ObjectFormType form : forms) { - if (BooleanUtils.isTrue(form.isIncludeDefaultForms())) { - return true; - } - } - - for (ObjectFormType form : forms) { - FormSpecificationType spec = form.getFormSpecification(); - if (spec == null || StringUtils.isEmpty(spec.getPanelUri())) { - continue; - } - - if (ObjectUtils.equals(uiAuthorizationUrl, spec.getPanelUri())) { - return true; - } - } - - return false; - } - - private List findObjectForm(CompiledGuiProfile config, PrismObject object) { - List result = new ArrayList<>(); - - if (config == null || config.getObjectForms() == null) { - return result; - } - - ObjectFormsType forms = config.getObjectForms(); - List list = forms.getObjectForm(); - if (list.isEmpty()) { - return result; - } - - for (ObjectFormType form : list) { - if (isApplicable(form, object)) { - result.add(form); - } - } - - return result; - } - - private boolean isApplicable(ObjectFormType form, PrismObject object) { - QName objectType = object.getDefinition().getTypeName(); - if (!objectType.equals(form.getType())) { - return false; - } - RoleRelationObjectSpecificationType roleRelation = form.getRoleRelation(); - if (roleRelation != null) { - List subjectRelations = roleRelation.getSubjectRelation(); - if (!pageBase.hasSubjectRoleRelation(object.getOid(), subjectRelations)) { - return false; - } - } - // TODO: roleRelation - return true; - } -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.gui.api.util; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.namespace.QName; + +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.model.IModel; + +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +/** + * Created by Viliam Repan (lazyman). + */ +public class ObjectTabVisibleBehavior extends VisibleEnableBehaviour { + private static final long serialVersionUID = 1L; + + private IModel> objectModel; + private String uiAuthorizationUrl; + private PageBase pageBase; + + public ObjectTabVisibleBehavior(IModel> objectModel, String uiAuthorizationUrl, PageBase pageBase) { + this.objectModel = objectModel; + this.uiAuthorizationUrl = uiAuthorizationUrl; + this.pageBase = pageBase; + } + + @Override + public boolean isVisible() { + PrismObject object = objectModel.getObject(); + if (object == null) { + return true; + } + + CompiledGuiProfile config = pageBase.getCompiledGuiProfile(); + + // find all object form definitions for specified type, if there is none we'll show all default tabs + List forms = findObjectForm(config, object); + if (forms.isEmpty()) { + return true; + } + + // we'll try to find includeDefault, if there is includeDefault=true, we can return true (all tabs visible) + for (ObjectFormType form : forms) { + if (BooleanUtils.isTrue(form.isIncludeDefaultForms())) { + return true; + } + } + + for (ObjectFormType form : forms) { + FormSpecificationType spec = form.getFormSpecification(); + if (spec == null || StringUtils.isEmpty(spec.getPanelUri())) { + continue; + } + + if (ObjectUtils.equals(uiAuthorizationUrl, spec.getPanelUri())) { + return true; + } + } + + return false; + } + + private List findObjectForm(CompiledGuiProfile config, PrismObject object) { + List result = new ArrayList<>(); + + if (config == null || config.getObjectForms() == null) { + return result; + } + + ObjectFormsType forms = config.getObjectForms(); + List list = forms.getObjectForm(); + if (list.isEmpty()) { + return result; + } + + for (ObjectFormType form : list) { + if (isApplicable(form, object)) { + result.add(form); + } + } + + return result; + } + + private boolean isApplicable(ObjectFormType form, PrismObject object) { + QName objectType = object.getDefinition().getTypeName(); + if (!objectType.equals(form.getType())) { + return false; + } + RoleRelationObjectSpecificationType roleRelation = form.getRoleRelation(); + if (roleRelation != null) { + List subjectRelations = roleRelation.getSubjectRelation(); + return pageBase.hasSubjectRoleRelation(object.getOid(), subjectRelations); + } + // TODO: roleRelation + return true; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java index cc0e6b81d06..fb1e3ca6d3c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java @@ -689,6 +689,48 @@ public static boolean isWorkflowTask(TaskType task) { return task != null && TaskCategory.WORKFLOW.equals(task.getCategory()); } + public static boolean isReconciliation(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_RECONCILIATION_TASK); + } + + public static boolean isRecomputation(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK); + } + + public static boolean isReport(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_REPORT_TASK); + } + + public static boolean isImport(TaskType task){ + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_IMPORT_TASK); + } + + public static boolean isLiveSync(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_LIVE_SYNC_TASK); + } + + private static boolean isArchetypedTask(TaskType taskType, SystemObjectsType archetype) { + ObjectReferenceType archetypeRef = getArchetypeReference(taskType); + if (archetypeRef == null){ + return false; + } + return archetype.value().equals(archetypeRef.getOid()); + } + + private static ObjectReferenceType getArchetypeReference(TaskType task) { + ObjectReferenceType archetypeRef = null; + if (task.getAssignment() == null || task.getAssignment().size() == 0) { + return archetypeRef; + } + for (AssignmentType assignment : task.getAssignment()) { + if (StringUtils.isNotEmpty(assignment.getTargetRef().getOid()) + && assignment.getTargetRef() != null && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { + archetypeRef = assignment.getTargetRef(); + } + } + return archetypeRef; + } + public static void iterativeExecuteBulkAction(PageBase pageBase, ExecuteScriptType script, Task task, OperationResult result ) throws SchemaException, SecurityViolationException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException{ @@ -746,6 +788,56 @@ public static Task createMemberOperationTask(Task operationalTask, QName type, O return null; } + public static Task createRecomputeMemberOperationTask(Task operationalTask, QName type, ObjectQuery memberQuery, + Collection> option, OperationResult parentResult, PageBase pageBase) throws SchemaException { + + MidPointPrincipal owner = SecurityUtils.getPrincipalUser(); + operationalTask.setOwner(owner.getFocus().asPrismObject()); + + operationalTask.setBinding(TaskBinding.LOOSE); + operationalTask.setInitialExecutionStatus(TaskExecutionStatus.RUNNABLE); + operationalTask.setThreadStopAction(ThreadStopActionType.RESTART); + ScheduleType schedule = new ScheduleType(); + schedule.setMisfireAction(MisfireActionType.EXECUTE_IMMEDIATELY); + operationalTask.makeSingle(schedule); + operationalTask.setName(WebComponentUtil.createPolyFromOrigString(parentResult.getOperation())); + + PrismPropertyDefinition propertyDefQuery = pageBase.getPrismContext().getSchemaRegistry() + .findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY); + PrismProperty queryProperty = propertyDefQuery.instantiate(); + QueryType queryType = pageBase.getQueryConverter().createQueryType(memberQuery); + queryProperty.setRealValue(queryType); + operationalTask.addExtensionProperty(queryProperty); + + PrismPropertyDefinition propertyDefType = pageBase.getPrismContext().getSchemaRegistry() + .findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE); + PrismProperty typeProperty = propertyDefType.instantiate(); + typeProperty.setRealValue(type); + operationalTask.addExtensionProperty(typeProperty); + + if (option != null) { + PrismPropertyDefinition propertyDefOption = pageBase.getPrismContext().getSchemaRegistry() + .findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_SEARCH_OPTIONS); + PrismProperty optionProperty = propertyDefOption.instantiate(); + optionProperty.setRealValue(MiscSchemaUtil.optionsToOptionsType(option)); + operationalTask.addExtensionProperty(optionProperty); + } + + try { + pageBase.getSecurityEnforcer().authorize(ModelAuthorizationAction.RECOMPUTE.getUrl(), + null, AuthorizationParameters.EMPTY, null, operationalTask, parentResult); + operationalTask.setHandlerUri(ModelPublicConstants.RECOMPUTE_HANDLER_URI); + return operationalTask; + } catch (ObjectNotFoundException | SchemaException + | ExpressionEvaluationException | CommunicationException | ConfigurationException + | SecurityViolationException e) { + parentResult.recordFatalError(pageBase.createStringResource("WebComponentUtil.message.startPerformed.fatalError.createTask").getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't create bulk action task", e); + } + return null; + } + + public static void executeMemberOperation(Task operationalTask, OperationResult parentResult, PageBase pageBase) { OperationResult result = parentResult.createSubresult("evaluateExpressionInBackground"); @@ -3013,15 +3105,16 @@ public static boolean isAllNulls(Iterable array) { return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null); } - public static ObjectFilter createAssociationShadowRefFilter(RefinedAssociationDefinition refinedAssocationDefinition, PrismContext prismContext, - String resourceOid){ + public static ObjectFilter createAssociationShadowRefFilter( + RefinedAssociationDefinition refinedAssociationDefinition, + PrismContext prismContext, String resourceOid) { S_FilterEntryOrEmpty atomicFilter = prismContext.queryFor(ShadowType.class); List orFilterClauses = new ArrayList<>(); - refinedAssocationDefinition.getIntents() + refinedAssociationDefinition.getIntents() .forEach(intent -> orFilterClauses.add(atomicFilter.item(ShadowType.F_INTENT).eq(intent).buildFilter())); OrFilter intentFilter = prismContext.queryFactory().createOr(orFilterClauses); - AndFilter filter = (AndFilter) atomicFilter.item(ShadowType.F_KIND).eq(refinedAssocationDefinition.getKind()).and() + AndFilter filter = (AndFilter) atomicFilter.item(ShadowType.F_KIND).eq(refinedAssociationDefinition.getKind()).and() .item(ShadowType.F_RESOURCE_REF).ref(resourceOid, ResourceType.COMPLEX_TYPE).buildFilter(); filter.addCondition(intentFilter); return filter; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java index ff721c90bbc..72f8f7e0879 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java @@ -1,844 +1,848 @@ -/* - * Copyright (c) 2010-2019 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.gui.api.util; - -import static com.evolveum.midpoint.schema.GetOperationOptions.createNoFetchCollection; - -import java.util.*; - -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.LocaleUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.Session; -import org.apache.wicket.ThreadContext; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import com.evolveum.midpoint.common.LocalizationService; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.delta.ChangeType; -import com.evolveum.midpoint.prism.delta.DeltaFactory; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.GetOperationOptionsBuilder; -import com.evolveum.midpoint.schema.SchemaHelper; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.security.api.MidPointPrincipal; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; -import com.evolveum.midpoint.util.exception.AuthorizationException; -import com.evolveum.midpoint.util.exception.CommonException; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.page.login.PageLogin; -import com.evolveum.midpoint.web.security.MidPointApplication; -import com.evolveum.midpoint.web.security.util.SecurityUtils; -import com.evolveum.prism.xml.ns._public.types_3.EvaluationTimeType; - -import javax.xml.namespace.QName; - -/** - * Utility class that contains methods that interact with ModelService and other - * midPoint components. - * - * @author lazyman - */ -public class WebModelServiceUtils { - - private static final Trace LOGGER = TraceManager.getTrace(WebModelServiceUtils.class); - - private static final String DOT_CLASS = WebModelServiceUtils.class.getName() + "."; - private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; - private static final String OPERATION_DELETE_OBJECT = DOT_CLASS + "deleteObject"; - private static final String OPERATION_SEARCH_OBJECTS = DOT_CLASS + "searchObjects"; - private static final String OPERATION_SAVE_OBJECT = DOT_CLASS + "saveObject"; - private static final String OPERATION_LOAD_OBJECT_REFS = DOT_CLASS + "loadObjectReferences"; - private static final String OPERATION_COUNT_OBJECT = DOT_CLASS + "countObjects"; - private static final String OPERATION_ASSUME_POWER_OF_ATTORNEY = DOT_CLASS + "assumePowerOfAttorney"; - private static final String OPERATION_DROP_POWER_OF_ATTORNEY = DOT_CLASS + "dropPowerOfAttorney"; - private static final String OPERATION_GET_SYSTEM_CONFIG = DOT_CLASS + "getSystemConfiguration"; - private static final String OPERATION_LOAD_FLOW_POLICY = DOT_CLASS + "loadFlowPolicy"; - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page) { - return resolveReferenceName(ref, page, false); - } - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, boolean translate) { - Task task = page.createSimpleTask(WebModelServiceUtils.class.getName() + ".resolveReferenceName"); - return resolveReferenceName(ref, page, task, task.getResult(), translate); - } - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result) { - return resolveReferenceName(ref, page, task, result, false); - } - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result, boolean translate) { - if (ref == null) { - return null; - } - if (ref.getTargetName() != null) { - return translate ? page.getLocalizationService().translate(ref.getTargetName().toPolyString(), page.getLocale(), true) - : ref.getTargetName().getOrig(); - } - if (StringUtils.isEmpty(ref.getOid()) || ref.getType() == null){ - return null; - } - PrismObject object = resolveReferenceNoFetch(ref, page, task, result); - if (object == null) { - return ref.getOid(); - } else { - ref.asReferenceValue().setObject(object); - return WebComponentUtil.getName(object, translate); - } - } - - public static PrismObject resolveReferenceNoFetch(ObjectReferenceType reference, PageBase page, Task task, OperationResult result) { - if (reference == null) { - return null; - } - if (reference.asReferenceValue().getObject() != null) { - return reference.asReferenceValue().getObject(); - } - PrismContext prismContext = page.getPrismContext(); - if (reference.getType() == null) { - LOGGER.error("No type in {}", reference); - return null; - } - PrismObjectDefinition definition = prismContext.getSchemaRegistry().findObjectDefinitionByType(reference.getType()); - if (definition == null) { - LOGGER.error("No definition for {} was found", reference.getType()); - return null; - } - if (reference.getOid() == null) { - if (reference.getResolutionTime() == EvaluationTimeType.RUN) { - // Runtime reference resolution. Ignore it for now. Later we maybe would want to resolve it here. - // But it may resolve to several objects .... - return null; - } else { - LOGGER.error("Null OID in reference {}", reference); - // Throw an exception instead? Maybe not. We want GUI to be robust. - return null; - } - } - return loadObject(definition.getCompileTimeClass(), reference.getOid(), createNoFetchCollection(), page, task, result); - } - - public static List createObjectReferenceList(Class type, PageBase page, Map referenceMap){ - referenceMap.clear(); - - OperationResult result = new OperationResult(OPERATION_LOAD_OBJECT_REFS); -// Task task = page.createSimpleTask(OPERATION_LOAD_PASSWORD_POLICIES); - - try { - List> objects = searchObjects(type, null, result, page); - result.recomputeStatus(); - List references = new ArrayList<>(); - - for(PrismObject object: objects){ - referenceMap.put(object.getOid(), WebComponentUtil.getName(object)); - references.add(ObjectTypeUtil.createObjectRef(object, page.getPrismContext())); - - } - return references; - } catch (Exception e){ - result.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadPasswordPolicies").getString(), e); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load password policies", e); - } - - // TODO - show error somehow - // if(!result.isSuccess()){ - // getPageBase().showResult(result); - // } - - return null; - } - - public static String runTask(TaskType taskToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ - try { - ObjectDelta delta = DeltaFactory.Object.createAddDelta(taskToRun.asPrismObject()); - pageBase.getPrismContext().adopt(delta); - pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, - operationalTask, parentResult); - parentResult.recordInProgress(); - parentResult.setBackgroundTaskOid(delta.getOid()); - pageBase.showResult(parentResult); - return delta.getOid(); - } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException - | ExpressionEvaluationException | CommunicationException | ConfigurationException - | PolicyViolationException | SecurityViolationException e) { - // TODO Auto-generated catch block -// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); - parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); - return null; - } - - } - - public static void runTask(Collection tasksToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ -// try { - - for (TaskType taskToRun : tasksToRun){ - runTask(tasksToRun, operationalTask, parentResult, pageBase); - } - -// } -// ObjectDelta delta = ObjectDelta.createAddDelta(taskToRun.asPrismObject()); -// pageBase.getPrismContext().adopt(delta); -// pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, -// operationalTask, parentResult); -// parentResult.recordInProgress(); -// parentResult.setBackgroundTaskOid(delta.getOid()); -// pageBase.showResult(parentResult); -// return delta.getOid(); -// } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException -// | ExpressionEvaluationException | CommunicationException | ConfigurationException -// | PolicyViolationException | SecurityViolationException e) { -// // TODO Auto-generated catch block -//// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); -// parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); -// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); -// return null; -// } - - } - - public static PrismObject loadObject(PrismReferenceValue objectRef, QName expectedTargetType, PageBase pageBase, Task task, OperationResult result) { - if (objectRef == null) { - return null; - } - - if (QNameUtil.match(expectedTargetType, objectRef.getTargetType())) { - Class type = pageBase.getPrismContext().getSchemaRegistry().determineClassForType(objectRef.getTargetType()); - PrismObject resourceType = WebModelServiceUtils.loadObject(type, objectRef.getOid(), GetOperationOptions.createNoFetchCollection(), pageBase, task, result); - return resourceType; - } - - return null; - } - - @Nullable - public static PrismObject loadObject(ObjectReferenceType objectReference, - PageBase page, Task task, OperationResult result) { - Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); - return loadObject(type, objectReference.getOid(), null, page, task, result); - } - - @Nullable - public static PrismObject loadObject(Class type, String oid, - PageBase page, Task task, OperationResult result) { - return loadObject(type, oid, null, page, task, result); - } - - @Nullable - public static PrismObject loadObject(Class type, String oid, - Collection> options, - PageBase page, Task task, OperationResult result) { - return loadObject(type, oid, options, true, page, task, result); - } - - @Nullable - public static PrismObject loadObject(Class type, String oid, - Collection> options, boolean allowNotFound, - PageBase page, Task task, OperationResult result) { - LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); - } else { - subResult = new OperationResult(OPERATION_LOAD_OBJECT); - } - PrismObject object = null; - try { - if (options == null) { - options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); - } else { - GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); - if (getOpts == null) { - options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); - } else { - getOpts.setResolveNames(Boolean.TRUE); - } - } - object = page.getModelService().getObject(type, oid, options, task, subResult); - } catch (AuthorizationException e) { - // Not authorized to access the object. This is probably caused by a reference that - // point to an object that the current user cannot read. This is no big deal. - // Just do not display that object. - subResult.recordHandledError(e); - LOGGER.debug("User {} is not authorized to read {} {}", - task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); - return null; - } catch (ObjectNotFoundException e) { - if (allowNotFound) { - // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. - subResult.recordHandledError(e); - LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); - return null; - } else { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), e); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", e); - } - } catch (Exception ex) { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - } finally { - subResult.computeStatus(); - } - // TODO reconsider this part: until recently, the condition was always 'false' - if (WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Loaded {} with result {}", object, subResult); - - return object; - } - - //TODO consider using modelServiceLocator instead of PageBase in other methods.. Do we even need it? What about showResult? Should it be - // here or directly in the page? Consider usability and readabiltiy - @Nullable - public static PrismObject loadObject(ObjectReferenceType objectReference, - ModelServiceLocator page, Task task, OperationResult result) { - Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); - String oid = objectReference.getOid(); - Collection> options = null; - LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); - } else { - subResult = new OperationResult(OPERATION_LOAD_OBJECT); - } - PrismObject object = null; - try { - if (options == null) { - options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); - } else { - GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); - if (getOpts == null) { - options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); - } else { - getOpts.setResolveNames(Boolean.TRUE); - } - } - object = page.getModelService().getObject(type, oid, options, task, subResult); - } catch (AuthorizationException e) { - // Not authorized to access the object. This is probably caused by a reference that - // point to an object that the current user cannot read. This is no big deal. - // Just do not display that object. - subResult.recordHandledError(e); - LOGGER.debug("User {} is not authorized to read {} {}", - task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); - return null; - } catch (ObjectNotFoundException e) { - // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. - subResult.recordHandledError(e); - LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); - return null; - - } catch (Exception ex) { - subResult.recordFatalError("WebModelUtils.couldntLoadObject", ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - } finally { - subResult.computeStatus(); - } - // TODO reconsider this part: until recently, the condition was always 'false' - if (WebComponentUtil.showResultInPage(subResult)) { - if (page instanceof PageBase) { - ((PageBase)page).showResult(subResult); - } - } - - LOGGER.debug("Loaded {} with result {}", object, subResult); - - return object; - } - - public static boolean isNoFetch(Collection> options) { - if (options == null) { - return false; - } - GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); - if (rootOptions == null) { - return false; - } - return GetOperationOptions.isNoFetch(rootOptions); - } - - @NotNull - public static List> searchObjects( - Class type, ObjectQuery query, OperationResult result, PageBase page) { - return searchObjects(type, query, null, result, page, null); - } - - @NotNull - public static List> searchObjects(Class type, ObjectQuery query, - Collection> options, - OperationResult result, PageBase page) { - return searchObjects(type, query, options, result, page, null); - } - - @NotNull - public static List> searchObjects( - Class type, ObjectQuery query, Collection> options, - OperationResult result, PageBase page, PrismObject principal) { - LOGGER.debug("Searching {} with oid {}, options {}", type.getSimpleName(), query, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_SEARCH_OBJECTS); - } else { - subResult = new OperationResult(OPERATION_SEARCH_OBJECTS); - } - List> objects = new ArrayList<>(); - try { - Task task = createSimpleTask(subResult.getOperation(), principal, page.getTaskManager()); - List> list = page.getModelService().searchObjects(type, query, options, task, subResult); - if (list != null) { - objects.addAll(list); - } - } catch (Exception ex) { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntSearchObjects").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't search objects", ex); - } finally { - subResult.computeStatus(); - } - - if (result == null && WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Loaded ({}) with result {}", objects.size(), subResult); - - return objects; - } - - public static int countObjects(Class type, ObjectQuery query, PageBase page) { - LOGGER.debug("Count object: type => {}, query => {}", type, query); - Task task = page.createSimpleTask(OPERATION_COUNT_OBJECT); - OperationResult parentResult = new OperationResult(OPERATION_COUNT_OBJECT); - int count = 0; - try { - count = page.getModelService().countObjects(type, query, null, task, parentResult); - } catch (SchemaException | ObjectNotFoundException | SecurityViolationException - | ConfigurationException | CommunicationException | ExpressionEvaluationException ex) { - parentResult.recordFatalError(page.createStringResource("WebModelUtils.couldntCountObjects").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't count objects", ex); - } - - LOGGER.debug("Count objects with result {}", parentResult); - return count; - } - - public static void deleteObject(Class type, String oid, OperationResult result, - PageBase page) { - deleteObject(type, oid, null, result, page, null); - } - - public static void deleteObject(Class type, String oid, ModelExecuteOptions options, - OperationResult result, PageBase page) { - deleteObject(type, oid, options, result, page, null); - } - - public static void deleteObject(Class type, String oid, ModelExecuteOptions options, - OperationResult result, PageBase page, - PrismObject principal) { - LOGGER.debug("Deleting {} with oid {}, options {}", type.getSimpleName(), oid, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_DELETE_OBJECT); - } else { - subResult = new OperationResult(OPERATION_DELETE_OBJECT); - } - try { - Task task = createSimpleTask(result.getOperation(), principal, page.getTaskManager()); - - ObjectDelta delta = page.getPrismContext().deltaFactory().object().create(type, ChangeType.DELETE); - delta.setOid(oid); - - page.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), options, task, subResult); - } catch (Exception ex) { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntDeleteObject").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete object", ex); - } finally { - subResult.computeStatus(); - } - - if (result == null && WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Deleted with result {}", result); - } - - public static Collection> createOptionsForParentOrgRefs(GetOperationOptionsBuilder builder) { - return builder - .item(ObjectType.F_PARENT_ORG_REF).retrieve() - .build(); - } - - public static void save(ObjectDelta delta, OperationResult result, PageBase page) { - save(delta, result, null, page); - } - - public static void save(ObjectDelta delta, OperationResult result, Task task, PageBase page) { - save(delta, null, result, task, page); - } - - public static void save(ObjectDelta delta, ModelExecuteOptions options, OperationResult result, Task task, PageBase page) { - save(WebComponentUtil.createDeltaCollection(delta), options, result, task, page); - } - - - public static void save(Collection> deltas, ModelExecuteOptions options, - OperationResult result, Task task, PageBase page) { - LOGGER.debug("Saving deltas {}, options {}", deltas, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_SAVE_OBJECT); - } else { - subResult = new OperationResult(OPERATION_SAVE_OBJECT); - } - - try { - if (task == null) { - task = page.createSimpleTask(result.getOperation()); - } - - page.getModelService().executeChanges(deltas, options, task, result); - } catch (Exception ex) { - subResult.recordFatalError(ex.getMessage()); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save object", ex); - } finally { - subResult.computeStatus(); - } - - if (result == null && WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Saved with result {}", subResult); - } - - public static ObjectDelta createActivationAdminStatusDelta( - Class type, String oid, boolean enabled, PrismContext context) { - - ItemPath path = SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; - ActivationStatusType status = enabled ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED; - ObjectDelta objectDelta = context.deltaFactory().object().createModificationReplaceProperty(type, oid, path, - status); - - return objectDelta; - } - - public static FocusType getLoggedInFocus() { - MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - Validate.notNull(principal, "No principal"); - if (principal.getFocus() == null) { - throw new IllegalArgumentException("No focus in principal: " + principal); - } - return principal.getFocus(); - } - - public static String getLoggedInFocusOid() { - MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - Validate.notNull(principal, "No principal"); - if (principal.getOid() == null) { - throw new IllegalArgumentException("No OID in principal: "+principal); - } - return principal.getOid(); - } - - public static Locale getLocale() { - return getLocale(null); - } - - public static Locale getLocale(FocusType focus) { - MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - Locale locale = null; - if (principal != null) { - if (focus == null) { - PrismObject focusPrismObject = principal.getFocus().asPrismObject(); - focus = focusPrismObject == null ? null : focusPrismObject.asObjectable(); - } - if (focus != null && focus.getPreferredLanguage() != null && - !focus.getPreferredLanguage().trim().equals("")) { - try { - locale = LocaleUtils.toLocale(focus.getPreferredLanguage()); - } catch (Exception ex) { - LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage()); - } - } - if (locale != null && MidPointApplication.containsLocale(locale)) { - return locale; - } else { - String userLocale = focus != null ? focus.getLocale() : null; - try { - locale = userLocale == null ? null : LocaleUtils.toLocale(userLocale); - } catch (Exception ex) { - LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage()); - } - if (locale != null && MidPointApplication.containsLocale(locale)) { - return locale; - } else { - //session in tests is null - if (ThreadContext.getSession() == null) { - return MidPointApplication.getDefaultLocale(); - } - - locale = Session.get().getLocale(); - if (locale == null || !MidPointApplication.containsLocale(locale)) { - //default locale for web application - return MidPointApplication.getDefaultLocale(); - } - return locale; - } - } - } - return MidPointApplication.getDefaultLocale(); - } - - public static TimeZone getTimezone() { - return getTimezone(null); - } - - public static TimeZone getTimezone(FocusType focus) { - GuiProfiledPrincipal principal = SecurityUtils.getPrincipalUser(); - if (principal != null && focus == null) { - focus = principal.getFocus(); - } - String timeZone; - - if (focus != null && StringUtils.isNotEmpty(focus.getTimezone())) { - timeZone = focus.getTimezone(); - } else { - timeZone = principal != null && principal.getCompiledGuiProfile() != null ? - principal.getCompiledGuiProfile().getDefaultTimezone() : ""; - } - try { - if (timeZone != null) { - return TimeZone.getTimeZone(timeZone); - } - } catch (Exception ex){ - LOGGER.debug("Error occurred while getting user time zone, " + ex.getMessage()); - } - return null; - } - - public static Task createSimpleTask(String operation, PrismObject owner, TaskManager manager) { - return createSimpleTask(operation, null, owner, manager); - } - - public static Task createSimpleTask(String operation, String channel, PrismObject owner, TaskManager manager) { - Task task = manager.createTaskInstance(operation); - - if (owner == null) { - MidPointPrincipal user = SecurityUtils.getPrincipalUser(); - if (user == null) { - throw new RestartResponseException(PageLogin.class); - } else { - owner = user.getFocus().asPrismObject(); - } - } - - task.setOwner(owner); - if (channel == null) { - task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI); - } else { - task.setChannel(channel); - } - - return task; - } - - public static PrismObject reconstructObject(Class type, - String oid, String eventIdentifier, Task task, OperationResult result){ - try { - MidPointApplication application = (MidPointApplication) MidPointApplication.get(); - return application.getAuditService().reconstructObject(type, oid, eventIdentifier, task, result); - } catch (Exception ex){ - LOGGER.debug("Error occurred while reconsructing the object, " + ex.getMessage()); - } - return null; - } - - public static Collection> createLookupTableRetrieveOptions(SchemaHelper schemaHelper) { - return schemaHelper.getOperationOptionsBuilder() - .item(LookupTableType.F_ROW) - .retrieveQuery() - .asc(LookupTableRowType.F_LABEL) - .end() - .build(); - } - - public static ActivationStatusType getAssignmentEffectiveStatus(String lifecycleStatus, ActivationType activationType, PageBase pageBase){ - return pageBase.getModelInteractionService().getAssignmentEffectiveStatus(lifecycleStatus, activationType); - } - - public static void assumePowerOfAttorney(PrismObject donor, - ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { - Task task = taskManager.createTaskInstance(); - OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_ASSUME_POWER_OF_ATTORNEY); - - try { - modelInteractionService.assumePowerOfAttorney(donor, task, result); - } catch (CommonException ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't assume power of attorney", ex); - result.recordFatalError("WebModelUtils.couldntAssumePowerAttorney", ex); - } finally { - result.computeStatusIfUnknown(); - } - } - - public static void dropPowerOfAttorney(ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { - Task task = taskManager.createTaskInstance(); - OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_DROP_POWER_OF_ATTORNEY); - - try { - modelInteractionService.dropPowerOfAttorney(task, result); - } catch (CommonException ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't drop power of attorney", ex); - result.recordFatalError("WebModelUtils.couldntDropPowerAttorney", ex); - } finally { - result.computeStatusIfUnknown(); - } - } - - public static boolean isEnableExperimentalFeature(Task task, ModelServiceLocator pageBase) { - OperationResult result = task.getResult(); - - ModelInteractionService mInteractionService = pageBase.getModelInteractionService(); - - CompiledGuiProfile adminGuiConfig = null; - try { - adminGuiConfig = mInteractionService.getCompiledGuiProfile(task, result); - result.recomputeStatus(); - result.recordSuccessIfUnknown(); - } catch (Exception e) { - LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); - result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); - - } - - if (adminGuiConfig == null) { - return false; - } - - return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); - - } - - public static boolean isEnableExperimentalFeature(ModelInteractionService modelInteractionService, Task task, OperationResult result) { - CompiledGuiProfile adminGuiConfig = null; - try { - adminGuiConfig = modelInteractionService.getCompiledGuiProfile(task, result); - result.recomputeStatus(); - result.recordSuccessIfUnknown(); - } catch (Exception e) { - LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); - result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); - - } - - if (adminGuiConfig == null) { - return false; - } - - return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); - - } - - public static boolean isEnableExperimentalFeature(ModelServiceLocator pageBase) { - Task task = pageBase.createSimpleTask("Load admin gui config"); - return isEnableExperimentalFeature(task, pageBase); - - } - - public static AccessCertificationConfigurationType getCertificationConfiguration(PageBase pageBase) { - OperationResult result = new OperationResult(WebModelServiceUtils.class.getName() + ".getCertificationConfiguration"); - try { - return pageBase.getModelInteractionService().getCertificationConfiguration(result); - } catch (Throwable t) { - LoggingUtils.logUnexpectedException(LOGGER, "Cannot load certification configuration", t); - return null; - } - } - - public static String translateMessage(OperationResult result, ModelServiceLocator page) { - LocalizationService service = page.getLocalizationService(); - Locale locale = page.getLocale(); - - return service.translate(result.getUserFriendlyMessage(), locale); - } - - public static boolean isPostAuthenticationEnabled(TaskManager taskManager, ModelInteractionService modelInteractionService) { - MidPointPrincipal midpointPrincipal = SecurityUtils.getPrincipalUser(); - if (midpointPrincipal != null) { - FocusType focus = midpointPrincipal.getFocus(); - Task task = taskManager.createTaskInstance(OPERATION_LOAD_FLOW_POLICY); - OperationResult parentResult = new OperationResult(OPERATION_LOAD_FLOW_POLICY); - RegistrationsPolicyType registrationPolicyType; - try { - registrationPolicyType = modelInteractionService.getFlowPolicy(focus.asPrismObject(), task, parentResult); - if (registrationPolicyType == null) { - return false; - } - SelfRegistrationPolicyType postAuthenticationPolicy = registrationPolicyType.getPostAuthentication(); - if (postAuthenticationPolicy == null) { - return false; - } - String requiredLifecycleState = postAuthenticationPolicy.getRequiredLifecycleState(); - if (StringUtils.isNotBlank(requiredLifecycleState) && requiredLifecycleState.equals(focus.getLifecycleState())) { - return true; - } - } catch (CommonException e) { - LoggingUtils.logException(LOGGER, "Cannot determine post authentication policies", e); - } - } - return false; - } - - public static PrismObject loadSystemConfigurationAsPrismObject(PageBase pageBase, Task task, OperationResult result) { - PrismObject systemConfig = loadObject( - SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, - pageBase, task, result); - - return systemConfig; - } - -} +/* + * Copyright (c) 2010-2019 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.gui.api.util; + +import static com.evolveum.midpoint.schema.GetOperationOptions.createNoFetchCollection; + +import java.util.*; + +import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.LocaleUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.Session; +import org.apache.wicket.ThreadContext; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.evolveum.midpoint.common.LocalizationService; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.api.ModelInteractionService; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismObjectDefinition; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.GetOperationOptionsBuilder; +import com.evolveum.midpoint.schema.SchemaHelper; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.security.api.MidPointPrincipal; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.task.api.TaskManager; +import com.evolveum.midpoint.util.exception.AuthorizationException; +import com.evolveum.midpoint.util.exception.CommonException; +import com.evolveum.midpoint.util.exception.CommunicationException; +import com.evolveum.midpoint.util.exception.ConfigurationException; +import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; +import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; +import com.evolveum.midpoint.util.exception.ObjectNotFoundException; +import com.evolveum.midpoint.util.exception.PolicyViolationException; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.page.login.PageLogin; +import com.evolveum.midpoint.web.security.MidPointApplication; +import com.evolveum.midpoint.web.security.util.SecurityUtils; +import com.evolveum.prism.xml.ns._public.types_3.EvaluationTimeType; + +import javax.xml.namespace.QName; + +/** + * Utility class that contains methods that interact with ModelService and other + * midPoint components. + * + * @author lazyman + */ +public class WebModelServiceUtils { + + private static final Trace LOGGER = TraceManager.getTrace(WebModelServiceUtils.class); + + private static final String DOT_CLASS = WebModelServiceUtils.class.getName() + "."; + private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; + private static final String OPERATION_DELETE_OBJECT = DOT_CLASS + "deleteObject"; + private static final String OPERATION_SEARCH_OBJECTS = DOT_CLASS + "searchObjects"; + private static final String OPERATION_SAVE_OBJECT = DOT_CLASS + "saveObject"; + private static final String OPERATION_LOAD_OBJECT_REFS = DOT_CLASS + "loadObjectReferences"; + private static final String OPERATION_COUNT_OBJECT = DOT_CLASS + "countObjects"; + private static final String OPERATION_ASSUME_POWER_OF_ATTORNEY = DOT_CLASS + "assumePowerOfAttorney"; + private static final String OPERATION_DROP_POWER_OF_ATTORNEY = DOT_CLASS + "dropPowerOfAttorney"; + private static final String OPERATION_GET_SYSTEM_CONFIG = DOT_CLASS + "getSystemConfiguration"; + private static final String OPERATION_LOAD_FLOW_POLICY = DOT_CLASS + "loadFlowPolicy"; + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page) { + return resolveReferenceName(ref, page, false); + } + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, boolean translate) { + Task task = page.createSimpleTask(WebModelServiceUtils.class.getName() + ".resolveReferenceName"); + return resolveReferenceName(ref, page, task, task.getResult(), translate); + } + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result) { + return resolveReferenceName(ref, page, task, result, false); + } + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result, boolean translate) { + if (ref == null) { + return null; + } + if (ref.getTargetName() != null) { + return translate ? page.getLocalizationService().translate(ref.getTargetName().toPolyString(), page.getLocale(), true) + : ref.getTargetName().getOrig(); + } + if (StringUtils.isEmpty(ref.getOid()) || ref.getType() == null){ + return null; + } + PrismObject object = resolveReferenceNoFetch(ref, page, task, result); + if (object == null) { + return ref.getOid(); + } else { + ref.asReferenceValue().setObject(object); + return WebComponentUtil.getName(object, translate); + } + } + + public static PrismObject resolveReferenceNoFetch(ObjectReferenceType reference, PageBase page, Task task, OperationResult result) { + if (reference == null) { + return null; + } + if (reference.asReferenceValue().getObject() != null) { + return reference.asReferenceValue().getObject(); + } + PrismContext prismContext = page.getPrismContext(); + if (reference.getType() == null) { + LOGGER.error("No type in {}", reference); + return null; + } + PrismObjectDefinition definition = prismContext.getSchemaRegistry().findObjectDefinitionByType(reference.getType()); + if (definition == null) { + LOGGER.error("No definition for {} was found", reference.getType()); + return null; + } + if (reference.getOid() == null) { + if (reference.getResolutionTime() == EvaluationTimeType.RUN) { + // Runtime reference resolution. Ignore it for now. Later we maybe would want to resolve it here. + // But it may resolve to several objects .... + return null; + } else { + LOGGER.error("Null OID in reference {}", reference); + // Throw an exception instead? Maybe not. We want GUI to be robust. + return null; + } + } + return loadObject(definition.getCompileTimeClass(), reference.getOid(), createNoFetchCollection(), page, task, result); + } + + public static List createObjectReferenceList(Class type, PageBase page, Map referenceMap){ + referenceMap.clear(); + + OperationResult result = new OperationResult(OPERATION_LOAD_OBJECT_REFS); +// Task task = page.createSimpleTask(OPERATION_LOAD_PASSWORD_POLICIES); + + try { + List> objects = searchObjects(type, null, result, page); + result.recomputeStatus(); + List references = new ArrayList<>(); + + for(PrismObject object: objects){ + referenceMap.put(object.getOid(), WebComponentUtil.getName(object)); + references.add(ObjectTypeUtil.createObjectRef(object, page.getPrismContext())); + + } + return references; + } catch (Exception e){ + result.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadPasswordPolicies").getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load password policies", e); + } + + // TODO - show error somehow + // if(!result.isSuccess()){ + // getPageBase().showResult(result); + // } + + return null; + } + + public static String runTask(TaskType taskToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ + try { + ObjectDelta delta = DeltaFactory.Object.createAddDelta(taskToRun.asPrismObject()); + pageBase.getPrismContext().adopt(delta); + pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, + operationalTask, parentResult); + parentResult.recordInProgress(); + parentResult.setBackgroundTaskOid(delta.getOid()); + pageBase.showResult(parentResult); + return delta.getOid(); + } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException + | ExpressionEvaluationException | CommunicationException | ConfigurationException + | PolicyViolationException | SecurityViolationException e) { + // TODO Auto-generated catch block +// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); + parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); + return null; + } + + } + + public static void runTask(Collection tasksToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ +// try { + + for (TaskType taskToRun : tasksToRun){ + runTask(tasksToRun, operationalTask, parentResult, pageBase); + } + +// } +// ObjectDelta delta = ObjectDelta.createAddDelta(taskToRun.asPrismObject()); +// pageBase.getPrismContext().adopt(delta); +// pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, +// operationalTask, parentResult); +// parentResult.recordInProgress(); +// parentResult.setBackgroundTaskOid(delta.getOid()); +// pageBase.showResult(parentResult); +// return delta.getOid(); +// } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException +// | ExpressionEvaluationException | CommunicationException | ConfigurationException +// | PolicyViolationException | SecurityViolationException e) { +// // TODO Auto-generated catch block +//// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); +// parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); +// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); +// return null; +// } + + } + + public static PrismObject loadObject(PrismReferenceValue objectRef, QName expectedTargetType, PageBase pageBase, Task task, OperationResult result) { + if (objectRef == null) { + return null; + } + + if (QNameUtil.match(expectedTargetType, objectRef.getTargetType())) { + Class type = pageBase.getPrismContext().getSchemaRegistry().determineClassForType(objectRef.getTargetType()); + PrismObject resourceType = WebModelServiceUtils.loadObject(type, objectRef.getOid(), GetOperationOptions.createNoFetchCollection(), pageBase, task, result); + return resourceType; + } + + return null; + } + + @Nullable + public static PrismObject loadObject(ObjectReferenceType objectReference, + PageBase page, Task task, OperationResult result) { + Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); + return loadObject(type, objectReference.getOid(), null, page, task, result); + } + + @Nullable + public static PrismObject loadObject(Class type, String oid, + PageBase page, Task task, OperationResult result) { + return loadObject(type, oid, null, page, task, result); + } + + @Nullable + public static PrismObject loadObject(Class type, String oid, + Collection> options, + PageBase page, Task task, OperationResult result) { + return loadObject(type, oid, options, true, page, task, result); + } + + @Nullable + public static PrismObject loadObject(Class type, String oid, + Collection> options, boolean allowNotFound, + PageBase page, Task task, OperationResult result) { + LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); + } else { + subResult = new OperationResult(OPERATION_LOAD_OBJECT); + } + PrismObject object = null; + try { + if (options == null) { + options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); + } else { + GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); + if (getOpts == null) { + options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); + } else { + getOpts.setResolveNames(Boolean.TRUE); + } + } + object = page.getModelService().getObject(type, oid, options, task, subResult); + } catch (AuthorizationException e) { + // Not authorized to access the object. This is probably caused by a reference that + // point to an object that the current user cannot read. This is no big deal. + // Just do not display that object. + subResult.recordHandledError(e); + LOGGER.debug("User {} is not authorized to read {} {}", + task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); + return null; + } catch (ObjectNotFoundException e) { + if (allowNotFound) { + // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. + subResult.recordHandledError(e); + LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); + return null; + } else { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", e); + } + } catch (Exception ex) { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + } finally { + subResult.computeStatus(); + } + // TODO reconsider this part: until recently, the condition was always 'false' + if (WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Loaded {} with result {}", object, subResult); + + return object; + } + + //TODO consider using modelServiceLocator instead of PageBase in other methods.. Do we even need it? What about showResult? Should it be + // here or directly in the page? Consider usability and readabiltiy + @Nullable + public static PrismObject loadObject(ObjectReferenceType objectReference, + ModelServiceLocator page, Task task, OperationResult result) { + Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); + String oid = objectReference.getOid(); + Collection> options = null; + LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); + } else { + subResult = new OperationResult(OPERATION_LOAD_OBJECT); + } + PrismObject object = null; + try { + if (options == null) { + options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); + } else { + GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); + if (getOpts == null) { + options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); + } else { + getOpts.setResolveNames(Boolean.TRUE); + } + } + object = page.getModelService().getObject(type, oid, options, task, subResult); + } catch (AuthorizationException e) { + // Not authorized to access the object. This is probably caused by a reference that + // point to an object that the current user cannot read. This is no big deal. + // Just do not display that object. + subResult.recordHandledError(e); + LOGGER.debug("User {} is not authorized to read {} {}", + task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); + return null; + } catch (ObjectNotFoundException e) { + // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. + subResult.recordHandledError(e); + LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); + return null; + + } catch (Exception ex) { + subResult.recordFatalError("WebModelUtils.couldntLoadObject", ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + } finally { + subResult.computeStatus(); + } + // TODO reconsider this part: until recently, the condition was always 'false' + if (WebComponentUtil.showResultInPage(subResult)) { + if (page instanceof PageBase) { + ((PageBase)page).showResult(subResult); + } + } + + LOGGER.debug("Loaded {} with result {}", object, subResult); + + return object; + } + + public static boolean isNoFetch(Collection> options) { + if (options == null) { + return false; + } + GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); + if (rootOptions == null) { + return false; + } + return GetOperationOptions.isNoFetch(rootOptions); + } + + @NotNull + public static List> searchObjects( + Class type, ObjectQuery query, OperationResult result, PageBase page) { + return searchObjects(type, query, null, result, page, null); + } + + @NotNull + public static List> searchObjects(Class type, ObjectQuery query, + Collection> options, + OperationResult result, PageBase page) { + return searchObjects(type, query, options, result, page, null); + } + + @NotNull + public static List> searchObjects( + Class type, ObjectQuery query, Collection> options, + OperationResult result, PageBase page, PrismObject principal) { + LOGGER.debug("Searching {} with oid {}, options {}", type.getSimpleName(), query, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_SEARCH_OBJECTS); + } else { + subResult = new OperationResult(OPERATION_SEARCH_OBJECTS); + } + List> objects = new ArrayList<>(); + try { + Task task = createSimpleTask(subResult.getOperation(), principal, page.getTaskManager()); + List> list = page.getModelService().searchObjects(type, query, options, task, subResult); + if (list != null) { + objects.addAll(list); + } + } catch (Exception ex) { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntSearchObjects").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't search objects", ex); + } finally { + subResult.computeStatus(); + } + + if (result == null && WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Loaded ({}) with result {}", objects.size(), subResult); + + return objects; + } + + public static int countObjects(Class type, ObjectQuery query, PageBase page) { + LOGGER.debug("Count object: type => {}, query => {}", type, query); + Task task = page.createSimpleTask(OPERATION_COUNT_OBJECT); + OperationResult parentResult = new OperationResult(OPERATION_COUNT_OBJECT); + int count = 0; + try { + count = page.getModelService().countObjects(type, query, null, task, parentResult); + } catch (SchemaException | ObjectNotFoundException | SecurityViolationException + | ConfigurationException | CommunicationException | ExpressionEvaluationException ex) { + parentResult.recordFatalError(page.createStringResource("WebModelUtils.couldntCountObjects").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't count objects", ex); + } + + LOGGER.debug("Count objects with result {}", parentResult); + return count; + } + + public static void deleteObject(Class type, String oid, OperationResult result, + PageBase page) { + deleteObject(type, oid, null, result, page, null); + } + + public static void deleteObject(Class type, String oid, ModelExecuteOptions options, + OperationResult result, PageBase page) { + deleteObject(type, oid, options, result, page, null); + } + + public static void deleteObject(Class type, String oid, ModelExecuteOptions options, + OperationResult result, PageBase page, + PrismObject principal) { + LOGGER.debug("Deleting {} with oid {}, options {}", type.getSimpleName(), oid, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_DELETE_OBJECT); + } else { + subResult = new OperationResult(OPERATION_DELETE_OBJECT); + } + try { + Task task = createSimpleTask(result.getOperation(), principal, page.getTaskManager()); + + ObjectDelta delta = page.getPrismContext().deltaFactory().object().create(type, ChangeType.DELETE); + delta.setOid(oid); + + page.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), options, task, subResult); + } catch (Exception ex) { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntDeleteObject").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete object", ex); + } finally { + subResult.computeStatus(); + } + + if (result == null && WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Deleted with result {}", result); + } + + public static Collection> createOptionsForParentOrgRefs(GetOperationOptionsBuilder builder) { + return builder + .item(ObjectType.F_PARENT_ORG_REF).retrieve() + .build(); + } + + public static void save(ObjectDelta delta, OperationResult result, PageBase page) { + save(delta, result, null, page); + } + + public static void save(ObjectDelta delta, OperationResult result, Task task, PageBase page) { + save(delta, null, result, task, page); + } + + public static void save(ObjectDelta delta, ModelExecuteOptions options, OperationResult result, Task task, PageBase page) { + save(WebComponentUtil.createDeltaCollection(delta), options, result, task, page); + } + + + public static void save(Collection> deltas, ModelExecuteOptions options, + OperationResult result, Task task, PageBase page) { + LOGGER.debug("Saving deltas {}, options {}", deltas, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_SAVE_OBJECT); + } else { + subResult = new OperationResult(OPERATION_SAVE_OBJECT); + } + + try { + if (task == null) { + task = page.createSimpleTask(result.getOperation()); + } + + page.getModelService().executeChanges(deltas, options, task, result); + } catch (Exception ex) { + subResult.recordFatalError(ex.getMessage()); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save object", ex); + } finally { + subResult.computeStatus(); + } + + if (result == null && WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Saved with result {}", subResult); + } + + public static ObjectDelta createActivationAdminStatusDelta( + Class type, String oid, boolean enabled, PrismContext context) { + + ItemPath path = SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; + ActivationStatusType status = enabled ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED; + ObjectDelta objectDelta = context.deltaFactory().object().createModificationReplaceProperty(type, oid, path, + status); + + return objectDelta; + } + + public static FocusType getLoggedInFocus() { + MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); + Validate.notNull(principal, "No principal"); + if (principal.getFocus() == null) { + throw new IllegalArgumentException("No focus in principal: " + principal); + } + return principal.getFocus(); + } + + public static String getLoggedInFocusOid() { + MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); + Validate.notNull(principal, "No principal"); + if (principal.getOid() == null) { + throw new IllegalArgumentException("No OID in principal: "+principal); + } + return principal.getOid(); + } + +// public static Locale getLocale() { +// return getLocale(null); +// } + + public static Locale getLocale() { + MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); + if (principal == null) { + return MidPointApplication.getDefaultLocale(); + } + + Locale locale = null; + + F focus = (F) principal.getFocus(); + if (focus == null) { + return MidPointApplication.getDefaultLocale(); + } +// if (principal != null) { +//// if (focus == null) { +// PrismObject focusPrismObject = principal.getFocus().asPrismObject(); +// FocusType focus = focusPrismObject == null ? null : focusPrismObject.asObjectable(); +//// } + String prefLang = focus.getPreferredLanguage(); + if (StringUtils.isBlank(prefLang)) { + prefLang = focus.getLocale(); + } + + try { + locale = LocaleUtils.toLocale(prefLang); + } catch (Exception ex) { + LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage()); + } + + if (locale == null) { + if (ThreadContext.getSession() == null) { + return MidPointApplication.getDefaultLocale(); + } + + locale = Session.get().getLocale(); + } + + if (MidPointApplication.containsLocale(locale)) { + return locale; + } + + return MidPointApplication.getDefaultLocale(); + } + +// public static TimeZone getTimezone() { +// return getTimezone(null); +// } + + public static TimeZone getTimezone() { + GuiProfiledPrincipal principal = SecurityUtils.getPrincipalUser(); + + if (principal == null) { + return null; + } + + FocusType focus = principal.getFocus(); + + String timeZone; + if (focus == null || StringUtils.isEmpty(focus.getTimezone())) { + timeZone = principal.getCompiledGuiProfile().getDefaultTimezone(); + } else { + timeZone = focus.getTimezone(); + } + + if (timeZone == null) { + return null; + } + + try { + return TimeZone.getTimeZone(timeZone); + } catch (Exception ex){ + LOGGER.debug("Error occurred while getting user time zone, " + ex.getMessage()); + return null; + } + + } + + public static Task createSimpleTask(String operation, PrismObject owner, TaskManager manager) { + return createSimpleTask(operation, null, owner, manager); + } + + public static Task createSimpleTask(String operation, String channel, PrismObject owner, TaskManager manager) { + Task task = manager.createTaskInstance(operation); + + if (owner == null) { + MidPointPrincipal user = SecurityUtils.getPrincipalUser(); + if (user == null) { + throw new RestartResponseException(PageLogin.class); + } else { + owner = user.getFocus().asPrismObject(); + } + } + + task.setOwner(owner); + if (channel == null) { + task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI); + } else { + task.setChannel(channel); + } + + return task; + } + + public static PrismObject reconstructObject(Class type, + String oid, String eventIdentifier, Task task, OperationResult result){ + try { + MidPointApplication application = (MidPointApplication) MidPointApplication.get(); + return application.getAuditService().reconstructObject(type, oid, eventIdentifier, task, result); + } catch (Exception ex){ + LOGGER.debug("Error occurred while reconsructing the object, " + ex.getMessage()); + } + return null; + } + + public static Collection> createLookupTableRetrieveOptions(SchemaHelper schemaHelper) { + return schemaHelper.getOperationOptionsBuilder() + .item(LookupTableType.F_ROW) + .retrieveQuery() + .asc(LookupTableRowType.F_LABEL) + .end() + .build(); + } + + public static ActivationStatusType getAssignmentEffectiveStatus(String lifecycleStatus, ActivationType activationType, PageBase pageBase){ + return pageBase.getModelInteractionService().getAssignmentEffectiveStatus(lifecycleStatus, activationType); + } + + public static void assumePowerOfAttorney(PrismObject donor, + ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { + Task task = taskManager.createTaskInstance(); + OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_ASSUME_POWER_OF_ATTORNEY); + + try { + modelInteractionService.assumePowerOfAttorney(donor, task, result); + } catch (CommonException ex) { + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't assume power of attorney", ex); + result.recordFatalError("WebModelUtils.couldntAssumePowerAttorney", ex); + } finally { + result.computeStatusIfUnknown(); + } + } + + public static void dropPowerOfAttorney(ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { + Task task = taskManager.createTaskInstance(); + OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_DROP_POWER_OF_ATTORNEY); + + try { + modelInteractionService.dropPowerOfAttorney(task, result); + } catch (CommonException ex) { + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't drop power of attorney", ex); + result.recordFatalError("WebModelUtils.couldntDropPowerAttorney", ex); + } finally { + result.computeStatusIfUnknown(); + } + } + + public static boolean isEnableExperimentalFeature(Task task, ModelServiceLocator pageBase) { + OperationResult result = task.getResult(); + + ModelInteractionService mInteractionService = pageBase.getModelInteractionService(); + + CompiledGuiProfile adminGuiConfig = null; + try { + adminGuiConfig = mInteractionService.getCompiledGuiProfile(task, result); + result.recomputeStatus(); + result.recordSuccessIfUnknown(); + } catch (Exception e) { + LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); + result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); + + } + + if (adminGuiConfig == null) { + return false; + } + + return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); + + } + + public static boolean isEnableExperimentalFeature(ModelInteractionService modelInteractionService, Task task, OperationResult result) { + CompiledGuiProfile adminGuiConfig = null; + try { + adminGuiConfig = modelInteractionService.getCompiledGuiProfile(task, result); + result.recomputeStatus(); + result.recordSuccessIfUnknown(); + } catch (Exception e) { + LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); + result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); + + } + + if (adminGuiConfig == null) { + return false; + } + + return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); + + } + + public static boolean isEnableExperimentalFeature(ModelServiceLocator pageBase) { + Task task = pageBase.createSimpleTask("Load admin gui config"); + return isEnableExperimentalFeature(task, pageBase); + + } + + public static AccessCertificationConfigurationType getCertificationConfiguration(PageBase pageBase) { + OperationResult result = new OperationResult(WebModelServiceUtils.class.getName() + ".getCertificationConfiguration"); + try { + return pageBase.getModelInteractionService().getCertificationConfiguration(result); + } catch (Throwable t) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot load certification configuration", t); + return null; + } + } + + public static String translateMessage(OperationResult result, ModelServiceLocator page) { + LocalizationService service = page.getLocalizationService(); + Locale locale = page.getLocale(); + + return service.translate(result.getUserFriendlyMessage(), locale); + } + + public static boolean isPostAuthenticationEnabled(TaskManager taskManager, ModelInteractionService modelInteractionService) { + MidPointPrincipal midpointPrincipal = SecurityUtils.getPrincipalUser(); + if (midpointPrincipal != null) { + FocusType focus = midpointPrincipal.getFocus(); + Task task = taskManager.createTaskInstance(OPERATION_LOAD_FLOW_POLICY); + OperationResult parentResult = new OperationResult(OPERATION_LOAD_FLOW_POLICY); + RegistrationsPolicyType registrationPolicyType; + try { + registrationPolicyType = modelInteractionService.getFlowPolicy(focus.asPrismObject(), task, parentResult); + if (registrationPolicyType == null) { + return false; + } + SelfRegistrationPolicyType postAuthenticationPolicy = registrationPolicyType.getPostAuthentication(); + if (postAuthenticationPolicy == null) { + return false; + } + String requiredLifecycleState = postAuthenticationPolicy.getRequiredLifecycleState(); + if (StringUtils.isNotBlank(requiredLifecycleState) && requiredLifecycleState.equals(focus.getLifecycleState())) { + return true; + } + } catch (CommonException e) { + LoggingUtils.logException(LOGGER, "Cannot determine post authentication policies", e); + } + } + return false; + } + + public static PrismObject loadSystemConfigurationAsPrismObject(PageBase pageBase, Task task, OperationResult result) { + PrismObject systemConfig = loadObject( + SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, + pageBase, task, result); + + return systemConfig; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java new file mode 100644 index 00000000000..a8fb2c6caf6 --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.gui.impl.factory; + +import javax.annotation.PostConstruct; + +import org.apache.wicket.markup.html.panel.Panel; +import org.springframework.stereotype.Component; + +import com.evolveum.midpoint.gui.api.factory.AbstractGuiComponentFactory; +import com.evolveum.midpoint.gui.api.prism.ItemWrapper; +import com.evolveum.midpoint.gui.impl.prism.ExpressionWrapper; +import com.evolveum.midpoint.web.component.input.AssociationExpressionValuePanel; +import com.evolveum.midpoint.web.component.input.SimpleValueExpressionPanel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; + +@Component +public class AssociationAndExpressionPanelFactory extends AbstractGuiComponentFactory { + + @PostConstruct + public void register() { + getRegistry().addToRegistry(this); + } + + @Override + protected Panel getPanel(PrismPropertyPanelContext panelCtx) { + ExpressionWrapper expressionWrapper = (ExpressionWrapper) panelCtx.unwrapWrapperModel(); + + if (expressionWrapper.isAttributeExpression()) { + return new SimpleValueExpressionPanel(panelCtx.getComponentId(), panelCtx.getRealValueModel()); + } + + return new AssociationExpressionValuePanel(panelCtx.getComponentId(), panelCtx.getRealValueModel(), expressionWrapper.getConstruction()); + + } + + @Override + public boolean match(IW wrapper) { + if (wrapper == null) { + return false; + } + + if (!(wrapper instanceof ExpressionWrapper)) { + return false; + } + ExpressionWrapper expressionWrapper = (ExpressionWrapper) wrapper; + return expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression(); + } + + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java index 27c767708c1..81e1066a080 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java @@ -48,9 +48,6 @@ public int getOrder() { protected PrismPropertyWrapper createWrapper(PrismContainerValueWrapper parent, PrismProperty item, ItemStatus status) { - if (parent != null && parent.getParent() != null && QNameUtil.match(parent.getParent().getTypeName(), MappingType.COMPLEX_TYPE)) { - return super.createWrapper(parent, item, status); - } ExpressionWrapper propertyWrapper = new ExpressionWrapper(parent, item, status); getRegistry().registerWrapperPanel(item.getDefinition().getTypeName(), ExpressionPropertyPanel.class); return propertyWrapper; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java index 7aa67011657..9278e2e1930 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java @@ -84,7 +84,7 @@ private ItemStatus getStatus(I childItem) { public IW createWrapper(Item childItem, ItemStatus status, WrapperContext context) throws SchemaException { return createWrapper(null, (I) childItem, status, context); - }; + } private IW createWrapper(PrismContainerValueWrapper parent, I childItem, ItemStatus status, WrapperContext context) throws SchemaException { IW itemWrapper = createWrapper(parent, childItem, status); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java index 204411310a6..ac1a9604b90 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java @@ -1,302 +1,170 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.gui.impl.factory; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import javax.xml.namespace.QName; - -import org.apache.commons.collections4.CollectionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.ItemWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.registry.GuiComponentRegistry; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.*; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - -/** - * @author katka - */ -@Component -public class PrismObjectWrapperFactoryImpl extends PrismContainerWrapperFactoryImpl implements PrismObjectWrapperFactory { - - private static final Trace LOGGER = TraceManager.getTrace(PrismObjectWrapperFactoryImpl.class); - - private static final String DOT_CLASS = PrismObjectWrapperFactoryImpl.class.getName() + "."; - private static final String OPERATION_DETERMINE_VIRTUAL_CONTAINERS = DOT_CLASS + "determineVirtualContainers"; - - private static final QName VIRTUAL_CONTAINER_COMPLEX_TYPE = new QName("VirtualContainerType"); - private static final QName VIRTUAL_CONTAINER = new QName("virtualContainer"); - - @Autowired private GuiComponentRegistry registry; - @Autowired protected ModelInteractionService modelInteractionService; - - public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status, WrapperContext context) throws SchemaException { - - try { - applySecurityConstraints(object, context); - } catch (CommunicationException | ObjectNotFoundException | SecurityViolationException | ConfigurationException | ExpressionEvaluationException e) { - context.getResult().recordFatalError("Cannot create object wrapper for " + object + ". An error occurred: " + e.getMessage(), e); - throw new SchemaException(e.getMessage(), e); - } - if (context.getObjectStatus() == null) { - context.setObjectStatus(status); - } - - Collection virtualContainers = modelInteractionService.determineVirtualContainers(object, context.getTask(), context.getResult()); - context.setVirtualContainers(virtualContainers); - - PrismObjectWrapper objectWrapper = createObjectWrapper(object, status); - if (context.getReadOnly() != null) { - objectWrapper.setReadOnly(context.getReadOnly().booleanValue()); - } - context.setShowEmpty(ItemStatus.ADDED == status); - objectWrapper.setExpanded(true); - PrismContainerValueWrapper valueWrapper = createValueWrapper(objectWrapper, object.getValue(), ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); - objectWrapper.getValues().add(valueWrapper); - - registry.registerWrapperPanel(object.getDefinition().getTypeName(), PrismContainerPanel.class); - return objectWrapper; - - } - - @Override - public PrismObjectValueWrapper createContainerValueWrapper(PrismContainerWrapper objectWrapper, PrismContainerValue objectValue, ValueStatus status, WrapperContext context) { - return new PrismObjectValueWrapperImpl((PrismObjectWrapper) objectWrapper, (PrismObjectValue) objectValue, status); - } - - public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status) { - return new PrismObjectWrapperImpl(object, status); - } - - @Override - public PrismContainerValueWrapper createValueWrapper(PrismContainerWrapper parent, PrismContainerValue value, ValueStatus status, WrapperContext context) throws SchemaException { - PrismContainerValueWrapper objectValueWrapper = super.createValueWrapper(parent, value, status, context); - - if (CollectionUtils.isEmpty(context.getVirtualContainers())) { - return objectValueWrapper; - } - - for (VirtualContainersSpecificationType virtualContainer : context.getVirtualContainers()) { - - MutableComplexTypeDefinition mCtd = getPrismContext().definitionFactory().createComplexTypeDefinition(VIRTUAL_CONTAINER_COMPLEX_TYPE); - DisplayType display = virtualContainer.getDisplay(); - - //TODO: support full polystring -> translations could be defined directly there. - mCtd.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); - mCtd.setHelp(WebComponentUtil.getOrigStringFromPoly(display.getHelp())); - mCtd.setRuntimeSchema(true); - - MutablePrismContainerDefinition def = getPrismContext().definitionFactory().createContainerDefinition(VIRTUAL_CONTAINER, mCtd); - def.setMaxOccurs(1); - def.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); - def.setDynamic(true); - - ItemWrapperFactory factory = getRegistry().findWrapperFactory(def); - if (factory == null) { - LOGGER.warn("Cannot find factory for {}. Skipping wrapper creation.", def); - continue; - } - - WrapperContext ctx = context.clone(); - ctx.setVirtualItemSpecification(virtualContainer.getItem()); - ItemWrapper iw = factory.createWrapper(objectValueWrapper, def, ctx); - - if (iw == null) { - continue; - } - ((List) objectValueWrapper.getItems()).add(iw); - - } - - return objectValueWrapper; - } - -// private List determineVirtualContainers(PrismObject object, WrapperContext context) { -// -// OperationResult result = context.getResult().createMinorSubresult(OPERATION_DETERMINE_VIRTUAL_CONTAINERS); -// if (AssignmentHolderType.class.isAssignableFrom(object.getCompileTimeClass())) { -// -// try { -// ArchetypePolicyType archetypePolicyType = modelInteractionService.determineArchetypePolicy((PrismObject) object, result); -// if (archetypePolicyType != null) { -// ArchetypeAdminGuiConfigurationType archetyAdminGui = archetypePolicyType.getAdminGuiConfiguration(); -// if (archetyAdminGui != null) { -// GuiObjectDetailsPageType guiDetails = archetyAdminGui.getObjectDetails(); -// if (guiDetails != null) { -// return guiDetails.getContainer(); -// } -// } -// } -// } catch (SchemaException | ConfigurationException e) { -// LOGGER.error("Cannot determine virtual containers for {}, reason: {}", object, e.getMessage(), e); -// result.recordPartialError("Cannot determine virtual containers for " + object + ", reason: " + e.getMessage(), e); -// return null; -// } -// -// } -// -// QName objectType = object.getDefinition().getTypeName(); -// try { -// CompiledGuiProfile userProfile = modelInteractionService.getCompiledGuiProfile(context.getTask(), context.getResult()); -// GuiObjectDetailsSetType objectDetailsSetType = userProfile.getObjectDetails(); -// if (objectDetailsSetType == null) { -// result.recordSuccess(); -// return null; -// } -// List detailsPages = objectDetailsSetType.getObjectDetailsPage(); -// for (GuiObjectDetailsPageType detailsPage : detailsPages) { -// if (objectType == null) { -// LOGGER.trace("Object type is not known, skipping considering custom details page settings."); -// continue; -// } -// if (detailsPage.getType() == null) { -// LOGGER.trace("Object type for details page {} not know, skipping considering custom details page settings.", detailsPage); -// continue; -// } -// -// if (QNameUtil.match(objectType, detailsPage.getType())) { -// result.recordSuccess(); -// return detailsPage.getContainer(); -// } -// } -// result.recordSuccess(); -// return null; -// } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { -// LOGGER.error("Cannot determine virtual containers for {}, reason: {}", objectType, e.getMessage(), e); -// result.recordPartialError("Cannot determine virtual containers for " + objectType + ", reason: " + e.getMessage(), e); -// return null; -// } -// -// } - - /** - * @param object apply security constraint to the object, update wrapper context with additional information, e.g. shadow related attributes, ... - */ - protected void applySecurityConstraints(PrismObject object, WrapperContext context) throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { - AuthorizationPhaseType phase = context.getAuthzPhase(); - Task task = context.getTask(); - OperationResult result = context.getResult(); - -// ObjectReferenceType archetypesToBeAdded = null; -// if (AssignmentHolderType.class.isAssignableFrom(object.getCompileTimeClass())) { -// archetypesToBeAdded = listArchetypes((PrismObject) object); -// if (archetypesToBeAdded != null) { -// applyArchetypes((PrismObject) object, archetypesToBeAdded); -// } -// } - - try { - PrismObjectDefinition objectDef = modelInteractionService.getEditObjectDefinition(object, phase, task, result); - object.applyDefinition(objectDef, true); - } catch (SchemaException | ConfigurationException | ObjectNotFoundException | ExpressionEvaluationException - | CommunicationException | SecurityViolationException e) { - throw e; - } -// finally { -// if (archetypesToBeAdded != null) { -// cleanupArchetypesToBeAdded((PrismObject) object, archetypesToBeAdded); -// } -// } - - } - - private void applyArchetypes(PrismObject object, ObjectReferenceType ref) throws SchemaException { - PrismReference archetypeRef = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF); - - if (archetypeRef == null) { - archetypeRef = object.findOrCreateReference(AssignmentHolderType.F_ARCHETYPE_REF); - } - - if (CollectionUtils.isNotEmpty(archetypeRef.getValues())) { - throw new SchemaException("Cannot apply new archetype to the object with already assigned archetype."); - } - - archetypeRef.getValues().add(ref.asReferenceValue()); - } - - private void cleanupArchetypesToBeAdded(PrismObject object, ObjectReferenceType ref) throws SchemaException { - //Now we expect thet object can have just one archetyperef, so if something was added, we just remove it. - - PrismReference archetype = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF); - if (archetype == null) { - return; - } - - if (archetype.getValues() != null && archetype.getValues().size() > 1) { - throw new SchemaException("More then one archetype ref found, but this is not supported."); - } - - object.removeReference(AssignmentHolderType.F_ARCHETYPE_REF); - } - - private ObjectReferenceType listArchetypes(PrismObject object) throws SchemaException { - PrismContainer assignmentContainer = object.findContainer(AssignmentHolderType.F_ASSIGNMENT); - Collection assignments = null; - if (assignmentContainer != null) { - assignments = assignmentContainer.getRealValues(); - } - - if (CollectionUtils.isEmpty(assignments)) { - return null; - } - - List archetypeAssignments = assignments.stream().filter(a -> a.getTargetRef() != null && QNameUtil.match(ArchetypeType.COMPLEX_TYPE, a.getTargetRef().getType())).collect(Collectors.toList()); - - if (archetypeAssignments.size() > 1) { - throw new SchemaException("More then one archetype assignment not supported."); - } - - if (CollectionUtils.isEmpty(archetypeAssignments)) { - return null; - } - - AssignmentType archetypeAssignment = archetypeAssignments.iterator().next(); - - PrismReference existingArchetypeRefs = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF); - if (existingArchetypeRefs == null || CollectionUtils.isEmpty(existingArchetypeRefs.getRealValues())) { - return archetypeAssignment.getTargetRef(); - } - - return null; - - } - - @Override - public boolean match(ItemDefinition def) { - return def instanceof PrismObjectDefinition; - } - - @Override - @PostConstruct - public void register() { - registry.addToRegistry(this); - } - - @Override - public int getOrder() { - return 100; - } - -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.gui.impl.factory; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import javax.xml.namespace.QName; + +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.ItemWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.registry.GuiComponentRegistry; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.model.api.ModelInteractionService; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +/** + * @author katka + */ +@Component +public class PrismObjectWrapperFactoryImpl extends PrismContainerWrapperFactoryImpl implements PrismObjectWrapperFactory { + + private static final Trace LOGGER = TraceManager.getTrace(PrismObjectWrapperFactoryImpl.class); + + private static final String DOT_CLASS = PrismObjectWrapperFactoryImpl.class.getName() + "."; + + private static final QName VIRTUAL_CONTAINER_COMPLEX_TYPE = new QName("VirtualContainerType"); + private static final QName VIRTUAL_CONTAINER = new QName("virtualContainer"); + + @Autowired private GuiComponentRegistry registry; + @Autowired protected ModelInteractionService modelInteractionService; + + public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status, WrapperContext context) throws SchemaException { + + try { + applySecurityConstraints(object, context); + } catch (CommunicationException | ObjectNotFoundException | SecurityViolationException | ConfigurationException | ExpressionEvaluationException e) { + context.getResult().recordFatalError("Cannot create object wrapper for " + object + ". An error occurred: " + e.getMessage(), e); + throw new SchemaException(e.getMessage(), e); + } + if (context.getObjectStatus() == null) { + context.setObjectStatus(status); + } + + Collection virtualContainers = modelInteractionService.determineVirtualContainers(object, context.getTask(), context.getResult()); + context.setVirtualContainers(virtualContainers); + + PrismObjectWrapper objectWrapper = createObjectWrapper(object, status); + if (context.getReadOnly() != null) { + objectWrapper.setReadOnly(context.getReadOnly().booleanValue()); + } + context.setShowEmpty(ItemStatus.ADDED == status); + objectWrapper.setExpanded(true); + PrismContainerValueWrapper valueWrapper = createValueWrapper(objectWrapper, object.getValue(), ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); + objectWrapper.getValues().add(valueWrapper); + + registry.registerWrapperPanel(object.getDefinition().getTypeName(), PrismContainerPanel.class); + return objectWrapper; + + } + + @Override + public PrismObjectValueWrapper createContainerValueWrapper(PrismContainerWrapper objectWrapper, PrismContainerValue objectValue, ValueStatus status, WrapperContext context) { + return new PrismObjectValueWrapperImpl((PrismObjectWrapper) objectWrapper, (PrismObjectValue) objectValue, status); + } + + public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status) { + return new PrismObjectWrapperImpl(object, status); + } + + @Override + public PrismContainerValueWrapper createValueWrapper(PrismContainerWrapper parent, PrismContainerValue value, ValueStatus status, WrapperContext context) throws SchemaException { + PrismContainerValueWrapper objectValueWrapper = super.createValueWrapper(parent, value, status, context); + + if (CollectionUtils.isEmpty(context.getVirtualContainers())) { + return objectValueWrapper; + } + + for (VirtualContainersSpecificationType virtualContainer : context.getVirtualContainers()) { + + MutableComplexTypeDefinition mCtd = getPrismContext().definitionFactory().createComplexTypeDefinition(VIRTUAL_CONTAINER_COMPLEX_TYPE); + DisplayType display = virtualContainer.getDisplay(); + + //TODO: support full polystring -> translations could be defined directly there. + mCtd.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); + mCtd.setHelp(WebComponentUtil.getOrigStringFromPoly(display.getHelp())); + mCtd.setRuntimeSchema(true); + + MutablePrismContainerDefinition def = getPrismContext().definitionFactory().createContainerDefinition(VIRTUAL_CONTAINER, mCtd); + def.setMaxOccurs(1); + def.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); + def.setDynamic(true); + + ItemWrapperFactory factory = getRegistry().findWrapperFactory(def); + if (factory == null) { + LOGGER.warn("Cannot find factory for {}. Skipping wrapper creation.", def); + continue; + } + + WrapperContext ctx = context.clone(); + ctx.setVirtualItemSpecification(virtualContainer.getItem()); + ItemWrapper iw = factory.createWrapper(objectValueWrapper, def, ctx); + iw.setVisibleOverwrite(virtualContainer.getVisibility()); + + if (iw == null) { + continue; + } + ((List) objectValueWrapper.getItems()).add(iw); + + } + + return objectValueWrapper; + } + + /** + * @param object apply security constraint to the object, update wrapper context with additional information, e.g. shadow related attributes, ... + */ + protected void applySecurityConstraints(PrismObject object, WrapperContext context) throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { + AuthorizationPhaseType phase = context.getAuthzPhase(); + Task task = context.getTask(); + OperationResult result = context.getResult(); + + try { + PrismObjectDefinition objectDef = modelInteractionService.getEditObjectDefinition(object, phase, task, result); + object.applyDefinition(objectDef, true); + } catch (SchemaException | ConfigurationException | ObjectNotFoundException | ExpressionEvaluationException + | CommunicationException | SecurityViolationException e) { + throw e; + } + + } + + @Override + public boolean match(ItemDefinition def) { + return def instanceof PrismObjectDefinition; + } + + @Override + @PostConstruct + public void register() { + registry.addToRegistry(this); + } + + @Override + public int getOrder() { + return 100; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java index d527a3a74f1..c0026150ead 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java @@ -176,9 +176,9 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); List> items = new ArrayList<>(); - for (RefinedAssociationDefinition refinedAssocationDefinition: refinedAssociationDefinitions) { + for (RefinedAssociationDefinition refinedAssociationDefinition: refinedAssociationDefinitions) { MutablePrismReferenceDefinition shadowRefDef = prismContext - .definitionFactory().createReferenceDefinition(refinedAssocationDefinition.getName(), ObjectReferenceType.COMPLEX_TYPE); + .definitionFactory().createReferenceDefinition(refinedAssociationDefinition.getName(), ObjectReferenceType.COMPLEX_TYPE); shadowRefDef.toMutable().setMaxOccurs(-1); shadowRefDef.setTargetTypeName(ShadowType.COMPLEX_TYPE); PrismReference shadowAss = shadowRefDef.instantiate(); @@ -186,7 +186,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p for (PrismContainerValue associationValue : association.getValues()) { if (association.getDefinition().getCompileTimeClass().equals(ShadowAssociationType.class)) { ShadowAssociationType shadowAssociation = (ShadowAssociationType)associationValue.asContainerable(); - if (shadowAssociation.getName().equals(refinedAssocationDefinition.getName())) { + if (shadowAssociation.getName().equals(refinedAssociationDefinition.getName())) { itemPath = associationValue.getPath(); shadowAss.add(associationValue.findReference(ShadowAssociationType.F_SHADOW_REF).getValue().clone()); } @@ -197,9 +197,9 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p itemPath = ShadowType.F_ASSOCIATION; } - String displayName = refinedAssocationDefinition.getDisplayName(); + String displayName = refinedAssociationDefinition.getDisplayName(); if (StringUtils.isBlank(displayName)) { - displayName = refinedAssocationDefinition.getName().getLocalPart(); + displayName = refinedAssociationDefinition.getName().getLocalPart(); } ShadowAssociationReferenceWrapperImpl item = new ShadowAssociationReferenceWrapperImpl(shadowValueWrapper, shadowAss, @@ -221,7 +221,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p refValues.add(refValue); } item.getValues().addAll((Collection)refValues); - item.setFilter(WebComponentUtil.createAssociationShadowRefFilter(refinedAssocationDefinition, + item.setFilter(WebComponentUtil.createAssociationShadowRefFilter(refinedAssociationDefinition, prismContext, resource.getOid())); // item.setReadOnly(true); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java index 15369c54cb5..efe0dc376ec 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java @@ -76,7 +76,7 @@ public boolean isCreateIfEmpty() { public void setCreateIfEmpty(boolean createIfEmpty) { this.createIfEmpty = createIfEmpty; - }; + } public Boolean getReadOnly() { return readOnly; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java index fbfc689f9bc..548f4c8fc76 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java @@ -16,6 +16,8 @@ import javax.xml.namespace.QName; import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; @@ -38,11 +40,6 @@ import com.evolveum.midpoint.web.component.data.column.ColumnUtils; import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FormItemServerValidationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FormItemValidationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ItemRefinedDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; /** * @author katka @@ -76,6 +73,7 @@ public abstract class ItemWrapperImpl parent, I item, ItemStatus status) { Validate.notNull(item, "Item must not be null."); @@ -374,6 +372,11 @@ public void setShowInVirtualContainer(boolean showInVirtualContainer) { this.showInVirtualContainer = showInVirtualContainer; } + @Override + public void setVisibleOverwrite(UserInterfaceElementVisibilityType visibleOverwrite) { + this.visibleOverwrite = visibleOverwrite; + } + @Override public boolean isVisible(PrismContainerValueWrapper parentContainer, ItemVisibilityHandler visibilityHandler) { @@ -720,4 +723,8 @@ protected I getOldItem() { public boolean isIndexOnly() { return false; // todo } + + protected UserInterfaceElementVisibilityType getVisibleOverwrite() { + return visibleOverwrite; + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java index a478bfdcfb4..31921515913 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java @@ -98,7 +98,7 @@ protected void populateItem(ListItem item) { protected boolean getLabelVisible() { return false; - }; + } }; checkFormGroup.getCheck().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java index 869fb2830ff..e4332d9ee69 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java @@ -79,16 +79,11 @@ public class PrismContainerValuePanel model, ItemPanelSettings settings) { super(id, model); this.settings = settings; -// this.visibilityHandler = visibilityHandler; -// this.editabilityHandler = editabilityHandler; } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java index 80c90056ab9..8ce34d4807a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java @@ -270,16 +270,11 @@ public List> getNonContainers() { PrismObjectWrapper objectWrapper = getParent().findObjectWrapper(); if (objectWrapper == null) { - LOGGER.trace("No object wraper foung. Skipping virtual items."); + LOGGER.trace("No object wrapper found. Skipping virtual items."); return nonContainers; } for (VirtualContainerItemSpecificationType virtualItem : getVirtualItems()) { - if (objectWrapper == null) { - //should not happen, if happens it means something veeery strange happened - continue; - } - try { ItemPath virtualItemPath = getVirtualItemPath(virtualItem); ItemWrapper itemWrapper = objectWrapper.findItem(virtualItemPath, ItemWrapper.class); @@ -292,17 +287,20 @@ public List> getNonContainers() { continue; } - ((List)nonContainers).add(itemWrapper); + if (checkContainerInclusion(itemWrapper)) { + ((List)nonContainers).add(itemWrapper); + } } catch (SchemaException e) { LOGGER.error("Cannot find wrapper with path {}, error occured {}", virtualItem, e.getMessage(), e); } - - } - return nonContainers; } + public boolean checkContainerInclusion(ItemWrapper itemWrapper) { + return true; + } + private ItemPath getVirtualItemPath(VirtualContainerItemSpecificationType virtualItem) throws SchemaException { ItemPathType itemPathType = virtualItem.getPath(); if (itemPathType == null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java index a86e55f455d..d20bb60c936 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java @@ -25,6 +25,8 @@ import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserInterfaceElementVisibilityType; + import org.apache.commons.collections4.CollectionUtils; import org.jetbrains.annotations.NotNull; @@ -347,6 +349,10 @@ protected ItemPath getDeltaPathForStatus(ItemStatus status) { @Override public boolean isVisible(PrismContainerValueWrapper parent, ItemVisibilityHandler visibilityHandler) { + if (isVirtual() && getVisibleOverwrite() != null && UserInterfaceElementVisibilityType.HIDDEN == getVisibleOverwrite()) { + return false; + } + if (getComplexTypeDefinition().getTypeName().equals(MetadataType.COMPLEX_TYPE)) { return (getParent() != null && getParent().isShowMetadata()); } @@ -354,11 +360,7 @@ public boolean isVisible(PrismContainerValueWrapper parent, ItemVisibilityHandle // pretend that object is always expanded. it is becasue all other containers are children of it // and it can influence visibility behavior on different tabs. boolean parentExpanded = parent instanceof PrismObjectValueWrapper ? true : parent.isExpanded(); - return isVisibleByVisibilityHandler(parentExpanded - - - - , visibilityHandler); + return isVisibleByVisibilityHandler(parentExpanded, visibilityHandler); } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html index d2882ee6181..939c0f006a0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html @@ -1,18 +1,22 @@ - - - - - -
-
-
-
-
-
- - + + + + + +
+
+
+
+
+
+ +
+
+
+ + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java index c9dcd24c706..002ec29b60b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java @@ -1,172 +1,137 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.gui.impl.prism.component; - -import com.evolveum.midpoint.gui.api.factory.GuiComponentFactory; -import com.evolveum.midpoint.gui.api.model.ReadOnlyValueModel; -import com.evolveum.midpoint.gui.impl.factory.ExpressionModel; -import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; -import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.gui.impl.prism.*; -import com.evolveum.midpoint.prism.PrismPropertyValue; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.input.AssociationExpressionValuePanel; -import com.evolveum.midpoint.web.component.input.SimpleValueExpressionPanel; -import com.evolveum.midpoint.web.component.input.TextPanel; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnBlurAjaxFormUpdatingBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnChangeAjaxFormUpdatingBehavior; -import com.evolveum.midpoint.web.page.admin.reports.component.AceEditorPanel; -import com.evolveum.midpoint.web.util.ExpressionUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import org.apache.commons.collections.CollectionUtils; -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; - -import java.util.Arrays; - -/** - * @author katka - * - */ -public class ExpressionPropertyPanel extends PrismPropertyPanel { - - private static final long serialVersionUID = 1L; - - private static final Trace LOGGER = TraceManager.getTrace(ExpressionPropertyPanel.class); - - private static final String ID_EXPRESSION_PANEL = "expressionPanel"; - private static final String ID_HEADER = "header"; - - private boolean isExpanded; - - public ExpressionPropertyPanel(String id, IModel> model, ItemPanelSettings settings) { - super(id, model, settings); - isExpanded = model.getObject() != null && CollectionUtils.isNotEmpty(model.getObject().getValues()); - //todo how to set displayOrder ? to display expression property the last, in the same way as containers - } - - @Override - protected Panel createHeaderPanel() { - ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); - if (expressionWrapper != null && (expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression())){ - return new ExpressionPropertyHeaderPanel(ID_HEADER, getModel()) { - private static final long serialVersionUID = 1L; - - @Override - protected void onExpandClick(AjaxRequestTarget target) { - super.onExpandClick(target); - isExpanded = !isExpanded; - target.add(ExpressionPropertyPanel.this); - } - - @Override - protected void addExpressionValuePerformed(AjaxRequestTarget target) { - ExpressionPropertyPanel.this.addExpressionValuePerformed(target); - } - - @Override - protected void removeExpressionValuePerformed(AjaxRequestTarget target){ - ExpressionPropertyPanel.this.getModelObject().getValues().clear(); - target.add(ExpressionPropertyPanel.this); - } - }; - } else { - return super.createHeaderPanel(); - } - } - - @Override - protected Component createValuePanel(ListItem> item, GuiComponentFactory factory, ItemVisibilityHandler visibilityHandler, - ItemEditabilityHandler editabilityHandler) { - ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); - Component expressionPanel = null; - if (expressionWrapper != null && (expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression())) { - ItemRealValueModel realValueModel = new ItemRealValueModel(item.getModel()); - if (expressionWrapper.isAttributeExpression()) { - expressionPanel = new SimpleValueExpressionPanel(ID_EXPRESSION_PANEL, realValueModel); - } else if (expressionWrapper.isAssociationExpression()) { - expressionPanel = new AssociationExpressionValuePanel(ID_EXPRESSION_PANEL, realValueModel, expressionWrapper.getConstruction()); - } - expressionPanel.setOutputMarkupId(true); - expressionPanel.add(new VisibleBehaviour(() -> isExpanded)); - item.add(expressionPanel); - } else { - ItemRealValueModel realValueModel = new ItemRealValueModel(item.getModel()); - expressionPanel = new AceEditorPanel(ID_EXPRESSION_PANEL, null, new ExpressionModel(realValueModel, getPageBase()), 200){ - @Override - protected boolean isResizeToMaxHeight() { - return false; - } - }; - ((AceEditorPanel)expressionPanel).getEditor().add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); - ((AceEditorPanel)expressionPanel).getEditor().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); - expressionPanel.add(new VisibleBehaviour(() -> isExpanded)); - item.add(expressionPanel); - } - - return expressionPanel; - } - - private void addExpressionValuePerformed(AjaxRequestTarget target){ - ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); - if (expressionWrapper.isAttributeExpression()){ - expressionValueAddPerformed(target, ExpressionValueTypes.LITERAL_VALUE_EXPRESSION); - } else { - ExpressionTypeSelectPopup expressionTypeSelectPopup = new ExpressionTypeSelectPopup(getPageBase().getMainPopupBodyId()) { - private static final long serialVersionUID = 1L; - - @Override - protected void addExpressionPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType) { - expressionValueAddPerformed(target, expressionType); - } - }; - getPageBase().showMainPopup(expressionTypeSelectPopup, target); - } - } - - private void expressionValueAddPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType){ - getPageBase().hideMainPopup(target); - try { - ExpressionType newExpressionValue = new ExpressionType(); - if (ExpressionValueTypes.SHADOW_REF_EXPRESSION.equals(expressionType)){ - ExpressionUtil.addShadowRefEvaluatorValue(newExpressionValue, null, getPrismContext()); - } else if (ExpressionValueTypes.ASSOCIATION_TARGET_SEARCH_EXPRESSION.equals(expressionType)){ - ExpressionUtil.getOrCreateAssociationTargetSearchValues(newExpressionValue, getPrismContext()); - } else if (ExpressionValueTypes.LITERAL_VALUE_EXPRESSION.equals(expressionType)){ - ExpressionUtil.updateLiteralExpressionValue(newExpressionValue, Arrays.asList(""), getPrismContext()); - } - - WrapperContext context = new WrapperContext(null, null); - PrismPropertyValue expressionValue = getPageBase().getPrismContext().itemFactory().createPropertyValue(newExpressionValue); - PrismPropertyValueWrapper newExpressionValueWrapper = (PrismPropertyValueWrapper) getPageBase() - .createValueWrapper(getModelObject(), expressionValue, ValueStatus.ADDED, context); - - getModelObject().getValues().clear(); - getModelObject().getValues().add(newExpressionValueWrapper); - getModelObject().getItem().setRealValue(newExpressionValue); - } catch (SchemaException ex){ - LOGGER.error("Unable to create new expression value: {}", ex.getLocalizedMessage()); - } - - target.add(ExpressionPropertyPanel.this); - - } - - @Override - protected void createButtons(ListItem> item) { - //nothing to do.. buttons are in the prism container panel header/ prism container value header - } - -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.gui.impl.prism.component; + +import java.util.Collections; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; + +import com.evolveum.midpoint.gui.api.factory.GuiComponentFactory; +import com.evolveum.midpoint.gui.impl.factory.WrapperContext; +import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.prism.PrismPropertyValue; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.web.component.util.VisibleBehaviour; +import com.evolveum.midpoint.web.util.ExpressionUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; + +/** + * @author katka + * + */ +public class ExpressionPropertyPanel extends PrismPropertyPanel { + + private static final long serialVersionUID = 1L; + + private static final Trace LOGGER = TraceManager.getTrace(ExpressionPropertyPanel.class); + + private static final String ID_HEADER = "header"; + + private boolean isExpanded; + + public ExpressionPropertyPanel(String id, IModel> model, ItemPanelSettings settings) { + super(id, model, settings); + isExpanded = model.getObject() != null && CollectionUtils.isNotEmpty(model.getObject().getValues()); + //todo how to set displayOrder ? to display expression property the last, in the same way as containers + } + + @Override + protected Panel createHeaderPanel() { + ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); + if (expressionWrapper != null && (expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression())){ + return new ExpressionPropertyHeaderPanel(ID_HEADER, getModel()) { + private static final long serialVersionUID = 1L; + + @Override + protected void onExpandClick(AjaxRequestTarget target) { + super.onExpandClick(target); + isExpanded = !isExpanded; + target.add(ExpressionPropertyPanel.this); + } + + @Override + protected void addExpressionValuePerformed(AjaxRequestTarget target) { + ExpressionPropertyPanel.this.addExpressionValuePerformed(target); + } + + @Override + protected void removeExpressionValuePerformed(AjaxRequestTarget target){ + ExpressionPropertyPanel.this.getModelObject().getValues().clear(); + target.add(ExpressionPropertyPanel.this); + } + }; + } else { + return super.createHeaderPanel(); + } + } + + @Override + protected Component createValuePanel(ListItem> item, GuiComponentFactory factory, ItemVisibilityHandler visibilityHandler, + ItemEditabilityHandler editabilityHandler) { + Component expressionPanel = super.createValuePanel(item, factory, visibilityHandler, editabilityHandler); + expressionPanel.add(new VisibleBehaviour(() -> isExpanded)); + return expressionPanel; + } + + private void addExpressionValuePerformed(AjaxRequestTarget target){ + ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); + if (expressionWrapper.isAttributeExpression()){ + expressionValueAddPerformed(target, ExpressionValueTypes.LITERAL_VALUE_EXPRESSION); + } else { + ExpressionTypeSelectPopup expressionTypeSelectPopup = new ExpressionTypeSelectPopup(getPageBase().getMainPopupBodyId()) { + private static final long serialVersionUID = 1L; + + @Override + protected void addExpressionPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType) { + expressionValueAddPerformed(target, expressionType); + } + }; + getPageBase().showMainPopup(expressionTypeSelectPopup, target); + } + } + + private void expressionValueAddPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType){ + getPageBase().hideMainPopup(target); + try { + ExpressionType newExpressionValue = new ExpressionType(); + if (ExpressionValueTypes.SHADOW_REF_EXPRESSION.equals(expressionType)){ + ExpressionUtil.addShadowRefEvaluatorValue(newExpressionValue, null, getPrismContext()); + } else if (ExpressionValueTypes.ASSOCIATION_TARGET_SEARCH_EXPRESSION.equals(expressionType)){ + ExpressionUtil.getOrCreateAssociationTargetSearchValues(newExpressionValue, getPrismContext()); + } else if (ExpressionValueTypes.LITERAL_VALUE_EXPRESSION.equals(expressionType)){ + ExpressionUtil.updateLiteralExpressionValue(newExpressionValue, Collections.singletonList(""), getPrismContext()); + } + + WrapperContext context = new WrapperContext(null, null); + PrismPropertyValue expressionValue = getPageBase().getPrismContext().itemFactory().createPropertyValue(newExpressionValue); + PrismPropertyValueWrapper newExpressionValueWrapper = getPageBase().createValueWrapper(getModelObject(), expressionValue, ValueStatus.ADDED, context); + + getModelObject().getValues().clear(); + getModelObject().getValues().add(newExpressionValueWrapper); + getModelObject().getItem().setRealValue(newExpressionValue); + } catch (SchemaException ex){ + LOGGER.error("Unable to create new expression value: {}", ex.getLocalizedMessage()); + } + + target.add(ExpressionPropertyPanel.this); + + } + + @Override + protected void createButtons(ListItem> item) { + //nothing to do.. buttons are in the prism container panel header/ prism container value header + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java index be0bee01bd3..35a41e5fea7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java @@ -897,7 +897,7 @@ public void onClick(AjaxRequestTarget target) { if (targetRef != null && targetRef.getValues() != null && targetRef.getValues().size() > 0) { PrismReferenceValueWrapperImpl refWrapper = targetRef.getValues().get(0); if (!StringUtils.isEmpty(refWrapper.getNewValue().getOid())) { - Class targetClass = ObjectTypes.getObjectTypeFromTypeQName(refWrapper.getRealValue().getType()).getClassDefinition(); + Class targetClass = ObjectTypes.getObjectTypeFromTypeQName(refWrapper.getRealValue().getType()).getClassDefinition(); WebComponentUtil.dispatchToObjectDetailsPage(targetClass, refWrapper.getNewValue().getOid(), AssignmentPanel.this, false); } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java index 225acabd0c0..3c62cab6b96 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java @@ -490,7 +490,7 @@ public boolean isEnabled(){ body.add(allowTransitive); addAjaxOnUpdateBehavior(body); - }; + } private void addPrivilegesPanel(WebMarkupContainer body){ privilegesNames = getPrivilegesNamesList(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java index 694a0a361a4..3b874a1bc58 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java @@ -141,7 +141,7 @@ private int computeRefreshInterval() { public int getAutoRefreshInterval() { return 0; - }; + } public boolean isAutoRefreshEnabled() { return false; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java index b6cf16db227..6f0161200de 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java @@ -116,7 +116,7 @@ public boolean isSecondEnabled(IModel model){ } public void firstClicked(AjaxRequestTarget target, IModel model){} - public void secondClicked(AjaxRequestTarget target, IModel model){}; + public void secondClicked(AjaxRequestTarget target, IModel model){} public String getFirstSizeCssClass(){ return ButtonSizeClass.SMALL.toString(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html index ce818c74f08..1fee985f83e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html @@ -1,30 +1,34 @@ - - - - - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - + + + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html index f4f55743b23..46e94bd4463 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html @@ -1,21 +1,23 @@ - - - - - - -
-
-
-
-
-
- - - - + + + + + + +
+
+
+
+
+
+
+
+ + + + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java index dd2d7ec12f1..f43d3438c49 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java @@ -53,7 +53,7 @@ public void close(AjaxRequestTarget target) { protected void onAfterRender() { opResult.setAlreadyShown(true); super.onAfterRender(); - }; + } }; panel.add(new VisibleEnableBehaviour() { @@ -61,7 +61,7 @@ protected void onAfterRender() { public boolean isVisible() { return !opResult.isAlreadyShown(); - }; + } }); panel.setOutputMarkupId(true); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java index 3b9ba675584..843b265ba48 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java @@ -1,320 +1,322 @@ -/* - * Copyright (c) 2015-2016 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import java.util.List; - -import org.apache.commons.lang.Validate; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.AjaxButton; -import com.evolveum.midpoint.web.component.AjaxSubmitButton; -import com.evolveum.midpoint.web.component.TabbedPanel; -import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.configuration.PageDebugView; -import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsDto; -import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsPanel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -/** - * @author semancik - * - */ -public abstract class AbstractObjectMainPanel extends Panel { - private static final long serialVersionUID = 1L; - - public static final String PARAMETER_SELECTED_TAB = "tab"; - - private static final String ID_MAIN_FORM = "mainForm"; - public static final String ID_TAB_PANEL = "tabPanel"; - private static final String ID_EXECUTE_OPTIONS = "executeOptions"; - private static final String ID_BACK = "back"; - private static final String ID_SAVE = "save"; - private static final String ID_EDIT_XML = "editXml"; - private static final String ID_PREVIEW_CHANGES = "previewChanges"; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectMainPanel.class); - - private Form mainForm; - - private LoadableModel> objectModel; - - private LoadableModel executeOptionsModel = new LoadableModel(false) { - private static final long serialVersionUID = 1L; - - @Override - protected ExecuteChangeOptionsDto load() { - return ExecuteChangeOptionsDto.createFromSystemConfiguration(); - } - }; - - public AbstractObjectMainPanel(String id, LoadableModel> objectModel, PageAdminObjectDetails parentPage) { - super(id, objectModel); - Validate.notNull(objectModel, "Null object model"); - this.objectModel = objectModel; - initLayout(parentPage); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - - TabbedPanel tabbedPanel = (TabbedPanel) get(ID_MAIN_FORM + ":" + ID_TAB_PANEL); - WebComponentUtil.setSelectedTabFromPageParameters(tabbedPanel, getPage().getPageParameters(), - PARAMETER_SELECTED_TAB); - } - - public LoadableModel> getObjectModel() { - return objectModel; - } - - public PrismObjectWrapper getObjectWrapper() { - return objectModel.getObject(); - } - - public PrismObject getObject() { - return objectModel.getObject().getObject(); - } - - public Form getMainForm() { - return mainForm; - } - - private void initLayout(PageAdminObjectDetails parentPage) { - mainForm = new Form<>(ID_MAIN_FORM, true); - add(mainForm); - initLayoutTabs(parentPage); - initLayoutOptions(); - initLayoutButtons(parentPage); - } - - protected void initLayoutTabs(final PageAdminObjectDetails parentPage) { - List tabs = createTabs(parentPage); - TabbedPanel tabPanel = WebComponentUtil.createTabPanel(ID_TAB_PANEL, parentPage, tabs, null, - PARAMETER_SELECTED_TAB); - mainForm.add(tabPanel); - } - - protected abstract List createTabs(PageAdminObjectDetails parentPage); - - protected void initLayoutOptions() { - ExecuteChangeOptionsPanel optionsPanel = new ExecuteChangeOptionsPanel(ID_EXECUTE_OPTIONS, - executeOptionsModel, true, false); - optionsPanel.setOutputMarkupId(true); - optionsPanel.add(new VisibleEnableBehaviour() { - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - return getOptionsPanelVisibility(); - } - - }); - mainForm.add(optionsPanel); - } - - protected void initLayoutButtons(PageAdminObjectDetails parentPage) { - initLayoutPreviewButton(parentPage); - initLayoutSaveButton(parentPage); - initLayoutBackButton(parentPage); - initLayoutEditXmlButton(parentPage); - } - - protected void initLayoutSaveButton(final PageAdminObjectDetails parentPage) { - AjaxSubmitButton saveButton = new AjaxSubmitButton(ID_SAVE, parentPage.createStringResource("pageAdminFocus.button.save")) { - private static final long serialVersionUID = 1L; - - @Override - protected void onSubmit(AjaxRequestTarget target) { - getDetailsPage().savePerformed(target); - } - - @Override - protected void onError(AjaxRequestTarget target) { - target.add(parentPage.getFeedbackPanel()); - } - }; - saveButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - return !getObjectWrapper().isReadOnly() && - !getDetailsPage().isForcedPreview(); - } - - @Override - public boolean isEnabled() { - //in case user isn't allowed to modify focus data but has - // e.g. #assign authorization, Save button is disabled on page load. - // Save button becomes enabled just if some changes are made - // on the Assignments tab (in the use case with #assign authorization) -// PrismContainerDefinition def = getObjectWrapper().getDefinition(); - if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) - && !getObjectWrapper().canModify()){ - return areSavePreviewButtonsEnabled(); - } - return true; - } - }); - saveButton.setOutputMarkupId(true); - saveButton.setOutputMarkupPlaceholderTag(true); - mainForm.setDefaultButton(saveButton); - mainForm.add(saveButton); - } - - // TEMPORARY - protected void initLayoutPreviewButton(final PageAdminObjectDetails parentPage) { - AjaxSubmitButton previewButton = new AjaxSubmitButton(ID_PREVIEW_CHANGES, parentPage.createStringResource("pageAdminFocus.button.previewChanges")) { - private static final long serialVersionUID = 1L; - - @Override - protected void onSubmit(AjaxRequestTarget target) { - getDetailsPage().previewPerformed(target); - } - - @Override - protected void onError(AjaxRequestTarget target) { - target.add(parentPage.getFeedbackPanel()); - } - }; - previewButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return AbstractObjectMainPanel.this.isPreviewButtonVisible(); - } - - @Override - public boolean isEnabled() { -// PrismContainerDefinition def = getObjectWrapper().getDefinition(); - if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) - && !getObjectWrapper().canModify()){ - return areSavePreviewButtonsEnabled(); - } - return true; - } - }); - previewButton.setOutputMarkupId(true); - previewButton.setOutputMarkupPlaceholderTag(true); - mainForm.add(previewButton); - } - - protected boolean isPreviewButtonVisible(){ - return !getObjectWrapper().isReadOnly(); - } - - protected void initLayoutBackButton(PageAdminObjectDetails parentPage) { - AjaxButton back = new AjaxButton(ID_BACK, parentPage.createStringResource("pageAdminFocus.button.back")) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - backPerformed(target); - } - - }; - back.setOutputMarkupId(true); - back.setOutputMarkupPlaceholderTag(true); - mainForm.add(back); - } - - private void initLayoutEditXmlButton(final PageAdminObjectDetails parentPage){ - AjaxButton editXmlButton = new AjaxButton(ID_EDIT_XML, parentPage.createStringResource("AbstractObjectMainPanel.editXmlButton")) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - ConfirmationPanel confirmationPanel = new ConfirmationPanel(parentPage.getMainPopupBodyId(), - parentPage.createStringResource("AbstractObjectMainPanel.confirmEditXmlRedirect")){ - private static final long serialVersionUID = 1L; - - @Override - public void yesPerformed(AjaxRequestTarget target) { - PageParameters parameters = new PageParameters(); - parameters.add(PageDebugView.PARAM_OBJECT_ID, parentPage.getObjectWrapper().getOid()); - parameters.add(PageDebugView.PARAM_OBJECT_TYPE, parentPage.getCompileTimeClass().getSimpleName()); - parentPage.navigateToNext(PageDebugView.class, parameters); - } - - @Override - public StringResourceModel getTitle() { - return new StringResourceModel("pageUsers.message.confirmActionPopupTitle"); - } - }; - - parentPage.showMainPopup(confirmationPanel, target); - } - }; - editXmlButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_CONFIGURATION_URL, - AuthorizationConstants.AUTZ_UI_CONFIGURATION_DEBUG_URL) && - !getObjectWrapper().isReadOnly(); - } - }); - mainForm.add(editXmlButton); - - } - public ExecuteChangeOptionsDto getExecuteChangeOptionsDto() { - return executeOptionsModel.getObject(); - } - - private void backPerformed(AjaxRequestTarget target) { - getDetailsPage().redirectBack(); - } - - protected PageAdminObjectDetails getDetailsPage() { - return (PageAdminObjectDetails)getPage(); - } - - protected boolean getOptionsPanelVisibility(){ - if (getObjectWrapper().isReadOnly()){ - return false; - } -// PrismContainerDefinition def = getObjectWrapper().getDefinition(); - if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) - && !getObjectWrapper().canModify()){ - return false; - } - return true; - } - - public void reloadSavePreviewButtons(AjaxRequestTarget target){ - target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_PREVIEW_CHANGES)); - target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_SAVE)); - - } - - protected boolean areSavePreviewButtonsEnabled() { - return false; - } - - public TabbedPanel getTabbedPanel() { - return (TabbedPanel) get(WebComponentUtil.getPageBase(this).createComponentPath(ID_MAIN_FORM, ID_TAB_PANEL)); - } -} +/* + * Copyright (c) 2015-2016 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.security.api.AuthorizationConstants; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.AjaxSubmitButton; +import com.evolveum.midpoint.web.component.TabbedPanel; +import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.web.page.admin.configuration.PageDebugView; +import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsDto; +import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsPanel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; + +/** + * @author semancik + * + */ +public abstract class AbstractObjectMainPanel extends Panel { + private static final long serialVersionUID = 1L; + + public static final String PARAMETER_SELECTED_TAB = "tab"; + + private static final String ID_MAIN_FORM = "mainForm"; + public static final String ID_TAB_PANEL = "tabPanel"; + private static final String ID_EXECUTE_OPTIONS = "executeOptions"; + private static final String ID_BACK = "back"; + private static final String ID_SAVE = "save"; + private static final String ID_EDIT_XML = "editXml"; + private static final String ID_PREVIEW_CHANGES = "previewChanges"; + + //private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectMainPanel.class); + + private Form> mainForm; + + private LoadableModel> objectModel; + //get rid of it. + private PageAdminObjectDetails parentPage; + + private LoadableModel executeOptionsModel = new LoadableModel(false) { + private static final long serialVersionUID = 1L; + + @Override + protected ExecuteChangeOptionsDto load() { + return ExecuteChangeOptionsDto.createFromSystemConfiguration(); + } + }; + + public AbstractObjectMainPanel(String id, LoadableModel> objectModel, PageAdminObjectDetails parentPage) { + super(id, objectModel); + Validate.notNull(objectModel, "Null object model"); + this.objectModel = objectModel; + this.parentPage = parentPage; + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(parentPage); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + + TabbedPanel tabbedPanel = (TabbedPanel) get(ID_MAIN_FORM + ":" + ID_TAB_PANEL); + WebComponentUtil.setSelectedTabFromPageParameters(tabbedPanel, getPage().getPageParameters(), + PARAMETER_SELECTED_TAB); + } + + public LoadableModel> getObjectModel() { + return objectModel; + } + + public PrismObjectWrapper getObjectWrapper() { + return objectModel.getObject(); + } + + public PrismObject getObject() { + return objectModel.getObject().getObject(); + } + + public Form> getMainForm() { + return mainForm; + } + + private void initLayout(PageAdminObjectDetails parentPage) { + mainForm = new Form<>(ID_MAIN_FORM, true); + add(mainForm); + initLayoutTabs(parentPage); + initLayoutOptions(); + initLayoutButtons(parentPage); + } + + protected void initLayoutTabs(final PageAdminObjectDetails parentPage) { + List tabs = createTabs(parentPage); + TabbedPanel tabPanel = WebComponentUtil.createTabPanel(ID_TAB_PANEL, parentPage, tabs, null, PARAMETER_SELECTED_TAB); + mainForm.add(tabPanel); + } + + protected abstract List createTabs(PageAdminObjectDetails parentPage); + + protected void initLayoutOptions() { + ExecuteChangeOptionsPanel optionsPanel = new ExecuteChangeOptionsPanel(ID_EXECUTE_OPTIONS, + executeOptionsModel, true, false); + optionsPanel.setOutputMarkupId(true); + optionsPanel.add(new VisibleEnableBehaviour() { + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return getOptionsPanelVisibility(); + } + + }); + mainForm.add(optionsPanel); + } + + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { + initLayoutPreviewButton(parentPage); + initLayoutSaveButton(parentPage); + initLayoutBackButton(parentPage); + initLayoutEditXmlButton(parentPage); + } + + protected void initLayoutSaveButton(final PageAdminObjectDetails parentPage) { + AjaxSubmitButton saveButton = new AjaxSubmitButton(ID_SAVE, parentPage.createStringResource("pageAdminFocus.button.save")) { + private static final long serialVersionUID = 1L; + + @Override + protected void onSubmit(AjaxRequestTarget target) { + getDetailsPage().savePerformed(target); + } + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(parentPage.getFeedbackPanel()); + } + }; + saveButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return !getObjectWrapper().isReadOnly() && + !getDetailsPage().isForcedPreview(); + } + + @Override + public boolean isEnabled() { + //in case user isn't allowed to modify focus data but has + // e.g. #assign authorization, Save button is disabled on page load. + // Save button becomes enabled just if some changes are made + // on the Assignments tab (in the use case with #assign authorization) +// PrismContainerDefinition def = getObjectWrapper().getDefinition(); + if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) + && !getObjectWrapper().canModify()){ + return areSavePreviewButtonsEnabled(); + } + return true; + } + }); + saveButton.setOutputMarkupId(true); + saveButton.setOutputMarkupPlaceholderTag(true); + mainForm.setDefaultButton(saveButton); + mainForm.add(saveButton); + } + + // TEMPORARY + protected void initLayoutPreviewButton(final PageAdminObjectDetails parentPage) { + AjaxSubmitButton previewButton = new AjaxSubmitButton(ID_PREVIEW_CHANGES, parentPage.createStringResource("pageAdminFocus.button.previewChanges")) { + private static final long serialVersionUID = 1L; + + @Override + protected void onSubmit(AjaxRequestTarget target) { + getDetailsPage().previewPerformed(target); + } + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(parentPage.getFeedbackPanel()); + } + }; + previewButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return AbstractObjectMainPanel.this.isPreviewButtonVisible(); + } + + @Override + public boolean isEnabled() { +// PrismContainerDefinition def = getObjectWrapper().getDefinition(); + if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) + && !getObjectWrapper().canModify()){ + return areSavePreviewButtonsEnabled(); + } + return true; + } + }); + previewButton.setOutputMarkupId(true); + previewButton.setOutputMarkupPlaceholderTag(true); + mainForm.add(previewButton); + } + + protected boolean isPreviewButtonVisible(){ + return !getObjectWrapper().isReadOnly(); + } + + protected void initLayoutBackButton(PageAdminObjectDetails parentPage) { + AjaxButton back = new AjaxButton(ID_BACK, parentPage.createStringResource("pageAdminFocus.button.back")) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + backPerformed(); + } + + }; + back.setOutputMarkupId(true); + back.setOutputMarkupPlaceholderTag(true); + mainForm.add(back); + } + + private void initLayoutEditXmlButton(final PageAdminObjectDetails parentPage){ + AjaxButton editXmlButton = new AjaxButton(ID_EDIT_XML, parentPage.createStringResource("AbstractObjectMainPanel.editXmlButton")) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ConfirmationPanel confirmationPanel = new ConfirmationPanel(parentPage.getMainPopupBodyId(), + parentPage.createStringResource("AbstractObjectMainPanel.confirmEditXmlRedirect")){ + private static final long serialVersionUID = 1L; + + @Override + public void yesPerformed(AjaxRequestTarget target) { + PageParameters parameters = new PageParameters(); + parameters.add(PageDebugView.PARAM_OBJECT_ID, parentPage.getObjectWrapper().getOid()); + parameters.add(PageDebugView.PARAM_OBJECT_TYPE, parentPage.getCompileTimeClass().getSimpleName()); + parentPage.navigateToNext(PageDebugView.class, parameters); + } + + @Override + public StringResourceModel getTitle() { + return new StringResourceModel("pageUsers.message.confirmActionPopupTitle"); + } + }; + + parentPage.showMainPopup(confirmationPanel, target); + } + }; + editXmlButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_CONFIGURATION_URL, + AuthorizationConstants.AUTZ_UI_CONFIGURATION_DEBUG_URL) && + !getObjectWrapper().isReadOnly(); + } + }); + mainForm.add(editXmlButton); + + } + public ExecuteChangeOptionsDto getExecuteChangeOptionsDto() { + return executeOptionsModel.getObject(); + } + + private void backPerformed() { + getDetailsPage().redirectBack(); + } + + @SuppressWarnings("unchecked") + protected PageAdminObjectDetails getDetailsPage() { + return (PageAdminObjectDetails) getPage(); + } + + protected boolean getOptionsPanelVisibility(){ + if (getObjectWrapper().isReadOnly()){ + return false; + } + return ItemStatus.NOT_CHANGED != getObjectWrapper().getStatus() + || getObjectWrapper().canModify(); + } + + public void reloadSavePreviewButtons(AjaxRequestTarget target){ + target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_PREVIEW_CHANGES)); + target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_SAVE)); + + } + + protected boolean areSavePreviewButtonsEnabled() { + return false; + } + + public TabbedPanel getTabbedPanel() { + return (TabbedPanel) get(WebComponentUtil.getPageBase(this).createComponentPath(ID_MAIN_FORM, ID_TAB_PANEL)); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java index 48f35fc34e8..ee97d1f6e5d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java @@ -1,149 +1,126 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettings; -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.MarkupContainer; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.impl.prism.PrismPropertyPanel; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.dialog.Popupable; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.prism.ItemVisibility; -import com.evolveum.midpoint.web.model.PrismPropertyWrapperModel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -/** - * @author semancik - */ -public abstract class AbstractObjectTabPanel extends Panel { - private static final long serialVersionUID = 1L; - - protected static final String ID_MAIN_FORM = "mainForm"; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectTabPanel.class); - - private LoadableModel> objectWrapperModel; -// protected PageBase pageBase; - private Form> mainForm; - - public AbstractObjectTabPanel(String id, Form> mainForm, LoadableModel> objectWrapperModel) { - super(id); - this.objectWrapperModel = objectWrapperModel; - this.mainForm = mainForm; -// this.pageBase = pageBase; - } - - public LoadableModel> getObjectWrapperModel() { - return objectWrapperModel; - } - - public PrismObjectWrapper getObjectWrapper() { - return objectWrapperModel.getObject(); - } - - protected PrismContext getPrismContext() { - return getPageBase().getPrismContext(); - } - - protected PageParameters getPageParameters() { - return getPageBase().getPageParameters(); - } - - public PageBase getPageBase() { - return (PageBase) getPage(); - } - - public Form> getMainForm() { - return mainForm; - } - - public StringResourceModel createStringResource(String resourceKey, Object... objects) { - return PageBase.createStringResourceStatic(this, resourceKey, objects); -// return new StringResourceModel(resourceKey, this, null, resourceKey, objects); - } - - public String getString(String resourceKey, Object... objects) { - return createStringResource(resourceKey, objects).getString(); - } - - protected String createComponentPath(String... components) { - return StringUtils.join(components, ":"); - } - - protected void showResult(OperationResult result) { - getPageBase().showResult(result); - } - - protected void showResult(OperationResult result, boolean showSuccess) { - getPageBase().showResult(result, false); - } - - - protected WebMarkupContainer getFeedbackPanel() { - return getPageBase().getFeedbackPanel(); - } - - public Object findParam(String param, String oid, OperationResult result) { - - Object object = null; - - //TODO: FIXME get(PARAM_OID) returns collection - for (OperationResult subResult : result.getSubresults()) { - if (subResult != null && subResult.getParams() != null) { - if (subResult.getParams().get(param) != null - && subResult.getParams().get(OperationResult.PARAM_OID) != null - && subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) { - return subResult.getParams().get(param); - } - object = findParam(param, oid, subResult); - - } - } - return object; - } - - protected void showModalWindow(Popupable popupable, AjaxRequestTarget target) { - getPageBase().showMainPopup(popupable, target); - target.add(getFeedbackPanel()); - } - - protected Panel addPrismPropertyPanel(MarkupContainer parentComponent, String id, QName typeName, ItemPath propertyPath) { - - try { - //FIXME : really always visible? - ItemPanelSettingsBuilder settingsBuilder = new ItemPanelSettingsBuilder(); - settingsBuilder.visibilityHandler(wrapper -> ItemVisibility.VISIBLE); - - Panel panel = getPageBase().initItemPanel(id, typeName, PrismPropertyWrapperModel.fromContainerWrapper(getObjectWrapperModel(), propertyPath), settingsBuilder.build()); - parentComponent.add(panel); - return panel; - } catch (SchemaException e) { - LOGGER.error("Cannot create panel for {}", typeName, e); - getSession().error("Cannot create panel for " + typeName + ", reason: " + e.getMessage()); - } - - return null; - } -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import javax.xml.namespace.QName; + +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.MarkupContainer; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.dialog.Popupable; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.prism.ItemVisibility; +import com.evolveum.midpoint.web.model.PrismPropertyWrapperModel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; + +/** + * @author semancik + */ +public abstract class AbstractObjectTabPanel extends Panel { + private static final long serialVersionUID = 1L; + + protected static final String ID_MAIN_FORM = "mainForm"; + + private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectTabPanel.class); + + private LoadableModel> objectWrapperModel; + private Form> mainForm; + + public AbstractObjectTabPanel(String id, Form> mainForm, LoadableModel> objectWrapperModel) { + super(id); + this.objectWrapperModel = objectWrapperModel; + this.mainForm = mainForm; + } + + public LoadableModel> getObjectWrapperModel() { + return objectWrapperModel; + } + + public PrismObjectWrapper getObjectWrapper() { + return objectWrapperModel.getObject(); + } + + protected PrismContext getPrismContext() { + return getPageBase().getPrismContext(); + } + + protected PageParameters getPageParameters() { + return getPageBase().getPageParameters(); + } + + public PageBase getPageBase() { + return (PageBase) getPage(); + } + + public Form> getMainForm() { + return mainForm; + } + + public StringResourceModel createStringResource(String resourceKey, Object... objects) { + return PageBase.createStringResourceStatic(this, resourceKey, objects); +// return new StringResourceModel(resourceKey, this, null, resourceKey, objects); + } + + public String getString(String resourceKey, Object... objects) { + return createStringResource(resourceKey, objects).getString(); + } + + protected String createComponentPath(String... components) { + return StringUtils.join(components, ":"); + } + + protected void showResult(OperationResult result) { + getPageBase().showResult(result); + } + + protected void showResult(OperationResult result, boolean showSuccess) { + getPageBase().showResult(result, showSuccess); + } + + + protected WebMarkupContainer getFeedbackPanel() { + return getPageBase().getFeedbackPanel(); + } + + protected void showModalWindow(Popupable popupable, AjaxRequestTarget target) { + getPageBase().showMainPopup(popupable, target); + target.add(getFeedbackPanel()); + } + + protected Panel addPrismPropertyPanel(MarkupContainer parentComponent, String id, QName typeName, ItemPath propertyPath) { + + try { + //FIXME : really always visible? + ItemPanelSettingsBuilder settingsBuilder = new ItemPanelSettingsBuilder(); + settingsBuilder.visibilityHandler(wrapper -> ItemVisibility.VISIBLE); + + Panel panel = getPageBase().initItemPanel(id, typeName, PrismPropertyWrapperModel.fromContainerWrapper(getObjectWrapperModel(), propertyPath), settingsBuilder.build()); + parentComponent.add(panel); + return panel; + } catch (SchemaException e) { + LOGGER.error("Cannot create panel for {}", typeName, e); + getSession().error("Cannot create panel for " + typeName + ", reason: " + e.getMessage()); + } + + return null; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java index 4a26cd7b5cd..b18ede050d8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java @@ -1,327 +1,326 @@ -/* - * Copyright (c) 2015-2016 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import org.apache.wicket.ajax.AjaxChannel; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.Model; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.AjaxButton; -import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.web.page.admin.PageAdminFocus; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; -import com.evolveum.midpoint.web.page.admin.roles.AvailableRelationDto; -import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; -import com.evolveum.midpoint.web.page.self.PageAssignmentShoppingCart; -import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; -import com.evolveum.midpoint.web.session.RoleCatalogStorage; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AreaCategoryType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -public abstract class AbstractRoleMainPanel extends FocusMainPanel { - private static final long serialVersionUID = 1L; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMainPanel.class); - - private static final String DOT_CLASS = AbstractRoleMainPanel.class.getName(); - private static final String OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM = DOT_CLASS + "canSearchRoleMembershipItem"; - private static final String OPERATION_LOAD_ASSIGNMENTS_LIMIT = DOT_CLASS + "loadAssignmentsLimit"; - private static final String ID_SHOPPING_CART_BUTTONS_PANEL = "shoppingCartButtonsPanel"; - private static final String ID_ADD_TO_CART_BUTTON = "addToCartButton"; - - public AbstractRoleMainPanel(String id, LoadableModel> objectModel, - LoadableModel> projectionModel, - PageAdminFocus parentPage) { - super(id, objectModel, projectionModel, parentPage); - } - - @Override - protected void initLayoutButtons(PageAdminObjectDetails parentPage) { - super.initLayoutButtons(parentPage); - initShoppingCartPanel(parentPage); - } - - private void initShoppingCartPanel(PageAdminObjectDetails parentPage){ - RoleCatalogStorage storage = parentPage.getSessionStorage().getRoleCatalog(); - - WebMarkupContainer shoppingCartButtonsPanel = new WebMarkupContainer(ID_SHOPPING_CART_BUTTONS_PANEL); - shoppingCartButtonsPanel.setOutputMarkupId(true); - shoppingCartButtonsPanel.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - //show panel only in case if user came to object details from - // Role Catalog page - return PageAssignmentShoppingCart.class.equals(WebComponentUtil.getPreviousPageClass(parentPage)); - } - }); - getMainForm().add(shoppingCartButtonsPanel); - - AjaxButton addToCartButton = new AjaxButton(ID_ADD_TO_CART_BUTTON, parentPage - .createStringResource("PageAssignmentDetails.addToCartButton")) { - private static final long serialVersionUID = 1L; - - @Override - protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { - attributes.setChannel(new AjaxChannel("blocking", AjaxChannel.Type.ACTIVE)); - } - - @Override - public void onClick(AjaxRequestTarget target) { - AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(getObject().asObjectable(), UserDtoStatus.ADD, parentPage); - storage.getAssignmentShoppingCart().add(dto); - parentPage.redirectBack(); - } - }; - addToCartButton.add(AttributeAppender.append("class", new LoadableModel() { - @Override - protected String load() { - return addToCartButton.isEnabled() ? "btn btn-success" : "btn btn-success disabled"; - } - })); - addToCartButton.setOutputMarkupId(true); - addToCartButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isEnabled(){ - int assignmentsLimit = AssignmentsUtil.loadAssignmentsLimit(new OperationResult(OPERATION_LOAD_ASSIGNMENTS_LIMIT), - parentPage); - AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(AbstractRoleMainPanel.this.getObject().asObjectable(), - UserDtoStatus.ADD, parentPage); - return !AssignmentsUtil.isShoppingCartAssignmentsLimitReached(assignmentsLimit, parentPage) - && (storage.isMultiUserRequest() || dto.isAssignable()); } - }); - addToCartButton.add(AttributeAppender.append("title", - AssignmentsUtil.getShoppingCartAssignmentsLimitReachedTitleModel(parentPage))); - shoppingCartButtonsPanel.add(addToCartButton); - } - - @Override - protected List createTabs(final PageAdminObjectDetails parentPage) { - List tabs = super.createTabs(parentPage); - - tabs.add( - new PanelTab(parentPage.createStringResource("pageAdminFocus.applicablePolicies"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_APPLICABLE_POLICIES_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusApplicablePoliciesTabPanel<>(panelId, getMainForm(), getObjectModel()); - } - }); - - tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.inducement"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_INDUCEMENTS_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - SwitchAssignmentTypePanel panel = new SwitchAssignmentTypePanel(panelId, - PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), AbstractRoleType.F_INDUCEMENT)){ - private static final long serialVersionUID = 1L; - - @Override - protected boolean isInducement(){ - return true; - } - }; - return panel; -// return new AbstractRoleInducementPanel<>(panelId, getMainForm(), getObjectModel(), parentPage); - } - - @Override - public String getCount(){ - return getInducementsCount(); - } - - }); - - tabs.add(new PanelTab(parentPage.createStringResource("pageRole.members"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_MEMBERS_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createMemberPanel(panelId); - } - - @Override - public boolean isVisible() { - return super.isVisible() && - getObjectWrapper().getStatus() != ItemStatus.ADDED && - isAllowedToReadRoleMembership(getObjectWrapper().getOid(), parentPage); - } - }); - - tabs.add(new PanelTab(parentPage.createStringResource("pageRole.governance"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_GOVERNANCE_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createGovernancePanel(panelId); - } - - @Override - public boolean isVisible() { - return super.isVisible() && getObjectWrapper().getStatus() != ItemStatus.ADDED; - } - }); - - return tabs; - } - - - public AbstractRoleMemberPanel createMemberPanel(String panelId) { - - return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { - - private static final long serialVersionUID = 1L; - - @Override - protected AvailableRelationDto getSupportedRelations() { - return getSupportedMembersTabRelations(); - } - - }; - } - - - public AbstractRoleMemberPanel createGovernancePanel(String panelId) { - - return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { - - private static final long serialVersionUID = 1L; - - @Override - protected AvailableRelationDto getSupportedRelations() { - AvailableRelationDto avariableRelations = getSupportedGovernanceTabRelations(); - avariableRelations.setDefaultRelation(getDefaultGovernanceRelation()); - return avariableRelations; - } - - @Override - protected Map getAuthorizations(QName complexType) { - return getGovernanceTabAuthorizations(); - } - - }; - } - - protected AvailableRelationDto getSupportedMembersTabRelations(){ - List relations = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.ADMINISTRATION, getDetailsPage()); - List governance = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage()); - governance.forEach(r -> relations.remove(r)); - return new AvailableRelationDto(relations); - } - - protected AvailableRelationDto getSupportedGovernanceTabRelations(){ - return new AvailableRelationDto(WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage())); - } - - protected QName getDefaultGovernanceRelation(){ - return WebComponentUtil.getCategoryDefaultRelation(AreaCategoryType.GOVERNANCE); - } - - protected Map getGovernanceTabAuthorizations(){ - return GuiAuthorizationConstants.GOVERNANCE_MEMBERS_AUTHORIZATIONS; - } - - private boolean isAllowedToReadRoleMembership(String abstractRoleOid, PageBase parentPage){ - return isAllowedToReadRoleMembershipItemForType(abstractRoleOid, UserType.class, parentPage) - || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, RoleType.class, parentPage) - || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, OrgType.class, parentPage) - || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, ServiceType.class, parentPage); - } - - private boolean isAllowedToReadRoleMembershipItemForType(String abstractRoleOid, Class type, PageBase parentPage){ - ObjectQuery query = parentPage.getPrismContext().queryFor(type) - .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(abstractRoleOid).build(); - Task task = parentPage.createSimpleTask(OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM); - OperationResult result = task.getResult(); - boolean isAllowed = false; - try { - isAllowed = parentPage.getModelInteractionService() - .canSearch(type, null, null, false, query, task, result); - } catch (Exception ex){ - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't check if user is allowed to search for roleMembershipRef item", ex); - } - return isAllowed; - } - - private String getInducementsCount(){ - PrismObject focus = getObjectModel().getObject().getObject(); - List inducements = focus.asObjectable().getInducement(); - if (inducements == null){ - return ""; - } - return Integer.toString(inducements.size()); - } - - - //TODO what? why? when? - @Override - protected boolean areSavePreviewButtonsEnabled(){ - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismContainerWrapper assignmentsWrapper; - try { - assignmentsWrapper = focusWrapper.findContainer(AbstractRoleType.F_INDUCEMENT); - } catch (SchemaException e) { - return false; - } - return super.areSavePreviewButtonsEnabled() || isAssignmentsModelChanged(assignmentsWrapper); - } -} +/* + * Copyright (c) 2015-2016 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.wicket.ajax.AjaxChannel; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.Model; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.web.page.admin.PageAdminFocus; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; +import com.evolveum.midpoint.web.page.admin.roles.AvailableRelationDto; +import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; +import com.evolveum.midpoint.web.page.self.PageAssignmentShoppingCart; +import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; +import com.evolveum.midpoint.web.session.RoleCatalogStorage; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AreaCategoryType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; + +/** + * @author semancik + * + */ +public abstract class AbstractRoleMainPanel extends FocusMainPanel { + private static final long serialVersionUID = 1L; + + private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMainPanel.class); + + private static final String DOT_CLASS = AbstractRoleMainPanel.class.getName(); + private static final String OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM = DOT_CLASS + "canSearchRoleMembershipItem"; + private static final String OPERATION_LOAD_ASSIGNMENTS_LIMIT = DOT_CLASS + "loadAssignmentsLimit"; + private static final String ID_SHOPPING_CART_BUTTONS_PANEL = "shoppingCartButtonsPanel"; + private static final String ID_ADD_TO_CART_BUTTON = "addToCartButton"; + + public AbstractRoleMainPanel(String id, LoadableModel> objectModel, + LoadableModel> projectionModel, + PageAdminFocus parentPage) { + super(id, objectModel, projectionModel, parentPage); + } + + @Override + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { + super.initLayoutButtons(parentPage); + initShoppingCartPanel(parentPage); + } + + private void initShoppingCartPanel(PageAdminObjectDetails parentPage){ + RoleCatalogStorage storage = parentPage.getSessionStorage().getRoleCatalog(); + + WebMarkupContainer shoppingCartButtonsPanel = new WebMarkupContainer(ID_SHOPPING_CART_BUTTONS_PANEL); + shoppingCartButtonsPanel.setOutputMarkupId(true); + shoppingCartButtonsPanel.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + //show panel only in case if user came to object details from + // Role Catalog page + return PageAssignmentShoppingCart.class.equals(WebComponentUtil.getPreviousPageClass(parentPage)); + } + }); + getMainForm().add(shoppingCartButtonsPanel); + + AjaxButton addToCartButton = new AjaxButton(ID_ADD_TO_CART_BUTTON, parentPage + .createStringResource("PageAssignmentDetails.addToCartButton")) { + private static final long serialVersionUID = 1L; + + @Override + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { + attributes.setChannel(new AjaxChannel("blocking", AjaxChannel.Type.ACTIVE)); + } + + @Override + public void onClick(AjaxRequestTarget target) { + AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(getObject().asObjectable(), UserDtoStatus.ADD, parentPage); + storage.getAssignmentShoppingCart().add(dto); + parentPage.redirectBack(); + } + }; + addToCartButton.add(AttributeAppender.append("class", new LoadableModel() { + @Override + protected String load() { + return addToCartButton.isEnabled() ? "btn btn-success" : "btn btn-success disabled"; + } + })); + addToCartButton.setOutputMarkupId(true); + addToCartButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isEnabled(){ + int assignmentsLimit = AssignmentsUtil.loadAssignmentsLimit(new OperationResult(OPERATION_LOAD_ASSIGNMENTS_LIMIT), + parentPage); + AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(AbstractRoleMainPanel.this.getObject().asObjectable(), + UserDtoStatus.ADD, parentPage); + return !AssignmentsUtil.isShoppingCartAssignmentsLimitReached(assignmentsLimit, parentPage) + && (storage.isMultiUserRequest() || dto.isAssignable()); } + }); + addToCartButton.add(AttributeAppender.append("title", + AssignmentsUtil.getShoppingCartAssignmentsLimitReachedTitleModel(parentPage))); + shoppingCartButtonsPanel.add(addToCartButton); + } + + @Override + protected List createTabs(final PageAdminObjectDetails parentPage) { + List tabs = super.createTabs(parentPage); + + tabs.add( + new PanelTab(parentPage.createStringResource("pageAdminFocus.applicablePolicies"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_APPLICABLE_POLICIES_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusApplicablePoliciesTabPanel<>(panelId, getMainForm(), getObjectModel()); + } + }); + + tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.inducement"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_INDUCEMENTS_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + SwitchAssignmentTypePanel panel = new SwitchAssignmentTypePanel(panelId, + PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), AbstractRoleType.F_INDUCEMENT)){ + private static final long serialVersionUID = 1L; + + @Override + protected boolean isInducement(){ + return true; + } + }; + return panel; + } + + @Override + public String getCount(){ + return getInducementsCount(); + } + + }); + + tabs.add(new PanelTab(parentPage.createStringResource("pageRole.members"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_MEMBERS_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createMemberPanel(panelId); + } + + @Override + public boolean isVisible() { + return super.isVisible() && + getObjectWrapper().getStatus() != ItemStatus.ADDED && + isAllowedToReadRoleMembership(getObjectWrapper().getOid(), parentPage); + } + }); + + tabs.add(new PanelTab(parentPage.createStringResource("pageRole.governance"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_GOVERNANCE_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createGovernancePanel(panelId); + } + + @Override + public boolean isVisible() { + return super.isVisible() && getObjectWrapper().getStatus() != ItemStatus.ADDED; + } + }); + + return tabs; + } + + + public AbstractRoleMemberPanel createMemberPanel(String panelId) { + + return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { + + private static final long serialVersionUID = 1L; + + @Override + protected AvailableRelationDto getSupportedRelations() { + return getSupportedMembersTabRelations(); + } + + }; + } + + + public AbstractRoleMemberPanel createGovernancePanel(String panelId) { + + return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { + + private static final long serialVersionUID = 1L; + + @Override + protected AvailableRelationDto getSupportedRelations() { + AvailableRelationDto avariableRelations = getSupportedGovernanceTabRelations(); + avariableRelations.setDefaultRelation(getDefaultGovernanceRelation()); + return avariableRelations; + } + + @Override + protected Map getAuthorizations(QName complexType) { + return getGovernanceTabAuthorizations(); + } + + }; + } + + protected AvailableRelationDto getSupportedMembersTabRelations(){ + List relations = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.ADMINISTRATION, getDetailsPage()); + List governance = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage()); + governance.forEach(r -> relations.remove(r)); + return new AvailableRelationDto(relations); + } + + protected AvailableRelationDto getSupportedGovernanceTabRelations(){ + return new AvailableRelationDto(WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage())); + } + + protected QName getDefaultGovernanceRelation(){ + return WebComponentUtil.getCategoryDefaultRelation(AreaCategoryType.GOVERNANCE); + } + + protected Map getGovernanceTabAuthorizations(){ + return GuiAuthorizationConstants.GOVERNANCE_MEMBERS_AUTHORIZATIONS; + } + + private boolean isAllowedToReadRoleMembership(String abstractRoleOid, PageBase parentPage){ + return isAllowedToReadRoleMembershipItemForType(abstractRoleOid, UserType.class, parentPage) + || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, RoleType.class, parentPage) + || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, OrgType.class, parentPage) + || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, ServiceType.class, parentPage); + } + + private boolean isAllowedToReadRoleMembershipItemForType(String abstractRoleOid, Class type, PageBase parentPage){ + ObjectQuery query = parentPage.getPrismContext().queryFor(type) + .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(abstractRoleOid).build(); + Task task = parentPage.createSimpleTask(OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM); + OperationResult result = task.getResult(); + boolean isAllowed = false; + try { + isAllowed = parentPage.getModelInteractionService() + .canSearch(type, null, null, false, query, task, result); + } catch (Exception ex){ + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't check if user is allowed to search for roleMembershipRef item", ex); + } + return isAllowed; + } + + private String getInducementsCount(){ + PrismObject focus = getObjectModel().getObject().getObject(); + List inducements = focus.asObjectable().getInducement(); + if (inducements == null){ + return ""; + } + return Integer.toString(inducements.size()); + } + + + //TODO what? why? when? + @Override + protected boolean areSavePreviewButtonsEnabled(){ + PrismObjectWrapper focusWrapper = getObjectModel().getObject(); + PrismContainerWrapper assignmentsWrapper; + try { + assignmentsWrapper = focusWrapper.findContainer(AbstractRoleType.F_INDUCEMENT); + } catch (SchemaException e) { + return false; + } + return super.areSavePreviewButtonsEnabled() || isAssignmentsModelChanged(assignmentsWrapper); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java index c8b488437f8..3d0abcc8a31 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java @@ -1,67 +1,65 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.Model; - -/** - * @author semancik - */ -public class AssignmentHolderTypeAssignmentsTabPanel extends AbstractObjectTabPanel { - private static final long serialVersionUID = 1L; - - private static final String ID_ASSIGNMENTS = "assignmentsContainer"; - private static final String ID_ASSIGNMENTS_PANEL = "assignmentsPanel"; - private static final String DOT_CLASS = AssignmentHolderTypeAssignmentsTabPanel.class.getName() + "."; - - public AssignmentHolderTypeAssignmentsTabPanel(String id, Form mainForm, LoadableModel> focusWrapperModel, PageBase page) { - super(id, mainForm, focusWrapperModel); - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - initLayout(); - } - - private void initLayout() { - WebMarkupContainer assignments = new WebMarkupContainer(ID_ASSIGNMENTS); - assignments.setOutputMarkupId(true); - add(assignments); - PrismContainerWrapperModel model = PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), AssignmentHolderType.F_ASSIGNMENT); - SwitchAssignmentTypePanel panel = createPanel(ID_ASSIGNMENTS_PANEL, model); - - assignments.add(panel); - } - - protected SwitchAssignmentTypePanel createPanel(String panelId, PrismContainerWrapperModel model) { - SwitchAssignmentTypePanel panel = new SwitchAssignmentTypePanel(panelId, model != null ? model : Model.of()){ - private static final long serialVersionUID = 1L; - - @Override - protected boolean isReadonly(){ - return AssignmentHolderTypeAssignmentsTabPanel.this.isReadonly(); - } - }; - return panel; - } - - protected boolean isReadonly(){ - return false; - } - -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.Model; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; + +/** + * @author semancik + */ +public class AssignmentHolderTypeAssignmentsTabPanel extends AbstractObjectTabPanel { + private static final long serialVersionUID = 1L; + + private static final String ID_ASSIGNMENTS = "assignmentsContainer"; + private static final String ID_ASSIGNMENTS_PANEL = "assignmentsPanel"; + + public AssignmentHolderTypeAssignmentsTabPanel(String id, Form> mainForm, LoadableModel> focusWrapperModel) { + super(id, mainForm, focusWrapperModel); + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + private void initLayout() { + WebMarkupContainer assignments = new WebMarkupContainer(ID_ASSIGNMENTS); + assignments.setOutputMarkupId(true); + add(assignments); + PrismContainerWrapperModel model = PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), AssignmentHolderType.F_ASSIGNMENT); + SwitchAssignmentTypePanel panel = createPanel(ID_ASSIGNMENTS_PANEL, model); + + assignments.add(panel); + } + + protected SwitchAssignmentTypePanel createPanel(String panelId, PrismContainerWrapperModel model) { + return new SwitchAssignmentTypePanel(panelId, model != null ? model : Model.of()){ + private static final long serialVersionUID = 1L; + + @Override + protected boolean isReadonly(){ + return AssignmentHolderTypeAssignmentsTabPanel.this.isReadonly(); + } + }; + } + + protected boolean isReadonly(){ + return false; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java index 2ea5ed7a45d..7754500543f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java @@ -1,86 +1,72 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.prism.ItemVisibility; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.wicket.markup.html.panel.Panel; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author semancik - */ -public class AssignmentHolderTypeDetailsTabPanel extends AbstractObjectTabPanel { - private static final long serialVersionUID = 1L; - - protected static final String ID_FOCUS_FORM = "focusDetails"; - - private static final String ID_MAIN_PANEL = "main"; - private static final String ID_ACTIVATION_PANEL = "activation"; - private static final String ID_PASSWORD_PANEL = "password"; - - private static final Trace LOGGER = TraceManager.getTrace(AssignmentHolderTypeDetailsTabPanel.class); - - public AssignmentHolderTypeDetailsTabPanel(String id, Form mainForm, - LoadableModel> focusWrapperModel) { - super(id, mainForm, focusWrapperModel); - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - initLayout(); - } - - private void initLayout() { - - try { - - ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder().visibilityHandler(w -> ItemVisibility.AUTO).showOnTopLevel(true); - builder.headerVisibility(false); - - Panel main = getPageBase().initItemPanel(ID_MAIN_PANEL, getObjectWrapper().getTypeName(), - PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.EMPTY_PATH), builder.build()); - add(main); - Panel activation = getPageBase().initItemPanel(ID_ACTIVATION_PANEL, ActivationType.COMPLEX_TYPE, - PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), FocusType.F_ACTIVATION), builder.build()); - add(activation); - Panel password = getPageBase().initItemPanel(ID_PASSWORD_PANEL, PasswordType.COMPLEX_TYPE, - PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD)), builder.build()); - add(password); - } catch (SchemaException e) { - LOGGER.error("Could not create focus details panel. Reason: {}", e.getMessage(), e); - } - } - - private List getVisibleContainers() { - List paths = new ArrayList<>(); - paths.add(ItemPath.EMPTY_PATH); - paths.add(SchemaConstants.PATH_ACTIVATION); - paths.add(SchemaConstants.PATH_PASSWORD); - if (WebModelServiceUtils.isEnableExperimentalFeature(getPageBase())) { - paths.add(AbstractRoleType.F_DATA_PROTECTION); - } - return paths; - } - - -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.prism.ItemVisibility; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.wicket.markup.html.panel.Panel; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author semancik + */ +public class AssignmentHolderTypeDetailsTabPanel extends AbstractObjectTabPanel { + private static final long serialVersionUID = 1L; + + private static final String ID_MAIN_PANEL = "main"; + private static final String ID_ACTIVATION_PANEL = "activation"; + private static final String ID_PASSWORD_PANEL = "password"; + + private static final Trace LOGGER = TraceManager.getTrace(AssignmentHolderTypeDetailsTabPanel.class); + + public AssignmentHolderTypeDetailsTabPanel(String id, Form mainForm, + LoadableModel> focusWrapperModel) { + super(id, mainForm, focusWrapperModel); + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + private void initLayout() { + + try { + + ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder().visibilityHandler(w -> ItemVisibility.AUTO).showOnTopLevel(true); + builder.headerVisibility(false); + + Panel main = getPageBase().initItemPanel(ID_MAIN_PANEL, getObjectWrapper().getTypeName(), + PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.EMPTY_PATH), builder.build()); + add(main); + Panel activation = getPageBase().initItemPanel(ID_ACTIVATION_PANEL, ActivationType.COMPLEX_TYPE, + PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), FocusType.F_ACTIVATION), builder.build()); + add(activation); + Panel password = getPageBase().initItemPanel(ID_PASSWORD_PANEL, PasswordType.COMPLEX_TYPE, + PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD)), builder.build()); + add(password); + } catch (SchemaException e) { + LOGGER.error("Could not create focus details panel. Reason: {}", e.getMessage(), e); + } + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java index 0cd6c754bd6..a7275e022ec 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java @@ -1,126 +1,118 @@ -/* - * Copyright (c) 2015-2019 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; -import com.evolveum.midpoint.gui.api.util.HistoryPageTabVisibleBehavior; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.IModel; - -import java.util.ArrayList; -import java.util.List; - - -/** - * Created by honchar - */ -public class AssignmentHolderTypeMainPanel extends AbstractObjectMainPanel{ - private static final long serialVersionUID = 1L; - - private AssignmentHolderTypeAssignmentsTabPanel assignmentsTabPanel = null; - - public AssignmentHolderTypeMainPanel(String id, LoadableModel> objectModel, - PageAdminObjectDetails parentPage) { - super(id, objectModel, parentPage); - } - - @Override - protected List createTabs(final PageAdminObjectDetails parentPage) { - List tabs = new ArrayList<>(); - - tabs.add( - new PanelTab(parentPage.createStringResource("pageAdminFocus.basic"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_BASIC_URL, true, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new AssignmentHolderTypeDetailsTabPanel<>(panelId, getMainForm(), getObjectModel()); - } - }); - - tabs.add( - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.assignments"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_ASSIGNMENTS_URL, true, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new AssignmentHolderTypeAssignmentsTabPanel(panelId, getMainForm(), getObjectModel(), parentPage){ - private static final long serialVersionUID = 1L; - - @Override - protected boolean isReadonly(){ - return AssignmentHolderTypeMainPanel.this.isReadonly(); - } - }; - } - - @Override - public String getCount() { - return Integer.toString(countAssignments()); - } - }); - - return tabs; - } - - protected IModel> unwrapModel() { - return new IModel>() { - - @Override - public PrismObject getObject() { - return getObjectWrapper().getObject(); - } - }; - } - - protected ObjectTabVisibleBehavior getTabVisibility(String authUrl, boolean isVisibleOnHistoryPage, PageAdminObjectDetails parentPage){ - if (isFocusHistoryPage()){ - return new HistoryPageTabVisibleBehavior(unwrapModel(), authUrl, isVisibleOnHistoryPage, parentPage); - } else { - return new ObjectTabVisibleBehavior(unwrapModel(), authUrl, parentPage); - } - } - - protected boolean isFocusHistoryPage(){ - return false; - } - - protected int countAssignments() { - int rv = 0; - PrismObject focus = getObjectModel().getObject().getObject(); - List assignments = focus.asObjectable().getAssignment(); - for (AssignmentType assignment : assignments) { - if (!AssignmentsUtil.isConsentAssignment(assignment) - && AssignmentsUtil.isAssignmentRelevant(assignment) && !AssignmentsUtil.isArchetypeAssignment(assignment)) { - rv++; - } - } - return rv; - } - - //this value will be used independently of object wrapper isReadonly value, - protected boolean isReadonly(){ - return false; - } - - -} +/* + * Copyright (c) 2015-2019 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; +import com.evolveum.midpoint.gui.api.util.HistoryPageTabVisibleBehavior; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; + +import java.util.ArrayList; +import java.util.List; + + +/** + * Created by honchar + */ +public class AssignmentHolderTypeMainPanel extends AbstractObjectMainPanel{ + private static final long serialVersionUID = 1L; + + public AssignmentHolderTypeMainPanel(String id, LoadableModel> objectModel, + PageAdminObjectDetails parentPage) { + super(id, objectModel, parentPage); + } + + @Override + protected List createTabs(final PageAdminObjectDetails parentPage) { + List tabs = new ArrayList<>(); + + tabs.add( + new PanelTab(parentPage.createStringResource("pageAdminFocus.basic"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_BASIC_URL, true, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new AssignmentHolderTypeDetailsTabPanel<>(panelId, getMainForm(), getObjectModel()); + } + }); + + tabs.add( + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.assignments"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_ASSIGNMENTS_URL, true, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new AssignmentHolderTypeAssignmentsTabPanel(panelId, getMainForm(), getObjectModel()){ + private static final long serialVersionUID = 1L; + + @Override + protected boolean isReadonly(){ + return AssignmentHolderTypeMainPanel.this.isReadonly(); + } + }; + } + + @Override + public String getCount() { + return Integer.toString(countAssignments()); + } + }); + + return tabs; + } + + protected IModel> unwrapModel() { + return (IModel>) () -> getObjectWrapper().getObject(); + } + + protected ObjectTabVisibleBehavior getTabVisibility(String authUrl, boolean isVisibleOnHistoryPage, PageAdminObjectDetails parentPage){ + if (isFocusHistoryPage()){ + return new HistoryPageTabVisibleBehavior<>(unwrapModel(), authUrl, isVisibleOnHistoryPage, parentPage); + } else { + return new ObjectTabVisibleBehavior<>(unwrapModel(), authUrl, parentPage); + } + } + + protected boolean isFocusHistoryPage(){ + return false; + } + + protected int countAssignments() { + int rv = 0; + PrismObject focus = getObjectModel().getObject().getObject(); + List assignments = focus.asObjectable().getAssignment(); + for (AssignmentType assignment : assignments) { + if (!AssignmentsUtil.isConsentAssignment(assignment) + && AssignmentsUtil.isAssignmentRelevant(assignment) && !AssignmentsUtil.isArchetypeAssignment(assignment)) { + rv++; + } + } + return rv; + } + + //this value will be used independently of object wrapper isReadonly value, + protected boolean isReadonly(){ + return false; + } + + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java index 4b367e16e6e..bc3d844da5a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java @@ -1,334 +1,296 @@ -/* - * Copyright (c) 2015-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.List; - -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.wf.util.QueryUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.IModel; -import org.apache.wicket.util.string.StringValue; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.model.api.ModelAuthorizationAction; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; - -/** - * @author semancik - * - */ -public class FocusMainPanel extends AssignmentHolderTypeMainPanel { - - private static final long serialVersionUID = 1L; - - private static final Trace LOGGER = TraceManager.getTrace(FocusMainPanel.class); - - private LoadableModel> projectionModel; - - public FocusMainPanel(String id, LoadableModel> objectModel, - LoadableModel> projectionModel, - PageAdminObjectDetails parentPage) { - super(id, objectModel, parentPage); - Validate.notNull(projectionModel, "Null projection model"); - this.projectionModel = projectionModel; - initLayout(parentPage); - } - - private void initLayout(final PageAdminObjectDetails parentPage) { - getMainForm().setMultiPart(true); - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - StringValue oidValue = getPage().getPageParameters().get(OnePageParameterEncoder.PARAMETER); - - } - - private ObjectQuery createTaskQuery(String oid, PageBase page) { - if (oid == null) { - oid = "non-existent"; // TODO !!!!!!!!!!!!!!!!!!!! - } - return page.getPrismContext().queryFor(CaseType.class) - .item(CaseType.F_OBJECT_REF).ref(oid) - .and() - .item(CaseType.F_ARCHETYPE_REF) - .ref(SystemObjectsType.ARCHETYPE_OPERATION_REQUEST.value()) - .and() - .not() - .item(CaseType.F_STATE) - .eq(SchemaConstants.CASE_STATE_CLOSED) - .desc(ItemPath.create(CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP)) - .build(); - } - - @Override - protected List createTabs(final PageAdminObjectDetails parentPage) { - List tabs = super.createTabs(parentPage); - - List objectFormTypes = parentPage.getObjectFormTypes(); - // default tabs are always added to component structure, visibility is decided later in - // visible behavior based on adminGuiConfiguration - addDefaultTabs(parentPage, tabs); - addSpecificTabs(parentPage, tabs); - if (objectFormTypes == null) { - return tabs; - } - - for (ObjectFormType objectFormType : objectFormTypes) { - final FormSpecificationType formSpecificationType = objectFormType.getFormSpecification(); - if (formSpecificationType == null){ - continue; - } - String title = formSpecificationType.getTitle(); - if (title == null) { - title = "pageAdminFocus.extended"; - } - - if (StringUtils.isEmpty(formSpecificationType.getPanelClass())) { - continue; - } - - tabs.add( - new PanelTab(parentPage.createStringResource(title)) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createTabPanel(panelId, formSpecificationType, parentPage); - } - }); - } - - return tabs; - } - - protected WebMarkupContainer createTabPanel(String panelId, FormSpecificationType formSpecificationType, - PageAdminObjectDetails parentPage) { - String panelClassName = formSpecificationType.getPanelClass(); - - Class panelClass; - try { - panelClass = Class.forName(panelClassName); - } catch (ClassNotFoundException e) { - throw new SystemException("Panel class '"+panelClassName+"' as specified in admin GUI configuration was not found", e); - } - if (AbstractFocusTabPanel.class.isAssignableFrom(panelClass)) { - Constructor constructor; - try { - constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class, LoadableModel.class); - } catch (NoSuchMethodException | SecurityException e) { - throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,LoadableModel,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); - } - AbstractFocusTabPanel tabPanel; - try { - tabPanel = (AbstractFocusTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel(), projectionModel); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); - } - return tabPanel; - } else if (AbstractObjectTabPanel.class.isAssignableFrom(panelClass)) { - Constructor constructor; - try { - constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class); - } catch (NoSuchMethodException | SecurityException e) { - throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); - } - AbstractObjectTabPanel tabPanel; - try { - tabPanel = (AbstractObjectTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel()); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); - } - return tabPanel; - - } else { - throw new UnsupportedOperationException("Tab panels that are not subclasses of AbstractObjectTabPanel or AbstractFocusTabPanel are not supported yet (got "+panelClass+")"); - } - } - - protected WebMarkupContainer createFocusDetailsTabPanel(String panelId, PageAdminObjectDetails parentPage) { - return new AssignmentHolderTypeDetailsTabPanel(panelId, getMainForm(), getObjectModel()); - } - - protected WebMarkupContainer createFocusProjectionsTabPanel(String panelId, PageAdminObjectDetails parentPage) { - return new FocusProjectionsTabPanel<>(panelId, getMainForm(), getObjectModel(), projectionModel); - } - - protected WebMarkupContainer createObjectHistoryTabPanel(String panelId, PageAdminObjectDetails parentPage) { - return new ObjectHistoryTabPanel(panelId, getMainForm(), getObjectModel()){ - protected void currentStateButtonClicked(AjaxRequestTarget target, PrismObject object, String date){ - viewObjectHistoricalDataPerformed(target, object, date); - } - }; - } - - protected void viewObjectHistoricalDataPerformed(AjaxRequestTarget target, PrismObject object, String date){ - } - - protected IModel> unwrapModel() { - return new IModel>() { - - @Override - public PrismObject getObject() { - return getObjectWrapper().getObject(); - } - }; - } - - protected void addSpecificTabs(final PageAdminObjectDetails parentPage, List tabs) { - } - - private void addDefaultTabs(final PageAdminObjectDetails parentPage, List tabs) { - - tabs.add(1, - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.projections"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_PROJECTIONS_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createFocusProjectionsTabPanel(panelId, parentPage); - } - - @Override - public String getCount() { - return Integer.toString(projectionModel.getObject() == null ? 0 : projectionModel.getObject().size()); - } - }); - - if (WebComponentUtil.isAuthorized(ModelAuthorizationAction.AUDIT_READ.getUrl()) && getObjectWrapper().getStatus() != ItemStatus.ADDED){ - tabs.add( - new PanelTab(parentPage.createStringResource("pageAdminFocus.objectHistory"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_OBJECT_HISTORY_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createObjectHistoryTabPanel(panelId, parentPage); - } - }); - } - - tabs.add( - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.cases"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusTasksTabPanel(panelId, getMainForm(), getObjectModel(), - countFocusObjectTasks(parentPage) > 0); - } - - @Override - public String getCount() { - return Integer.toString(countFocusObjectTasks(parentPage)); - } - }); - - tabs.add( - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.triggers"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusTriggersTabPanel(panelId, getMainForm(), getObjectModel()); - } - - @Override - public String getCount() { - return Integer.toString(countFocusObjectTriggers()); - } - }); - - } - - private int countFocusObjectTasks(PageBase parentPage){ - String oid = null; - if (getObjectWrapper() == null || StringUtils.isEmpty(getObjectWrapper().getOid())) { - oid = "non-existent"; - } else { - oid = getObjectWrapper().getOid(); - } - ObjectQuery casesQuery = QueryUtils.filterForCasesOverUser(parentPage.getPrismContext().queryFor(CaseType.class), oid) - .desc(ItemPath.create(CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP)) - .build(); - return WebModelServiceUtils.countObjects(CaseType.class, casesQuery, parentPage); - } - - private int countFocusObjectTriggers(){ - PrismObjectWrapper objectWrapper = getObjectWrapper(); - if (objectWrapper.getObject() != null){ - F focusObject = objectWrapper.getObject().asObjectable(); - return focusObject.getTrigger() != null ? focusObject.getTrigger().size() : 0; - } - return 0; - } - - @Override - @Deprecated - protected boolean areSavePreviewButtonsEnabled() { - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismContainerWrapper assignmentsWrapper; - try { - assignmentsWrapper = focusWrapper.findContainer(FocusType.F_ASSIGNMENT); - } catch (SchemaException e) { - LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); - return false; - } - return isAssignmentsModelChanged(assignmentsWrapper); - } - - protected boolean isAssignmentsModelChanged(PrismContainerWrapper assignmentsWrapper){ - if (assignmentsWrapper != null) { - for (PrismContainerValueWrapper assignmentWrapper : assignmentsWrapper.getValues()) { - if (ValueStatus.DELETED.equals(assignmentWrapper.getStatus()) || - ValueStatus.ADDED.equals(assignmentWrapper.getStatus())) { - return true; - } - } - } - return false; - } - -} +/* + * Copyright (c) 2015-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; +import com.evolveum.midpoint.model.api.ModelAuthorizationAction; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.wf.util.QueryUtils; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +/** + * @author semancik + * + */ +public class FocusMainPanel extends AssignmentHolderTypeMainPanel { + + private static final long serialVersionUID = 1L; + + private static final Trace LOGGER = TraceManager.getTrace(FocusMainPanel.class); + + private LoadableModel> projectionModel; + + public FocusMainPanel(String id, LoadableModel> objectModel, + LoadableModel> projectionModel, + PageAdminObjectDetails parentPage) { + super(id, objectModel, parentPage); + Validate.notNull(projectionModel, "Null projection model"); + this.projectionModel = projectionModel; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + getMainForm().setMultiPart(true); + } + + @Override + protected List createTabs(final PageAdminObjectDetails parentPage) { + List tabs = super.createTabs(parentPage); + + List objectFormTypes = parentPage.getObjectFormTypes(); + // default tabs are always added to component structure, visibility is decided later in + // visible behavior based on adminGuiConfiguration + addDefaultTabs(parentPage, tabs); + addSpecificTabs(parentPage, tabs); + if (objectFormTypes == null) { + return tabs; + } + + for (ObjectFormType objectFormType : objectFormTypes) { + final FormSpecificationType formSpecificationType = objectFormType.getFormSpecification(); + if (formSpecificationType == null){ + continue; + } + String title = formSpecificationType.getTitle(); + if (title == null) { + title = "pageAdminFocus.extended"; + } + + if (StringUtils.isEmpty(formSpecificationType.getPanelClass())) { + continue; + } + + tabs.add( + new PanelTab(parentPage.createStringResource(title)) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createTabPanel(panelId, formSpecificationType); + } + }); + } + + return tabs; + } + + protected WebMarkupContainer createTabPanel(String panelId, FormSpecificationType formSpecificationType) { + String panelClassName = formSpecificationType.getPanelClass(); + + Class panelClass; + try { + panelClass = Class.forName(panelClassName); + } catch (ClassNotFoundException e) { + throw new SystemException("Panel class '"+panelClassName+"' as specified in admin GUI configuration was not found", e); + } + if (AbstractFocusTabPanel.class.isAssignableFrom(panelClass)) { + Constructor constructor; + try { + constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class, LoadableModel.class); + } catch (NoSuchMethodException | SecurityException e) { + throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,LoadableModel,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); + } + AbstractFocusTabPanel tabPanel; + try { + tabPanel = (AbstractFocusTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel(), projectionModel); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); + } + return tabPanel; + } else if (AbstractObjectTabPanel.class.isAssignableFrom(panelClass)) { + Constructor constructor; + try { + constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class); + } catch (NoSuchMethodException | SecurityException e) { + throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); + } + AbstractObjectTabPanel tabPanel; + try { + tabPanel = (AbstractObjectTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel()); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); + } + return tabPanel; + + } else { + throw new UnsupportedOperationException("Tab panels that are not subclasses of AbstractObjectTabPanel or AbstractFocusTabPanel are not supported yet (got "+panelClass+")"); + } + } + + protected WebMarkupContainer createFocusProjectionsTabPanel(String panelId) { + return new FocusProjectionsTabPanel<>(panelId, getMainForm(), getObjectModel(), projectionModel); + } + + protected WebMarkupContainer createObjectHistoryTabPanel(String panelId) { + return new ObjectHistoryTabPanel(panelId, getMainForm(), getObjectModel()){ + protected void currentStateButtonClicked(AjaxRequestTarget target, PrismObject object, String date){ + viewObjectHistoricalDataPerformed(target, object, date); + } + }; + } + + protected void viewObjectHistoricalDataPerformed(AjaxRequestTarget target, PrismObject object, String date){ + } + + protected IModel> unwrapModel() { + return (IModel>) () -> getObjectWrapper().getObject(); + } + + protected void addSpecificTabs(final PageAdminObjectDetails parentPage, List tabs) { + } + + private void addDefaultTabs(final PageAdminObjectDetails parentPage, List tabs) { + + tabs.add(1, + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.projections"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_PROJECTIONS_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createFocusProjectionsTabPanel(panelId); + } + + @Override + public String getCount() { + return Integer.toString(projectionModel.getObject() == null ? 0 : projectionModel.getObject().size()); + } + }); + + if (WebComponentUtil.isAuthorized(ModelAuthorizationAction.AUDIT_READ.getUrl()) && getObjectWrapper().getStatus() != ItemStatus.ADDED){ + tabs.add( + new PanelTab(parentPage.createStringResource("pageAdminFocus.objectHistory"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_OBJECT_HISTORY_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createObjectHistoryTabPanel(panelId); + } + }); + } + + tabs.add( + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.cases"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusTasksTabPanel<>(panelId, getMainForm(), getObjectModel(), + countFocusObjectTasks(parentPage) > 0); + } + + @Override + public String getCount() { + return Integer.toString(countFocusObjectTasks(parentPage)); + } + }); + + tabs.add( + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.triggers"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusTriggersTabPanel<>(panelId, getMainForm(), getObjectModel()); + } + + @Override + public String getCount() { + return Integer.toString(countFocusObjectTriggers()); + } + }); + + } + + private int countFocusObjectTasks(PageBase parentPage){ + String oid; + if (getObjectWrapper() == null || StringUtils.isEmpty(getObjectWrapper().getOid())) { + oid = "non-existent"; + } else { + oid = getObjectWrapper().getOid(); + } + ObjectQuery casesQuery = QueryUtils.filterForCasesOverUser(parentPage.getPrismContext().queryFor(CaseType.class), oid) + .desc(ItemPath.create(CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP)) + .build(); + return WebModelServiceUtils.countObjects(CaseType.class, casesQuery, parentPage); + } + + private int countFocusObjectTriggers(){ + PrismObjectWrapper objectWrapper = getObjectWrapper(); + if (objectWrapper.getObject() != null){ + F focusObject = objectWrapper.getObject().asObjectable(); + return focusObject.getTrigger() != null ? focusObject.getTrigger().size() : 0; + } + return 0; + } + + @Override + protected boolean areSavePreviewButtonsEnabled() { + PrismObjectWrapper focusWrapper = getObjectModel().getObject(); + PrismContainerWrapper assignmentsWrapper; + try { + assignmentsWrapper = focusWrapper.findContainer(FocusType.F_ASSIGNMENT); + } catch (SchemaException e) { + LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); + return false; + } + return isAssignmentsModelChanged(assignmentsWrapper); + } + + protected boolean isAssignmentsModelChanged(PrismContainerWrapper assignmentsWrapper){ + if (assignmentsWrapper != null) { + for (PrismContainerValueWrapper assignmentWrapper : assignmentsWrapper.getValues()) { + if (ValueStatus.DELETED.equals(assignmentWrapper.getStatus()) || + ValueStatus.ADDED.equals(assignmentWrapper.getStatus())) { + return true; + } + } + } + return false; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java index 449ca6a1cfc..1db6ea238c4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java @@ -92,7 +92,7 @@ public String getExcludeOid() { public IModel getLabel() { return createStringResource("FocusType.delegations"); - }; + } @Override protected List createAssignmentMenu() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java index d4a04e5f791..7b2c0217d91 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java @@ -1,35 +1,35 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.web.component.refresh; - -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; - -/** - * Refreshable page (or component). - * - * @author mederly - */ -public interface Refreshable { - - /** - * Called on manually requested refresh action. - * @param target The request target. - */ - void refresh(AjaxRequestTarget target); - - /** - * Component to which the refreshing timer should be attached. - */ - Component getRefreshingBehaviorParent(); - - /** - * Current refreshing interval (may depend on page content). - */ - int getRefreshInterval(); -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.web.component.refresh; + +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; + +/** + * Refreshable page (or component). + * + * @author mederly + */ +public interface Refreshable { + + /** + * Called on manually requested refresh action. + * @param target The request target. + */ + void refresh(AjaxRequestTarget target); + + /** + * If the refresh is enabled + */ + boolean isRefreshEnabled(); + + /** + * Current refreshing interval (may depend on page content). + */ + int getRefreshInterval(); +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java index 391a369ba62..ea972535e01 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java @@ -1,60 +1,48 @@ -/* - * Copyright (c) 2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.page.admin; - -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; - -public abstract class PageAdminAbstractRole extends PageAdminFocus { - private static final long serialVersionUID = 1L; - - public PageAdminAbstractRole() { - super(); - } - - public PageAdminAbstractRole(PageParameters parameters) { - super(parameters); - } - - public PageAdminAbstractRole(final PrismObject abstractRole) { - super(abstractRole); - } - - public PageAdminAbstractRole(final PrismObject userToEdit, boolean isNewObject) { - super(userToEdit, isNewObject); - } - - - public PageAdminAbstractRole(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { - super(abstractRole, isNewObject, isReadonly); - } - - @Override - protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws SchemaException { - super.prepareObjectDeltaForModify(focusDelta); - - PrismObject abstractRole = getObjectWrapper().getObject(); - PrismContainerDefinition def = abstractRole.getDefinition() - .findContainerDefinition(AbstractRoleType.F_INDUCEMENT); - } - - @Override - protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { - super.prepareObjectForAdd(focus); - } - - @Override - protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - super.initializeModel(objectToEdit, isNewObject, isReadonly); - } -} +/* + * Copyright (c) 2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin; + +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; + +public abstract class PageAdminAbstractRole extends PageAdminFocus { + private static final long serialVersionUID = 1L; + + public PageAdminAbstractRole() { + super(); + } + + public PageAdminAbstractRole(PageParameters parameters) { + super(parameters); + } + + public PageAdminAbstractRole(final PrismObject abstractRole) { + super(abstractRole); + } + + public PageAdminAbstractRole(final PrismObject userToEdit, boolean isNewObject) { + super(userToEdit, isNewObject); + } + + + public PageAdminAbstractRole(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { + super(abstractRole, isNewObject, isReadonly); + } + + @Override + protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { + super.prepareObjectForAdd(focus); + } + + @Override + protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + super.initializeModel(objectToEdit, isNewObject, isReadonly); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java index 99c619975b9..7ee98ad50b6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java @@ -1,1027 +1,820 @@ -/* - * Copyright (c) 2010-2019 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.page.admin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Session; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.protocol.http.WebSession; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; -import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.context.AssignmentPath; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignment; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignmentTarget; -import com.evolveum.midpoint.model.api.context.EvaluatedConstruction; -import com.evolveum.midpoint.model.api.context.ModelContext; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.OriginType; -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismContainerValue; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.PrismReference; -import com.evolveum.midpoint.prism.PrismReferenceDefinition; -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.delta.ContainerDelta; -import com.evolveum.midpoint.prism.delta.DeltaSetTriple; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.delta.ReferenceDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.schema.SchemaRegistry; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.NoFocusNameSchemaException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; -import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; -import com.evolveum.midpoint.web.page.admin.users.component.AssignmentInfoDto; -import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; -import com.evolveum.midpoint.web.security.util.SecurityUtils; -import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; -import com.evolveum.midpoint.web.util.validation.SimpleValidationError; - -public abstract class PageAdminFocus extends PageAdminObjectDetails - implements ProgressReportingAwarePage { - private static final long serialVersionUID = 1L; - - private LoadableModel> projectionModel; - private LoadableModel> delegatedToMeModel; - - private static final String DOT_CLASS = PageAdminFocus.class.getName() + "."; - private static final String OPERATION_RECOMPUTE_ASSIGNMENTS = DOT_CLASS + "recomputeAssignments"; - - private static final String OPERATION_LOAD_SHADOW = DOT_CLASS + "loadShadow"; - - private static final Trace LOGGER = TraceManager.getTrace(PageAdminFocus.class); - - public PageAdminFocus() { - initialize(null); - } - - public PageAdminFocus(PageParameters parameters) { - getPageParameters().overwriteWith(parameters); - initialize(null); - } - - public PageAdminFocus(final PrismObject userToEdit) { - initialize(userToEdit); - } - - public PageAdminFocus(final PrismObject unitToEdit, boolean isNewObject) { - initialize(unitToEdit, isNewObject); - } - - public PageAdminFocus(final PrismObject unitToEdit, boolean isNewObject, boolean isReadonly) { - initialize(unitToEdit, isNewObject, isReadonly); - } - - - @Override - protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - super.initializeModel(objectToEdit, isNewObject, isReadonly); - - projectionModel = new LoadableModel>(false) { - private static final long serialVersionUID = 1L; - - @Override - protected List load() { - return loadShadowWrappers(true); - } - }; - - delegatedToMeModel= new LoadableModel>(false) { - - private static final long serialVersionUID = 1L; - @Override - protected List load() { - return loadDelegatedToMe(); - } - }; - - } - - public LoadableModel> getProjectionModel() { - return projectionModel; - } - - public LoadableModel> getDelegatedToMeModel() { - return delegatedToMeModel; - } - - public List getFocusShadows() { - return projectionModel.getObject(); - } - - protected void reviveModels() throws SchemaException { - super.reviveModels(); - WebComponentUtil.revive(projectionModel, getPrismContext()); - } - - @Override - public void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync) { - - if (previewRequested) { - finishPreviewProcessing(target, result); - return; - } - if (result.isSuccess() && getDelta() != null && SecurityUtils.getPrincipalUser().getOid().equals(getDelta().getOid())) { - FocusType focus = null; - if (getObjectWrapper().getObject().asObjectable() instanceof UserType){ - focus = getObjectWrapper().getObject().asObjectable(); - } - Session.get().setLocale(WebModelServiceUtils.getLocale(focus)); - LOGGER.debug("Using {} as locale", getLocale()); - WebSession.get().getClientInfo().getProperties(). - setTimeZone(WebModelServiceUtils.getTimezone(focus)); - LOGGER.debug("Using {} as time zone", WebSession.get().getClientInfo().getProperties().getTimeZone()); - } - boolean focusAddAttempted = getDelta() != null && getDelta().isAdd(); - boolean focusAddSucceeded = focusAddAttempted && StringUtils.isNotEmpty(getDelta().getOid()); - - // we don't want to allow resuming editing if a new focal object was created (on second 'save' there would be a conflict with itself) - // and also in case of partial errors, like those related to projections (many deltas would be already executed, and this could cause problems on second 'save'). - boolean canContinueEditing = !focusAddSucceeded && result.isFatalError(); - - boolean canExitPage; - if (returningFromAsync) { - canExitPage = getProgressPanel().isAllSuccess() || result.isInProgress() || result.isHandledError(); // if there's at least a warning in the progress table, we would like to keep the table open - } else { - canExitPage = !canContinueEditing; // no point in staying on page if we cannot continue editing (in synchronous case i.e. no progress table present) - } - - if (!isKeepDisplayingResults() && canExitPage) { - showResult(result); - redirectBack(); - } else { - if (returningFromAsync) { - getProgressPanel().showBackButton(target); - getProgressPanel().hideAbortButton(target); - } - showResult(result); - target.add(getFeedbackPanel()); - - if (canContinueEditing) { - getProgressPanel().hideBackButton(target); - getProgressPanel().showContinueEditingButton(target); - } - } - } - - private void finishPreviewProcessing(AjaxRequestTarget target, OperationResult result) { - getMainPanel().setVisible(true); - getProgressPanel().hide(); - getProgressPanel().hideAbortButton(target); - getProgressPanel().hideBackButton(target); - getProgressPanel().hideContinueEditingButton(target); - - showResult(result); - target.add(getFeedbackPanel()); - - Map, ModelContext> modelContextMap = new LinkedHashMap<>(); - modelContextMap.put(getObjectWrapper().getObject(), getProgressPanel().getPreviewResult()); - - processAdditionalFocalObjectsForPreview(modelContextMap); - - navigateToNext(new PagePreviewChanges(modelContextMap, getModelInteractionService())); - } - - protected void processAdditionalFocalObjectsForPreview(Map, ModelContext> modelContextMap){ - } - - @Override - public void continueEditing(AjaxRequestTarget target) { - getMainPanel().setVisible(true); - getProgressPanel().hide(); - getProgressPanel().hideAbortButton(target); - getProgressPanel().hideBackButton(target); - getProgressPanel().hideContinueEditingButton(target); - target.add(this); - } - - private List loadShadowWrappers(boolean noFetch) { - List list = new ArrayList<>(); - - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismObject focus = focusWrapper.getObject(); - PrismReference prismReference = focus.findReference(UserType.F_LINK_REF); - if (prismReference == null || prismReference.isEmpty()) { - return new ArrayList<>(); - } - List references = prismReference.getValues(); - - Task task = createSimpleTask(OPERATION_LOAD_SHADOW); - for (PrismReferenceValue reference : references) { - if(reference == null || (reference.getOid() == null && reference.getTargetType() == null)) { - LOGGER.trace("Skiping reference for shadow with null oid"); - continue; // default value - } - OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); - PrismObject projection = getPrismObjectForWrapper(ShadowType.class, reference.getOid(), - noFetch, task, subResult, createLoadOptionForShadowWrapper()); - - if(projection == null) { -// showResult(subResult, "pageAdminFocus.message.couldntLoadShadowProjection"); - LOGGER.error("Couldn't load shadow projection"); - continue; - } - - try { - ShadowWrapper wrapper = loadShadowWrapper(projection, task, subResult); - wrapper.setLoadWithNoFetch(noFetch); - - if (wrapper != null) { - list.add((ShadowWrapper)wrapper); - } else { - showResult(subResult, "pageAdminFocus.message.shadowWrapperIsNull"); - LOGGER.error("ShadowWrapper is null"); - } - - //TODO catch Exception/Runtim,eException, Throwable - } catch (SchemaException e) { - showResult(subResult, "pageAdminFocus.message.couldntCreateShadowWrapper"); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't create shadow wrapper", e); - } - } - return list; - } - - private Collection> createLoadOptionForShadowWrapper(){ - return getSchemaHelper().getOperationOptionsBuilder() - .item(ShadowType.F_RESOURCE_REF).resolve().readOnly() - .build(); - } - - public ShadowWrapper loadShadowWrapper(PrismObject projection, Task task, OperationResult result) throws SchemaException{ - PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(projection.getDefinition()); - WrapperContext context = new WrapperContext(task, result); - context.setCreateIfEmpty(false); - ShadowWrapper wrapper = (ShadowWrapper) factory.createObjectWrapper(projection, ItemStatus.NOT_CHANGED, context); - wrapper.setProjectionStatus(UserDtoStatus.MODIFY); - return wrapper; - } - - public void loadFullShadow(PrismObjectValueWrapper shadowWrapperValue, AjaxRequestTarget target) { - if(shadowWrapperValue.getRealValue() == null) { - error(getString("pageAdminFocus.message.couldntCreateShadowWrapper")); - LOGGER.error("Couldn't create shadow wrapper, because RealValue is null in " + shadowWrapperValue); - return; - } - String oid = shadowWrapperValue.getRealValue().getOid(); - Task task = createSimpleTask(OPERATION_LOAD_SHADOW); - OperationResult result = task.getResult(); - PrismObject projection = getPrismObjectForWrapper(ShadowType.class, oid, false, task, - result, createLoadOptionForShadowWrapper()); - - if (projection == null) { - result.recordFatalError(getString("PageAdminFocus.message.loadFullShadow.fatalError", shadowWrapperValue.getRealValue())); - showResult(result); - target.add(getFeedbackPanel()); - return; - } - - ShadowWrapper shadowWrapperNew; - try { - shadowWrapperNew = loadShadowWrapper(projection, task, result); - - if (shadowWrapperNew == null) { - error(getString("pageAdminFocus.message.shadowWrapperIsNull")); - LOGGER.error("ShadowWrapper is null"); - return; - } - - shadowWrapperValue.getItems().clear(); - shadowWrapperValue.getItems().addAll((Collection) shadowWrapperNew.getValue().getItems()); - ((ShadowWrapper)shadowWrapperValue.getParent()).setLoadWithNoFetch(false); - } catch (SchemaException e) { - error(getString("pageAdminFocus.message.couldntCreateShadowWrapper")); - LOGGER.error("Couldn't create shadow wrapper", e); - } - } - -// @Override -// protected List> loadOrgWrappers() { -// return loadSubwrappers(OrgType.class, UserType.F_PARENT_ORG_REF, false); -// } - -// private List> loadSubwrappers(Class type, -// ItemName propertyToLoad, boolean noFetch) { -// List> list = new ArrayList<>(); -// -// PrismObjectWrapper focusWrapper = getObjectModel().getObject(); -// PrismObject focus = focusWrapper.getObject(); -// PrismReference prismReference = focus.findReference(propertyToLoad); -// if (prismReference == null) { -// return new ArrayList<>(); -// } -// List references = prismReference.getValues(); -// -// Task task = createSimpleTask(OPERATION_LOAD_SHADOW); -// for (PrismReferenceValue reference : references) { -// FocusSubwrapperDto subWrapper = loadSubWrapperDto(type, reference.getOid(), noFetch, task); -// if (subWrapper != null) { -// list.add(subWrapper); -// } -// } -// -// return list; -// } - - private PrismObject getPrismObjectForWrapper(Class type, String oid, boolean noFetch, - Task task, OperationResult subResult, Collection> loadOptions){ - if (oid == null) { - return null; - } - - if (noFetch) { - GetOperationOptions rootOptions = SelectorOptions.findRootOptions(loadOptions); - if (rootOptions == null) { - loadOptions.add(new SelectorOptions<>(GetOperationOptions.createNoFetch())); - } else { - rootOptions.setNoFetch(true); - } - } - - PrismObject projection = WebModelServiceUtils.loadObject(type, oid, loadOptions, this, task, subResult); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Loaded projection {} ({}):\n{}", oid, loadOptions, projection==null?null:projection.debugDump()); - } - - return projection; - } - -// private FocusSubwrapperDto loadSubWrapperDto(Class type, String oid, boolean noFetch, Task task) { -// OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); -// Collection> loadOptions = new ArrayList<>(); -// PrismObject projection = getPrismObjectForWrapper(type, oid, noFetch, task, subResult, loadOptions); -// if (projection == null) { -// // No access or error -// // TODO actually it would be nice to show an error if the shadow repo object does not exist -// return null; -// } -// String resourceName = null; -// try { -// S projectionType = projection.asObjectable(); -// -// OperationResultType fetchResult = projectionType.getFetchResult(); -// StringBuilder description = new StringBuilder(); -// if (ShadowType.class.equals(type)) { -// ShadowType shadowType = (ShadowType) projectionType; -// ResourceType resource = shadowType.getResource(); -// resourceName = WebComponentUtil.getName(resource); -// -// if (shadowType.getIntent() != null) { -// description.append(shadowType.getIntent()).append(", "); -// } -// } else if (OrgType.class.equals(type)) { -// OrgType orgType = (OrgType) projectionType; -// resourceName = orgType.getDisplayName() != null -// ? WebComponentUtil.getOrigStringFromPoly(orgType.getDisplayName()) : ""; -// } -// description.append(WebComponentUtil.getOrigStringFromPoly(projectionType.getName())); -// -// ObjectWrapperOld wrapper = ObjectWrapperUtil.createObjectWrapper(resourceName, -// description.toString(), projection, ContainerStatus.MODIFYING, task, this); -// wrapper.setLoadOptions(loadOptions); -// wrapper.setFetchResult(OperationResult.createOperationResult(fetchResult)); -// wrapper.setSelectable(true); -// wrapper.setMinimalized(true); -// -//// wrapper.initializeContainers(this); -// -// subResult.computeStatus(); -// FocusSubwrapperDto ret = new FocusSubwrapperDto<>(wrapper, UserDtoStatus.MODIFY); -// return ret; -// -// } catch (Exception ex) { -// subResult.recordFatalError("Couldn't load account." + ex.getMessage(), ex); -// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load account", ex); -// subResult.computeStatus(); -// return new FocusSubwrapperDto<>(false, resourceName, subResult); -// } -// } - - private List loadDelegatedToMe() { - List list = new ArrayList<>(); - - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismObject focus = focusWrapper.getObject(); - List assignments = focus.asObjectable().getAssignment(); - for (AssignmentType assignment : assignments) { - if (assignment.getTargetRef() != null && - UserType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType())) { - AssignmentEditorDto dto = new AssignmentEditorDto(UserDtoStatus.MODIFY, assignment, this); - dto.setSimpleView(true); - dto.setEditable(false); - list.add(dto); - } - } - - Collections.sort(list); - - return list; - } - - protected List getPolicyRulesList(List assignments, UserDtoStatus status){ - List list = new ArrayList<>(); - for (AssignmentType assignment : assignments) { - if (AssignmentsUtil.isPolicyRuleAssignment(assignment)) { - //TODO set status - list.add(assignment); - } - } - return list; - } - - @Override - protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { - super.prepareObjectForAdd(focus); - F focusType = focus.asObjectable(); - // handle added accounts - - List shadowsToAdd = prepareShadowObject(getFocusShadows()); - for (ShadowType shadowToAdd : shadowsToAdd) { - addDefaultKindAndIntent(shadowToAdd.asPrismObject()); - ObjectReferenceType linkRef = new ObjectReferenceType(); - linkRef.asReferenceValue().setObject(shadowToAdd.asPrismObject()); - focusType.getLinkRef().add(linkRef); - } - -// List orgsToAdd = prepareSubobject(getParentOrgs()); -// if (!orgsToAdd.isEmpty()){ -// focusType.getParentOrg().addAll(orgsToAdd); -// } - - } - - @Override - protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws SchemaException { - super.prepareObjectDeltaForModify(focusDelta); - // handle accounts - PrismObjectDefinition objectDefinition = getObjectDefinition(); - PrismReferenceDefinition refDef = objectDefinition.findReferenceDefinition(FocusType.F_LINK_REF); - ReferenceDelta refDelta = prepareUserAccountsDeltaForModify(refDef); - if (!refDelta.isEmpty()) { - focusDelta.addModification(refDelta); - } - -// refDef = objectDefinition.findReferenceDefinition(FocusType.F_PARENT_ORG_REF); -// refDelta = prepareUserOrgsDeltaForModify(refDef); -// if (!refDelta.isEmpty()) { -// focusDelta.addModification(refDelta); -// } - } - - protected PrismObjectDefinition getObjectDefinition() { - SchemaRegistry registry = getPrismContext().getSchemaRegistry(); - return registry - .findObjectDefinitionByCompileTimeClass(getCompileTimeClass()); - } - - protected ContainerDelta handleAssignmentDeltas(ObjectDelta focusDelta, - List assignments, PrismContainerDefinition def, - boolean isDelegation) throws SchemaException { - ContainerDelta assDelta = getPrismContext().deltaFactory().container().create(ItemPath.EMPTY_PATH, def.getItemName(), def); - - for (AssignmentEditorDto assDto : assignments) { - PrismContainerValue newValue = assDto.getNewValue(getPrismContext()); - - switch (assDto.getStatus()) { - case ADD: - newValue.applyDefinition(def, false); - assDelta.addValueToAdd(newValue.clone()); - break; - case DELETE: - PrismContainerValue oldValue = assDto.getOldValue(); - if (isDelegation){ - oldValue.applyDefinition(def, false); - } else { - oldValue.applyDefinition(def); - } - assDelta.addValueToDelete(oldValue.clone()); - break; - case MODIFY: - if (!assDto.isModified(getPrismContext())) { - LOGGER.trace("Assignment '{}' not modified.", new Object[] { assDto.getName() }); - continue; - } - - handleModifyAssignmentDelta(assDto, def, newValue, focusDelta); - break; - default: - warn(getString("pageAdminUser.message.illegalAssignmentState", assDto.getStatus())); - } - } - - if (!assDelta.isEmpty()) { - assDelta = focusDelta.addModification(assDelta); - } - - return assDelta; - } - - private void handleModifyAssignmentDelta(AssignmentEditorDto assDto, - PrismContainerDefinition assignmentDef, PrismContainerValue newValue, ObjectDelta focusDelta) - throws SchemaException { - LOGGER.debug("Handling modified assignment '{}', computing delta.", - new Object[] { assDto.getName() }); - - PrismValue oldValue = assDto.getOldValue(); - Collection deltas = oldValue.diff(newValue); - - for (ItemDelta delta : deltas) { - ItemPath deltaPath = delta.getPath().rest(); - ItemDefinition deltaDef = assignmentDef.findItemDefinition(deltaPath); - - delta.setParentPath(WebComponentUtil.joinPath(oldValue.getPath(), delta.getPath().allExceptLast())); - delta.applyDefinition(deltaDef); - - focusDelta.addModification(delta); - } - } - - @Override - protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, - OperationResult parentResult) { - if (isForce()) { - OperationResult result = parentResult.createSubresult("Force delete operation"); - - try { - ObjectDelta forceDeleteDelta = getForceDeleteDelta(userWrapper); - forceDeleteDelta.revive(getPrismContext()); - - if (forceDeleteDelta != null && !forceDeleteDelta.isEmpty()) { - getModelService().executeChanges(WebComponentUtil.createDeltaCollection(forceDeleteDelta), - options, task, result); - } - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminFocus.message.executeForceDelete.fatalError")); - LoggingUtils.logUnexpectedException(LOGGER, "Failed to execute delete operation with force", ex); - return false; - } - - result.recomputeStatus(); - result.recordSuccessIfUnknown(); - return true; - } - return false; - } - - private ObjectDelta getForceDeleteDelta(PrismObjectWrapper focusWrapper) throws SchemaException { - - List accounts = getFocusShadows(); - List refDeltas = new ArrayList<>(); - ObjectDelta forceDeleteDelta = null; - for (ShadowWrapper account : accounts) { -// if (!accDto.isLoadedOK()) { -// continue; -// } - if (account.getProjectionStatus() == UserDtoStatus.DELETE) { -// ObjectWrapperOld accWrapper = accDto.getObjectOld(); - ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, - focusWrapper.getObject().getDefinition(), account.getObject()); - refDeltas.add(refDelta); - } else if (account.getProjectionStatus() == UserDtoStatus.UNLINK) { -// ObjectWrapperOld accWrapper = accDto.getObjectOld(); - ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, - focusWrapper.getObject().getDefinition(), account.getObject().getOid()); - refDeltas.add(refDelta); - } - } - if (!refDeltas.isEmpty()) { - forceDeleteDelta = getPrismContext().deltaFactory().object() - .createModifyDelta(focusWrapper.getObject().getOid(), refDeltas, - getCompileTimeClass()); - } - PrismContainerDefinition def = focusWrapper.getObject().findContainer(UserType.F_ASSIGNMENT) - .getDefinition(); - if (forceDeleteDelta == null) { - forceDeleteDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), - focusWrapper.getObject().getOid()); - } - return forceDeleteDelta; - } - -// private

List

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

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

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

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

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

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

List

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

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

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

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

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

proj = delta.getObjectToAdd(); +// WebComponentUtil.encryptCredentials(proj, true, getMidpointApplication()); +// +// projectionsToAdd.add(proj.asObjectable()); +// } +// return projectionsToAdd; +// } + + private List prepareShadowObject(List projections) throws SchemaException{ + List projectionsToAdd = new ArrayList<>(); + for (ShadowWrapper projection : projections) { + if (UserDtoStatus.MODIFY.equals(projection.getProjectionStatus())) { + // this is legal e.g. when child org is being create (one assignment comes pre-created) + // TODO do we need more specific checks here? + continue; + } + + if (!UserDtoStatus.ADD.equals(projection.getProjectionStatus())) { + warn(getString("pageAdminFocus.message.illegalAccountState", projection.getStatus())); + continue; + } + + ObjectDelta delta = projection.getObjectDelta(); + PrismObject proj = delta.getObjectToAdd(); + WebComponentUtil.encryptCredentials(proj, true, getMidpointApplication()); + + projectionsToAdd.add(proj.asObjectable()); + } + return projectionsToAdd; + } + + + @Override + protected List> getAdditionalModifyDeltas(OperationResult result) { + return getShadowModifyDeltas(result); + } + + private List> getShadowModifyDeltas(OperationResult result) { + List> deltas = new ArrayList<>(); + + List accounts = getFocusShadows(); + for (ShadowWrapper account : accounts) { + try { + ObjectDelta delta = account.getObjectDelta(); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Account delta computed from {} as:\n{}", + new Object[] { account, delta.debugDump(3) }); + } + + if (!UserDtoStatus.MODIFY.equals(account.getProjectionStatus())) { + continue; + } + + if (delta == null || delta.isEmpty()) { + continue; + } + + WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Modifying account:\n{}", new Object[] { delta.debugDump(3) }); + } + + deltas.add(delta); + + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminFocus.message.getShadowModifyDeltas.fatalError"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't compute account delta", ex); + } + } + + return deltas; + } + + private ReferenceDelta prepareUserAccountsDeltaForModify(PrismReferenceDefinition refDef) + throws SchemaException { + ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().create(refDef); + + List accounts = getFocusShadows(); + for (ShadowWrapper accountWrapper : accounts) { + accountWrapper.revive(getPrismContext()); + ObjectDelta delta = accountWrapper.getObjectDelta(); + PrismReferenceValue refValue = getPrismContext().itemFactory().createReferenceValue(null, OriginType.USER_ACTION, null); + + PrismObject account; + switch (accountWrapper.getProjectionStatus()) { + case ADD: + account = delta.getObjectToAdd(); + addDefaultKindAndIntent(account); + WebComponentUtil.encryptCredentials(account, true, getMidpointApplication()); + refValue.setObject(account); + refDelta.addValueToAdd(refValue); + break; + case DELETE: + account = accountWrapper.getObject(); + refValue.setObject(account); + refDelta.addValueToDelete(refValue); + break; + case MODIFY: + // nothing to do, account modifications were applied + // before + continue; + case UNLINK: + refValue.setOid(delta.getOid()); + refValue.setTargetType(ShadowType.COMPLEX_TYPE); + refDelta.addValueToDelete(refValue); + break; + default: + warn(getString("pageAdminFocus.message.illegalAccountState", accountWrapper.getProjectionStatus())); + } +// } + } + + return refDelta; + } + + private void addDefaultKindAndIntent(PrismObject account) { + if (account.asObjectable().getKind() == null) { + account.asObjectable().setKind(ShadowKindType.ACCOUNT); + } + if (account.asObjectable().getIntent() == null) { + account.asObjectable().setIntent(SchemaConstants.INTENT_DEFAULT); + } + } + + public List showAllAssignmentsPerformed(AjaxRequestTarget ajaxRequestTarget) { + LOGGER.debug("Recompute user assignments"); + Task task = createSimpleTask(OPERATION_RECOMPUTE_ASSIGNMENTS); + OperationResult result = new OperationResult(OPERATION_RECOMPUTE_ASSIGNMENTS); + ObjectDelta delta; + Set assignmentInfoDtoSet = new TreeSet<>(); + + try { + reviveModels(); + + PrismObjectWrapper focusWrapper = getObjectWrapper(); + delta = focusWrapper.getObjectDelta(); +// if (focusWrapper.getOldDelta() != null) { +// delta = ObjectDeltaCollectionsUtil.summarize(focusWrapper.getOldDelta(), delta); +// } + + switch (focusWrapper.getStatus()) { + case ADDED: + PrismObject focus = delta.getObjectToAdd(); + prepareObjectForAdd(focus); + getPrismContext().adopt(focus, getCompileTimeClass()); + + LOGGER.trace("Delta before add focus:\n{}", delta.debugDumpLazily(3)); + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + } else { + result.recordSuccess(); + } + break; + case NOT_CHANGED: + prepareObjectDeltaForModify(delta); + LOGGER.trace("Delta before modify user:\n{}", delta.debugDumpLazily(3)); + + List> accountDeltas = getShadowModifyDeltas(result); + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + } + for (ObjectDelta accDelta : accountDeltas) { + if (!accDelta.isEmpty()) { + accDelta.revive(getPrismContext()); + } + } + break; + default: + error(getString("pageAdminFocus.message.unsupportedState", focusWrapper.getStatus())); + } + + ModelContext modelContext; + try { + ModelExecuteOptions options = ModelExecuteOptions.createEvaluateAllAssignmentRelationsOnRecompute(); + modelContext = getModelInteractionService().previewChanges(Collections.singleton(delta), options, task, result); + } catch (NoFocusNameSchemaException e) { + info(getString("pageAdminFocus.message.noUserName")); + ajaxRequestTarget.add(getFeedbackPanel()); + return null; + } + + DeltaSetTriple> evaluatedAssignmentTriple = modelContext.getEvaluatedAssignmentTriple(); + Collection> evaluatedAssignments = null; + if (evaluatedAssignmentTriple != null) { + evaluatedAssignments = evaluatedAssignmentTriple.getNonNegativeValues(); + } + if (evaluatedAssignments == null || evaluatedAssignments.isEmpty()) { + info(getString("pageAdminFocus.message.noAssignmentsAvailable")); + ajaxRequestTarget.add(getFeedbackPanel()); + return null; + } + + for (EvaluatedAssignment evaluatedAssignment : evaluatedAssignments) { + if (!evaluatedAssignment.isValid()) { + continue; + } + // roles and orgs + DeltaSetTriple targetsTriple = evaluatedAssignment.getRoles(); + Collection targets = targetsTriple.getNonNegativeValues(); + for (EvaluatedAssignmentTarget target : targets) { + if (target.getTarget() != null && ArchetypeType.class.equals(target.getTarget().getCompileTimeClass())){ + continue; + } + if (target.appliesToFocusWithAnyRelation(getRelationRegistry())) { + assignmentInfoDtoSet.add(createAssignmentsPreviewDto(target, task, result)); + } + } + + // all resources + DeltaSetTriple evaluatedConstructionsTriple = evaluatedAssignment + .getEvaluatedConstructions(task, result); + Collection evaluatedConstructions = evaluatedConstructionsTriple + .getNonNegativeValues(); + for (EvaluatedConstruction construction : evaluatedConstructions) { + if (!construction.isWeak()) { + assignmentInfoDtoSet.add(createAssignmentsPreviewDto(construction)); + } + } + } + + return new ArrayList<>(assignmentInfoDtoSet); + + } catch (Exception e) { + LoggingUtils.logUnexpectedException(LOGGER, "Could not create assignments preview.", e); + error("Could not create assignments preview. Reason: " + e); + ajaxRequestTarget.add(getFeedbackPanel()); + } + return null; + } + + private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedAssignmentTarget evaluatedAbstractRole, + Task task, OperationResult result) { + return createAssignmentsPreviewDto(evaluatedAbstractRole.getTarget(), evaluatedAbstractRole.isDirectlyAssigned(), + evaluatedAbstractRole.getAssignmentPath(), evaluatedAbstractRole.getAssignment()); + } + + protected AssignmentInfoDto createDelegableAssignmentsPreviewDto(AssignmentType assignment, Task task, OperationResult result) { + if (assignment.getTargetRef() != null) { + if (RoleType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()) + || OrgType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()) + || ServiceType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType())) { + PrismObject targetObject = WebModelServiceUtils.resolveReferenceNoFetch(assignment.getTargetRef(), + PageAdminFocus.this, task, result); + Boolean isDelegable = false; + if (targetObject != null) { + isDelegable = targetObject.asObjectable().isDelegable(); + } + if (Boolean.TRUE.equals(isDelegable)) { + return createAssignmentsPreviewDto(targetObject, true, null, assignment); + } + } + } + return null; + } + + private AssignmentInfoDto createAssignmentsPreviewDto(PrismObject targetObject, + boolean isDirectlyAssigned, AssignmentPath assignmentPath, AssignmentType assignment) { + AssignmentInfoDto dto = new AssignmentInfoDto(); + dto.setTargetOid(targetObject.getOid()); + dto.setTargetName(getNameToDisplay(targetObject)); + dto.setTargetDescription(targetObject.asObjectable().getDescription()); + dto.setTargetClass(targetObject.getCompileTimeClass()); + dto.setTargetType(WebComponentUtil.classToQName(getPrismContext(), targetObject.getCompileTimeClass())); + dto.setDirect(isDirectlyAssigned); + dto.setAssignmentParent(assignmentPath); + if (assignment != null) { + if (assignment.getTenantRef() != null) { + dto.setTenantName(WebModelServiceUtils.resolveReferenceName(assignment.getTenantRef(), PageAdminFocus.this)); + dto.setTenantRef(assignment.getTenantRef()); + } + if (assignment.getOrgRef() != null) { + dto.setOrgRefName(WebModelServiceUtils.resolveReferenceName(assignment.getOrgRef(), PageAdminFocus.this)); + dto.setOrgRef(assignment.getOrgRef()); + } + if (assignment.getTargetRef() != null){ + dto.setRelation(assignment.getTargetRef().getRelation()); + } + } + return dto; + } + + private String getNameToDisplay(PrismObject target) { + if (target.canRepresent(AbstractRoleType.class)) { + String n = PolyString.getOrig(((AbstractRoleType)target.asObjectable()).getDisplayName()); + if (StringUtils.isNotBlank(n)) { + return n; + } + } + return PolyString.getOrig(target.asObjectable().getName()); + } + + private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedConstruction evaluatedConstruction) { + AssignmentInfoDto dto = new AssignmentInfoDto(); + PrismObject resource = evaluatedConstruction.getResource(); + dto.setTargetOid(resource.getOid()); + dto.setTargetName(PolyString.getOrig(resource.asObjectable().getName())); + dto.setTargetDescription(resource.asObjectable().getDescription()); + dto.setTargetClass(resource.getCompileTimeClass()); + dto.setDirect(evaluatedConstruction.isDirectlyAssigned()); + dto.setAssignmentParent(evaluatedConstruction.getAssignmentPath()); + dto.setKind(evaluatedConstruction.getKind()); + dto.setIntent(evaluatedConstruction.getIntent()); + return dto; + } + + @Override + protected void performAdditionalValidation(PrismObject object, + Collection> deltas, Collection errors) throws SchemaException { + + if (object != null && object.asObjectable() != null) { + for (AssignmentType assignment : object.asObjectable().getAssignment()) { + for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { + if (errors == null) { + errors = validator.validateAssignment(assignment); + } else { + errors.addAll(validator.validateAssignment(assignment)); + } + } + } + } + + } + + protected boolean isFocusHistoryPage(){ + return false; + } + + protected boolean isSelfProfile(){ + return false; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java index f82fe7ca9e9..d0f28488763 100755 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java @@ -1,1016 +1,1079 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.page.admin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.gui.api.component.*; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.util.WebPrismUtil; -import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; -import com.evolveum.midpoint.prism.PrismContainerValue; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.web.component.AjaxButton; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.web.component.util.SelectableBean; -import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.PageSystemConfiguration; -import com.evolveum.midpoint.web.page.admin.server.OperationalButtonsPanel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Page; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.behavior.Behavior; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.util.string.StringValue; -import org.apache.wicket.util.time.Duration; -import org.jetbrains.annotations.NotNull; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; -import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.ObjectSummaryPanel; -import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; -import com.evolveum.midpoint.web.component.progress.ProgressPanel; -import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.page.admin.users.dto.FocusSubwrapperDto; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; -import com.evolveum.midpoint.web.util.validation.SimpleValidationError; - -/** - * @author semancik - */ -public abstract class PageAdminObjectDetails extends PageAdmin - implements ProgressReportingAwarePage { - private static final long serialVersionUID = 1L; - - private static final String DOT_CLASS = PageAdminObjectDetails.class.getName() + "."; - - public static final String PARAM_RETURN_PAGE = "returnPage"; - - private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; - private static final String OPERATION_LOAD_PARENT_ORGS = DOT_CLASS + "loadParentOrgs"; - private static final String OPERATION_LOAD_GUI_CONFIGURATION = DOT_CLASS + "loadGuiConfiguration"; - protected static final String OPERATION_SAVE = DOT_CLASS + "save"; - protected static final String OPERATION_PREVIEW_CHANGES = DOT_CLASS + "previewChanges"; - protected static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit"; - protected static final String OPERATION_LOAD_ARCHETYPE_REF = DOT_CLASS + "loadArchetypeRef"; - protected static final String OPERATION_EXECUTE_CHANGES = DOT_CLASS + "executeChangesTask"; - protected static final String OPERATION_EXECUTE_ARCHETYPE_CHANGES = DOT_CLASS + "executeArchetypeChanges"; - protected static final String OPERATION_LOAD_FILTERED_ARCHETYPES = DOT_CLASS + "loadFilteredArchetypes"; - - protected static final String ID_SUMMARY_PANEL = "summaryPanel"; - protected static final String ID_MAIN_PANEL = "mainPanel"; - private static final String ID_PROGRESS_PANEL = "progressPanel"; - private static final String ID_BUTTONS = "buttons"; - - private static final Trace LOGGER = TraceManager.getTrace(PageAdminObjectDetails.class); - - private LoadableModel> objectModel; - private LoadableModel>> parentOrgModel; - - private ProgressPanel progressPanel; - - // used to determine whether to leave this page or stay on it (after - // operation finishing) - private ObjectDelta delta; - - private AbstractObjectMainPanel mainPanel; - private boolean saveOnConfigure; // ugly hack - whether to invoke 'Save' when returning to this page - - private boolean editingFocus = false; //before we got isOidParameterExists status depending only on oid parameter existence - //we should set editingFocus=true not only when oid parameter exists but also - //when object is given as a constructor parameter - - public boolean isEditingFocus() { - return editingFocus; - } - - @Override - protected void createBreadcrumb() { - createInstanceBreadcrumb(); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - if (saveOnConfigure) { - saveOnConfigure = false; - add(new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) { - @Override - protected void onTimer(AjaxRequestTarget target) { - stop(target); - savePerformed(target); - } - }); - } - } - - @Override - protected IModel createPageTitleModel() { - if (PageAdminObjectDetails.this instanceof PageSystemConfiguration){ - return super.createPageTitleModel(); - } - String simpleName = getObjectSimpleName(); - String lokalizedSimpleName = new StringResourceModel("ObjectType." + simpleName).setDefaultValue(simpleName).getString(); - if (isAdd()) { - return createStringResource("PageAdminObjectDetails.title.new", lokalizedSimpleName); - } - - String name = null; - if (getObjectWrapper() != null && getObjectWrapper().getObject() != null) { - name = WebComponentUtil.getName(getObjectWrapper().getObject()); - } - - return createStringResource("PageAdminObjectDetails.title.edit.readonly.${readOnly}", getObjectModel(), lokalizedSimpleName, name); - } - - private String getObjectSimpleName(){ - if (getObjectWrapper() != null && getObjectWrapper().getObject() != null - && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType){ - AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); - DisplayType displayType = WebComponentUtil - .getArchetypePolicyDisplayType(assignmentHolderObj, PageAdminObjectDetails.this); - if (displayType == null){ - ObjectReferenceType archetypeReference = getObjectArchetypeRef(); - if (archetypeReference != null){ - OperationResult result = new OperationResult(OPERATION_LOAD_ARCHETYPE_REF); - Task task = createSimpleTask(OPERATION_LOAD_ARCHETYPE_REF); - PrismObject archetypeObj = WebModelServiceUtils.resolveReferenceNoFetch(archetypeReference, - this, task, result); - displayType = archetypeObj != null && archetypeObj.asObjectable().getArchetypePolicy() != null ? - archetypeObj.asObjectable().getArchetypePolicy().getDisplay() : null; - } - } - if (displayType != null && displayType.getLabel() != null) { - String archetypeLocalizedName = getLocalizationService() - .translate(displayType.getLabel().toPolyString(), WebComponentUtil.getCurrentLocale(), true); - if (StringUtils.isNotEmpty(archetypeLocalizedName)) { - return archetypeLocalizedName; - } - } - } - return getCompileTimeClass().getSimpleName(); - } - - public boolean isAdd() { - return !isOidParameterExists() && !editingFocus; - } - - public LoadableModel> getObjectModel() { - return objectModel; - } - - protected AbstractObjectMainPanel getMainPanel() { - return mainPanel; - } - - public PrismObjectWrapper getObjectWrapper() { - return objectModel.getObject(); - } - - public List> getParentOrgs() { - return parentOrgModel.getObject(); - } - - public ObjectDelta getDelta() { - return delta; - } - - public void setDelta(ObjectDelta delta) { - this.delta = delta; - } - - public ProgressPanel getProgressPanel() { - return progressPanel; - } - - protected void reviveModels() throws SchemaException { - WebComponentUtil.revive(objectModel, getPrismContext()); - WebComponentUtil.revive(parentOrgModel, getPrismContext()); - } - - public abstract Class getCompileTimeClass(); - - - public void initialize(final PrismObject objectToEdit) { - boolean isNewObject = objectToEdit == null && StringUtils.isEmpty(getObjectOidParameter()); - - initialize(objectToEdit, isNewObject, false); - } - - public void initialize(final PrismObject objectToEdit, boolean isNewObject) { - initialize(objectToEdit, isNewObject, false); - } - - public void initialize(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - initializeModel(objectToEdit, isNewObject, isReadonly); -// initLayout(); - } - - protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - editingFocus = !isNewObject; - - objectModel = new LoadableModel>(false) { - private static final long serialVersionUID = 1L; - - @Override - protected PrismObjectWrapper load() { - PrismObjectWrapper wrapper = loadObjectWrapper(objectToEdit, isReadonly); -// wrapper.sort(); - return wrapper; - } - }; - - parentOrgModel = new LoadableModel>>(false) { - private static final long serialVersionUID = 1L; - - @Override - protected List> load() { - return loadOrgWrappers(); - } - }; - } - - private ObjectReferenceType getObjectArchetypeRef() { - ObjectReferenceType archetypeReference = null; - if (getObjectWrapper() != null && getObjectWrapper().getObject() != null - && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType) { - AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); - if (assignmentHolderObj.getAssignment() != null) { - for (AssignmentType assignment : assignmentHolderObj.getAssignment()) { - if (assignment.getTargetRef() != null && assignment.getTargetRef().getType() != null - && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { - archetypeReference = assignment.getTargetRef(); - break; - } - } - } - } - return archetypeReference; - } - - protected List> loadOrgWrappers() { - // WRONG!! TODO: fix - return null; - } - - protected abstract O createNewObject(); - - @Override - protected void onInitialize() { - super.onInitialize(); - initLayout(); - } - - protected void initLayout() { - initLayoutSummaryPanel(); - initOperationalButtonsPanel(); - - mainPanel = createMainPanel(ID_MAIN_PANEL); - mainPanel.setOutputMarkupId(true); - add(mainPanel); - - progressPanel = new ProgressPanel(ID_PROGRESS_PANEL); - add(progressPanel); - } - - protected abstract ObjectSummaryPanel createSummaryPanel(); - - protected void initLayoutSummaryPanel() { - - ObjectSummaryPanel summaryPanel = createSummaryPanel(); - summaryPanel.setOutputMarkupId(true); - - setSummaryPanelVisibility(summaryPanel); - add(summaryPanel); - } - - protected void setSummaryPanelVisibility(ObjectSummaryPanel summaryPanel){ - summaryPanel.add(new VisibleEnableBehaviour() { - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - return isOidParameterExists() || editingFocus; - } - }); - } - - private void initOperationalButtonsPanel(){ - OperationalButtonsPanel opButtonPanel = new OperationalButtonsPanel(ID_BUTTONS) { - private static final long serialVersionUID = 1L; - - @Override - protected void addButtons(RepeatingView repeatingView) { - initOperationalButtons(repeatingView); - } - }; - if (getAdditionalOperationalButtonPanelBehaviors() != null && !getAdditionalOperationalButtonPanelBehaviors().isEmpty()){ - getAdditionalOperationalButtonPanelBehaviors().forEach(this::add); - } - opButtonPanel.setOutputMarkupId(true); - opButtonPanel.add(new VisibleBehaviour(() -> isEditingFocus() && opButtonPanel.buttonsExist())); - add(opButtonPanel); - } - - protected List getAdditionalOperationalButtonPanelBehaviors(){ - return new ArrayList<>(); - } - - protected void initOperationalButtons(RepeatingView repeatingView){ - if (getObjectArchetypeRef() != null) { - AjaxButton changeArchetype = new AjaxButton(repeatingView.newChildId(), createStringResource("PageAdminObjectDetails.button.changeArchetype")) { - @Override - public void onClick(AjaxRequestTarget target) { - changeArchetypeButtonClicked(target); - } - }; - changeArchetype.add(new VisibleBehaviour(() -> getObjectArchetypeRef() != null)); - changeArchetype.add(AttributeAppender.append("class", "btn-default")); - repeatingView.add(changeArchetype); - } - } - - protected OperationalButtonsPanel getOperationalButtonsPanel(){ - return (OperationalButtonsPanel) get(ID_BUTTONS); - } - - private void changeArchetypeButtonClicked(AjaxRequestTarget target){ - - AssignmentPopup changeArchetypePopup = new AssignmentPopup(getMainPopupBodyId()) { - - private static final long serialVersionUID = 1L; - - @Override - protected void addPerformed(AjaxRequestTarget target, List newAssignmentsList) { - super.addPerformed(target, newAssignmentsList); - try { - PrismContainerWrapper assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); - ((List) newAssignmentsList).forEach(assignment -> { - PrismContainerValue newAssignment = assignmentsWrapper.getItem().createNewValue(); - assignmentsWrapper.getValues().forEach(assignmentValue -> { - if (assignmentValue.getRealValue().getTargetRef() != null - && assignmentValue.getRealValue().getTargetRef().getType() != null - && QNameUtil.match(assignmentValue.getRealValue().getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)){ - assignmentValue.setStatus(ValueStatus.DELETED); - } - }); - AssignmentType assignmentType = newAssignment.asContainerable(); - assignmentType.setTargetRef(assignment.getTargetRef()); - WebPrismUtil.createNewValueWrapper(assignmentsWrapper, newAssignment, PageAdminObjectDetails.this, target); - OperationResult result = new OperationResult(OPERATION_EXECUTE_ARCHETYPE_CHANGES); - Task task = createSimpleTask(OPERATION_EXECUTE_ARCHETYPE_CHANGES); - try { - ObjectDelta archetypeDelta = getObjectWrapper().getObjectDelta(); - if (!archetypeDelta.isEmpty()) { - archetypeDelta.revive(getPrismContext()); - getModelService().executeChanges(WebComponentUtil.createDeltaCollection(archetypeDelta), null, task, result); - result.computeStatus(); - } - } catch (Exception e) { - LOGGER.error("Cannot save archetype assignment changes: {}", e.getMessage()); - } - showResult(result); - }); - } catch (SchemaException e) { - LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); - } - target.add(PageAdminObjectDetails.this.getFeedbackPanel()); - } - - @Override - protected List createAssignmentTabs() { - List tabs = new ArrayList<>(); - - tabs.add(new PanelTab(getPageBase().createStringResource("ObjectTypes.ARCHETYPE"), - new VisibleBehaviour(() -> true)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusTypeAssignmentPopupTabPanel(panelId, ObjectTypes.ARCHETYPE) { - private static final long serialVersionUID = 1L; - - @Override - protected PrismContainerWrapper getAssignmentWrapperModel() { - PrismContainerWrapper assignmentsWrapper = null; - try { - assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); - } catch (SchemaException e) { - LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); - } - return assignmentsWrapper; - } - - @Override - protected List getSupportedRelations() { - return Collections.singletonList(SchemaConstants.ORG_DEFAULT); - } - - @Override - protected void onSelectionPerformed(AjaxRequestTarget target, IModel> rowModel) { - target.add(getObjectListPanel()); - tabLabelPanelUpdate(target); - } - - @Override - protected IModel getObjectSelectCheckBoxEnableModel(IModel> rowModel){ - if (rowModel == null){ - return Model.of(false); - } - List selectedObjects = getSelectedObjectsList(); - return Model.of(selectedObjects == null || selectedObjects.size() == 0 - || (rowModel.getObject() != null && rowModel.getObject().isSelected())); - } - - - @Override - protected ObjectTypes getObjectType() { - return ObjectTypes.ARCHETYPE; - } - - @Override - protected ObjectQuery addFilterToContentQuery(ObjectQuery query){ - super.addFilterToContentQuery(query); - if (query == null) { - query = getPrismContext().queryFactory().createQuery(); - } - List archetypeOidsList = getFilteredArchetypeOidsList(); - ObjectFilter filter = getPrismContext().queryFor(ArchetypeType.class) - .id(archetypeOidsList.toArray(new String[0])) - .buildFilter(); - query.addFilter(filter); - return query; - } - }; - } - }); - return tabs; - } - }; - - changeArchetypePopup.setOutputMarkupPlaceholderTag(true); - showMainPopup(changeArchetypePopup, target); - - } - - private List getFilteredArchetypeOidsList(){ - OperationResult result = new OperationResult(OPERATION_LOAD_FILTERED_ARCHETYPES); - PrismObject obj = getObjectWrapper().getObject(); - List oidsList = new ArrayList<>(); - try { - List filteredArchetypes = getModelInteractionService().getFilteredArchetypesByHolderType(obj, result); - if (filteredArchetypes != null){ - filteredArchetypes.forEach(archetype -> oidsList.add(archetype.getOid())); - } - } catch (SchemaException ex){ - result.recordPartialError(ex.getLocalizedMessage()); - LOGGER.error("Couldn't load assignment target specification for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); - } - return oidsList; - } - - protected abstract AbstractObjectMainPanel createMainPanel(String id); - - protected String getObjectOidParameter() { - PageParameters parameters = getPageParameters(); - LOGGER.trace("Page parameters: {}", parameters); - StringValue oidValue = parameters.get(OnePageParameterEncoder.PARAMETER); - LOGGER.trace("OID parameter: {}", oidValue); - if (oidValue == null) { - return null; - } - String oid = oidValue.toString(); - if (StringUtils.isBlank(oid)) { - return null; - } - return oid; - } - - protected ObjectSummaryPanel getSummaryPanel() { - return (ObjectSummaryPanel) get(ID_SUMMARY_PANEL); - } - - public boolean isOidParameterExists() { - return getObjectOidParameter() != null; - } - - protected PrismObjectWrapper loadObjectWrapper(PrismObject objectToEdit, boolean isReadonly) { - Task task = createSimpleTask(OPERATION_LOAD_OBJECT); - OperationResult result = task.getResult(); - PrismObject object = null; - try { - if (!isOidParameterExists()) { - if (objectToEdit == null) { - LOGGER.trace("Loading object: New object (creating)"); - O focusType = createNewObject(); - - // Apply subtype using page parameters - List subtypes = getPageParameters().getValues(ObjectType.F_SUBTYPE.getLocalPart()); - subtypes.stream().filter(p -> !p.isEmpty()).forEach(c -> focusType.subtype(c.toString())); - - getMidpointApplication().getPrismContext().adopt(focusType); - object = (PrismObject) focusType.asPrismObject(); - } else { - LOGGER.trace("Loading object: New object (supplied): {}", objectToEdit); - object = objectToEdit; - } - } else { - - String focusOid = getObjectOidParameter(); - object = WebModelServiceUtils.loadObject(getCompileTimeClass(), focusOid, buildGetOptions(), this, task, result); - LOGGER.trace("Loading object: Existing object (loadled): {} -> {}", focusOid, object); - } - - result.recordSuccess(); - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - } - - showResult(result, false); - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Loaded object:\n{}", object.debugDump()); - } - - if (object == null) { - if (isOidParameterExists()) { - getSession().error(getString("pageAdminFocus.message.cantEditFocus")); - } else { - getSession().error(getString("pageAdminFocus.message.cantNewFocus")); - } - throw new RestartResponseException(getRestartResponsePage()); - } - - ItemStatus itemStatus = isOidParameterExists() || editingFocus ? ItemStatus.NOT_CHANGED : ItemStatus.ADDED; - PrismObjectWrapper wrapper; - - PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(object.getDefinition()); - WrapperContext context = new WrapperContext(task, result); - context.setCreateIfEmpty(ItemStatus.ADDED == itemStatus); - //we don't want to set to false.. refactor this method to take either enum (READONLY, AUTO, ...) or - // Boolean instead of boolean isReadonly - if (isReadonly) { - context.setReadOnly(isReadonly); - } - - - try { - wrapper = factory.createObjectWrapper(object.clone(), itemStatus, context); - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - showResult(result, false); - throw new RestartResponseException(getRestartResponsePage()); - } - - showResult(result, false); - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump()); - } - - return wrapper; - } - - protected Collection> buildGetOptions() { - return getOperationOptionsBuilder() - .item(UserType.F_JPEG_PHOTO).retrieve() - .build(); - } - -// private void loadParentOrgs(PrismObjectWrapper wrapper, Task task, OperationResult result) { -// OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS); -// PrismObject focus = wrapper.getObject(); -// // Load parent organizations (full objects). There are used in the -// // summary panel and also in the main form. -// // Do it here explicitly instead of using resolve option to have ability -// // to better handle (ignore) errors. -// for (ObjectReferenceType parentOrgRef : focus.asObjectable().getParentOrgRef()) { -// -// PrismObject parentOrg = null; -// try { -// -// parentOrg = getModelService().getObject(OrgType.class, parentOrgRef.getOid(), null, task, -// subResult); -// LOGGER.trace("Loaded parent org with result {}", -// new Object[] { subResult.getLastSubresult() }); -// } catch (AuthorizationException e) { -// // This can happen if the user has permission to read parentOrgRef but it does not have -// // the permission to read target org -// // It is OK to just ignore it. -// subResult.muteLastSubresultError(); -// LOGGER.debug("User {} does not have permission to read parent org unit {} (ignoring error)", task.getOwner().getName(), parentOrgRef.getOid()); -// } catch (Exception ex) { -// subResult.recordWarning(createStringResource("PageAdminObjectDetails.message.loadParentOrgs.warning", parentOrgRef.getOid()).getString(), ex); -// LOGGER.warn("Cannot load parent org {}: {}", parentOrgRef.getOid(), ex.getMessage(), ex); -// } -// -// if (parentOrg != null) { -// wrapper.getParentOrgs().add(parentOrg); -// } -// } -// subResult.computeStatus(); -// } - - protected abstract Class getRestartResponsePage(); - - public Object findParam(String param, String oid, OperationResult result) { - - Object object = null; - - for (OperationResult subResult : result.getSubresults()) { - if (subResult != null && subResult.getParams() != null) { - if (subResult.getParams().get(param) != null - && subResult.getParams().get(OperationResult.PARAM_OID) != null - && subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) { - return subResult.getParams().get(param); - } - object = findParam(param, oid, subResult); - - } - } - return object; - } - - // TODO put this into correct place - protected boolean previewRequested; - - /** - * This will be called from the main form when save button is pressed. - */ - public void savePerformed(AjaxRequestTarget target) { - progressPanel.onBeforeSave(); - OperationResult result = new OperationResult(OPERATION_SAVE); - previewRequested = false; - saveOrPreviewPerformed(target, result, false); - } - - public void previewPerformed(AjaxRequestTarget target) { - progressPanel.onBeforeSave(); - OperationResult result = new OperationResult(OPERATION_PREVIEW_CHANGES); - previewRequested = true; - saveOrPreviewPerformed(target, result, true); - } - - public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly) { - saveOrPreviewPerformed(target, result, previewOnly, null); - } - - public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly, Task task) { - boolean delegationChangesExist = processDeputyAssignments(previewOnly); - - PrismObjectWrapper objectWrapper = getObjectWrapper(); - LOGGER.debug("Saving object {}", objectWrapper); - - // todo: improve, delta variable is quickfix for MID-1006 - // redirecting to user list page everytime user is created in repository - // during user add in gui, - // and we're not taking care about account/assignment create errors - // (error message is still displayed) - delta = null; - - if(task == null) { - task = createSimpleTask(OPERATION_SEND_TO_SUBMIT); - } - - ModelExecuteOptions options = getOptions(previewOnly); - - LOGGER.debug("Using execute options {}.", options); - - try { - reviveModels(); - - delta = objectWrapper.getObjectDelta(); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) }); - } - } catch (Exception ex) { - result.recordFatalError(getString("pageAdminObjectDetails.message.cantCreateObject"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Create Object failed", ex); - showResult(result); - target.add(getFeedbackPanel()); - return; - } - - switch (objectWrapper.getStatus()) { - case ADDED: - try { - PrismObject objectToAdd = delta.getObjectToAdd(); - WebComponentUtil.encryptCredentials(objectToAdd, true, getMidpointApplication()); - prepareObjectForAdd(objectToAdd); - getPrismContext().adopt(objectToAdd, getCompileTimeClass()); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) }); - } - - if (!delta.isEmpty()) { - delta.revive(getPrismContext()); - - final Collection> deltas = WebComponentUtil.createDeltaCollection(delta); - final Collection validationErrors = performCustomValidation(objectToAdd, deltas); - if (checkValidationErrors(target, validationErrors)) { - return; - } - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else { - result.recordSuccess(); - } - } catch (Exception ex) { - result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex); - showResult(result); - } - break; - - case NOT_CHANGED: - try { - WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); - prepareObjectDeltaForModify(delta); //preparing of deltas for projections (ADD, DELETE, UNLINK) - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) }); - } - - Collection> deltas = new ArrayList<>(); - if (!delta.isEmpty()) { - delta.revive(getPrismContext()); - deltas.add(delta); - } - - List> additionalDeltas = getAdditionalModifyDeltas(result); - if (additionalDeltas != null) { - for (ObjectDelta additionalDelta : additionalDeltas) { - if (!additionalDelta.isEmpty()) { - additionalDelta.revive(getPrismContext()); - deltas.add(additionalDelta); - } - } - } - - if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) { - ObjectDelta emptyDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), - objectWrapper.getObject().getOid()); - deltas.add(emptyDelta); - - Collection validationErrors = performCustomValidation(null, deltas); - if (checkValidationErrors(target, validationErrors)) { - return; - } - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else if (!deltas.isEmpty()) { - Collection validationErrors = performCustomValidation(null, deltas); - if (checkValidationErrors(target, validationErrors)) { - return; - } - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else if (previewOnly && delta.isEmpty() && delegationChangesExist){ - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else { - progressPanel.clearProgressPanel(); // from previous attempts (useful only if we would call finishProcessing at the end, but that's not the case now) - if (!previewOnly) { - if (!delegationChangesExist) { - result.recordWarning(getString("PageAdminObjectDetails.noChangesSave")); - showResult(result); - } - redirectBack(); - } else { - if (!delegationChangesExist) { - warn(getString("PageAdminObjectDetails.noChangesPreview")); - target.add(getFeedbackPanel()); - } - } - } - - } catch (Exception ex) { - if (!executeForceDelete(objectWrapper, task, options, result)) { - result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex); - LoggingUtils.logUnexpectedException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex); - } else { - result.recomputeStatus(); - } - showResult(result); - } - break; - // support for add/delete containers (e.g. delete credentials) - default: - error(getString("pageAdminFocus.message.unsupportedState", objectWrapper.getStatus())); - } - -// result.recomputeStatus(); -// -// if (!result.isInProgress()) { -// LOGGER.trace("Result NOT in progress, calling finishProcessing"); -// finishProcessing(target, result, false); -// } - - LOGGER.trace("returning from saveOrPreviewPerformed"); - } - - protected boolean processDeputyAssignments(boolean previewOnly){ - return false; - } - - protected boolean checkValidationErrors(AjaxRequestTarget target, Collection validationErrors) { - if (validationErrors != null && !validationErrors.isEmpty()) { - for (SimpleValidationError error : validationErrors) { - LOGGER.error("Validation error, attribute: '" + error.printAttribute() - + "', message: '" + error.getMessage() + "'."); - error("Validation error, attribute: '" + error.printAttribute() - + "', message: '" + error.getMessage() + "'."); - } - - target.add(getFeedbackPanel()); - return true; - } - return false; - } - - @Override - public void startProcessing(AjaxRequestTarget target, OperationResult result) { - LOGGER.trace("startProcessing called, making main panel invisible"); - mainPanel.setVisible(false); - target.add(mainPanel); - } - - @NotNull - protected ModelExecuteOptions getOptions(boolean previewOnly) { - ModelExecuteOptions options = mainPanel.getExecuteChangeOptionsDto().createOptions(); - if (previewOnly) { - options.getOrCreatePartialProcessing().setApprovals(PartialProcessingTypeType.PROCESS); - } - return options; - } - - protected void prepareObjectForAdd(PrismObject object) throws SchemaException { - - } - - protected void prepareObjectDeltaForModify(ObjectDelta objectDelta) throws SchemaException { - - } - - protected List> getAdditionalModifyDeltas(OperationResult result) { - return null; - } - - protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, - OperationResult parentResult) { - return isForce(); - } - - protected boolean isForce() { - return getMainPanel().getExecuteChangeOptionsDto().isForce(); - } - - protected boolean isKeepDisplayingResults() { - return getMainPanel().getExecuteChangeOptionsDto().isKeepDisplayingResults(); - } - - protected boolean isSaveInBackground(){ - return getMainPanel().getExecuteChangeOptionsDto().isSaveInBackground(); - } - - protected Collection performCustomValidation(PrismObject object, - Collection> deltas) throws SchemaException { - Collection errors = null; - - if (object == null) { - if (getObjectWrapper() != null && getObjectWrapper().getObjectOld() != null) { - object = getObjectWrapper().getObjectOld().clone(); // otherwise original object could get corrupted e.g. by applying the delta below - - for (ObjectDelta delta : deltas) { - // because among deltas there can be also ShadowType deltas - if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) { - delta.applyTo(object); - } - } - } - } else { - object = object.clone(); - } - - performAdditionalValidation(object, deltas, errors); - - for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { - if (errors == null) { - errors = validator.validateObject(object, deltas); - } else { - errors.addAll(validator.validateObject(object, deltas)); - } - } - - return errors; - } - - protected void performAdditionalValidation(PrismObject object, - Collection> deltas, Collection errors) throws SchemaException { - - } - - public List getObjectFormTypes() { - Task task = createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION); - OperationResult result = task.getResult(); - CompiledGuiProfile adminGuiConfiguration; - try { - adminGuiConfiguration = getModelInteractionService().getCompiledGuiProfile(task, result); - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { - throw new SystemException("Cannot load GUI configuration: "+e.getMessage(), e); - } - ObjectFormsType objectFormsType = adminGuiConfiguration.getObjectForms(); - if (objectFormsType == null) { - return null; - } - List objectForms = objectFormsType.getObjectForm(); - if (objectForms == null || objectForms.isEmpty()) { - return objectForms; - } - List validObjectForms = new ArrayList<>(); - for (ObjectFormType objectForm: objectForms) { - if (isSupportedObjectType(objectForm.getType())) { - validObjectForms.add(objectForm); - } - } - return validObjectForms; - } - - protected boolean isSupportedObjectType(QName type) { - ObjectTypes objectType = ObjectTypes.getObjectType(getCompileTimeClass()); - return QNameUtil.match(objectType.getTypeQName(),type); - } - - public void setSaveOnConfigure(boolean saveOnConfigure) { - this.saveOnConfigure = saveOnConfigure; - } - - public boolean isSaveOnConfigure() { - return saveOnConfigure; - } - - public boolean isForcedPreview() { - GuiObjectDetailsPageType objectDetails = getCompiledGuiProfile().findObjectDetailsConfiguration(getCompileTimeClass()); - return objectDetails != null && DetailsPageSaveMethodType.FORCED_PREVIEW.equals(objectDetails.getSaveMethod()); - } - -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin; + +import java.util.*; + +import javax.xml.namespace.QName; + +import com.evolveum.midpoint.gui.api.component.*; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.util.WebPrismUtil; +import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; +import com.evolveum.midpoint.model.api.context.ModelContext; +import com.evolveum.midpoint.prism.PrismContainerValue; +import com.evolveum.midpoint.prism.query.ObjectFilter; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; +import com.evolveum.midpoint.web.component.refresh.Refreshable; +import com.evolveum.midpoint.web.component.util.SelectableBean; +import com.evolveum.midpoint.web.component.util.VisibleBehaviour; +import com.evolveum.midpoint.web.page.admin.configuration.PageSystemConfiguration; +import com.evolveum.midpoint.web.page.admin.server.OperationalButtonsPanel; +import com.evolveum.midpoint.web.security.util.SecurityUtils; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.Page; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.Session; +import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.behavior.Behavior; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.protocol.http.WebSession; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.util.string.StringValue; +import org.apache.wicket.util.time.Duration; +import org.jetbrains.annotations.NotNull; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; +import com.evolveum.midpoint.gui.impl.factory.WrapperContext; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.ObjectTypes; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.ObjectSummaryPanel; +import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.progress.ProgressPanel; +import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.page.admin.users.dto.FocusSubwrapperDto; +import com.evolveum.midpoint.web.util.OnePageParameterEncoder; +import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; +import com.evolveum.midpoint.web.util.validation.SimpleValidationError; + +/** + * @author semancik + */ +public abstract class PageAdminObjectDetails extends PageAdmin + implements ProgressReportingAwarePage, Refreshable { + private static final long serialVersionUID = 1L; + + private static final String DOT_CLASS = PageAdminObjectDetails.class.getName() + "."; + + private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; + protected static final String OPERATION_SAVE = DOT_CLASS + "save"; + protected static final String OPERATION_PREVIEW_CHANGES = DOT_CLASS + "previewChanges"; + protected static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit"; + protected static final String OPERATION_LOAD_ARCHETYPE_REF = DOT_CLASS + "loadArchetypeRef"; + protected static final String OPERATION_EXECUTE_ARCHETYPE_CHANGES = DOT_CLASS + "executeArchetypeChanges"; + protected static final String OPERATION_LOAD_FILTERED_ARCHETYPES = DOT_CLASS + "loadFilteredArchetypes"; + + protected static final String ID_SUMMARY_PANEL = "summaryPanel"; + protected static final String ID_MAIN_PANEL = "mainPanel"; + private static final String ID_PROGRESS_PANEL = "progressPanel"; + private static final String ID_BUTTONS = "buttons"; + + private static final Trace LOGGER = TraceManager.getTrace(PageAdminObjectDetails.class); + + private LoadableModel> objectModel; + private LoadableModel>> parentOrgModel; + + private ProgressPanel progressPanel; + + // used to determine whether to leave this page or stay on it (after + // operation finishing) + private ObjectDelta delta; + + private AbstractObjectMainPanel mainPanel; + private boolean saveOnConfigure; // ugly hack - whether to invoke 'Save' when returning to this page + + private boolean editingFocus = false; //before we got isOidParameterExists status depending only on oid parameter existence + //we should set editingFocus=true not only when oid parameter exists but also + //when object is given as a constructor parameter + + public boolean isEditingFocus() { + return editingFocus; + } + + @Override + protected void createBreadcrumb() { + createInstanceBreadcrumb(); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + if (saveOnConfigure) { + saveOnConfigure = false; + add(new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) { + @Override + protected void onTimer(AjaxRequestTarget target) { + stop(target); + savePerformed(target); + } + }); + } + } + + @Override + protected IModel createPageTitleModel() { + if (PageAdminObjectDetails.this instanceof PageSystemConfiguration){ + return super.createPageTitleModel(); + } + String simpleName = getObjectSimpleName(); + String lokalizedSimpleName = new StringResourceModel("ObjectType." + simpleName).setDefaultValue(simpleName).getString(); + if (isAdd()) { + return createStringResource("PageAdminObjectDetails.title.new", lokalizedSimpleName); + } + + String name = null; + if (getObjectWrapper() != null && getObjectWrapper().getObject() != null) { + name = WebComponentUtil.getName(getObjectWrapper().getObject()); + } + + return createStringResource("PageAdminObjectDetails.title.edit.readonly.${readOnly}", getObjectModel(), lokalizedSimpleName, name); + } + + private String getObjectSimpleName(){ + if (getObjectWrapper() != null && getObjectWrapper().getObject() != null + && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType){ + AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); + DisplayType displayType = WebComponentUtil + .getArchetypePolicyDisplayType(assignmentHolderObj, PageAdminObjectDetails.this); + if (displayType == null){ + ObjectReferenceType archetypeReference = getObjectArchetypeRef(); + if (archetypeReference != null){ + OperationResult result = new OperationResult(OPERATION_LOAD_ARCHETYPE_REF); + Task task = createSimpleTask(OPERATION_LOAD_ARCHETYPE_REF); + PrismObject archetypeObj = WebModelServiceUtils.resolveReferenceNoFetch(archetypeReference, + this, task, result); + displayType = archetypeObj != null && archetypeObj.asObjectable().getArchetypePolicy() != null ? + archetypeObj.asObjectable().getArchetypePolicy().getDisplay() : null; + } + } + if (displayType != null && displayType.getLabel() != null) { + String archetypeLocalizedName = getLocalizationService() + .translate(displayType.getLabel().toPolyString(), WebComponentUtil.getCurrentLocale(), true); + if (StringUtils.isNotEmpty(archetypeLocalizedName)) { + return archetypeLocalizedName; + } + } + } + return getCompileTimeClass().getSimpleName(); + } + + public boolean isAdd() { + return !isOidParameterExists() && !editingFocus; + } + + public LoadableModel> getObjectModel() { + return objectModel; + } + + protected AbstractObjectMainPanel getMainPanel() { + return mainPanel; + } + + public PrismObjectWrapper getObjectWrapper() { + return objectModel.getObject(); + } + + public List> getParentOrgs() { + return parentOrgModel.getObject(); + } + + public ObjectDelta getDelta() { + return delta; + } + + public void setDelta(ObjectDelta delta) { + this.delta = delta; + } + + public ProgressPanel getProgressPanel() { + return progressPanel; + } + + protected void reviveModels() throws SchemaException { + WebComponentUtil.revive(objectModel, getPrismContext()); + WebComponentUtil.revive(parentOrgModel, getPrismContext()); + } + + public abstract Class getCompileTimeClass(); + + + public void initialize(final PrismObject objectToEdit) { + boolean isNewObject = objectToEdit == null && StringUtils.isEmpty(getObjectOidParameter()); + + initialize(objectToEdit, isNewObject, false); + } + + public void initialize(final PrismObject objectToEdit, boolean isNewObject) { + initialize(objectToEdit, isNewObject, false); + } + + public void initialize(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + initializeModel(objectToEdit, isNewObject, isReadonly); +// initLayout(); + } + + protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + editingFocus = !isNewObject; + + objectModel = new LoadableModel>(false) { + private static final long serialVersionUID = 1L; + + @Override + protected PrismObjectWrapper load() { + PrismObjectWrapper wrapper = loadObjectWrapper(objectToEdit, isReadonly); + return wrapper; + } + }; + + parentOrgModel = new LoadableModel>>(false) { + private static final long serialVersionUID = 1L; + + @Override + protected List> load() { + return loadOrgWrappers(); + } + }; + } + + private ObjectReferenceType getObjectArchetypeRef() { + ObjectReferenceType archetypeReference = null; + if (getObjectWrapper() != null && getObjectWrapper().getObject() != null + && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType) { + AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); + if (assignmentHolderObj.getAssignment() != null) { + for (AssignmentType assignment : assignmentHolderObj.getAssignment()) { + if (assignment.getTargetRef() != null && assignment.getTargetRef().getType() != null + && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { + archetypeReference = assignment.getTargetRef(); + break; + } + } + } + } + return archetypeReference; + } + + protected List> loadOrgWrappers() { + // WRONG!! TODO: fix + return null; + } + + protected abstract O createNewObject(); + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + protected void initLayout() { + initLayoutSummaryPanel(); + initOperationalButtonsPanel(); + + mainPanel = createMainPanel(ID_MAIN_PANEL); + mainPanel.setOutputMarkupId(true); + add(mainPanel); + + progressPanel = new ProgressPanel(ID_PROGRESS_PANEL); + add(progressPanel); + } + + protected abstract ObjectSummaryPanel createSummaryPanel(); + + protected void initLayoutSummaryPanel() { + + ObjectSummaryPanel summaryPanel = createSummaryPanel(); + summaryPanel.setOutputMarkupId(true); + + setSummaryPanelVisibility(summaryPanel); + add(summaryPanel); + } + + protected void setSummaryPanelVisibility(ObjectSummaryPanel summaryPanel){ + summaryPanel.add(new VisibleEnableBehaviour() { + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return isOidParameterExists() || editingFocus; + } + }); + } + + private void initOperationalButtonsPanel(){ + OperationalButtonsPanel opButtonPanel = new OperationalButtonsPanel(ID_BUTTONS) { + private static final long serialVersionUID = 1L; + + @Override + protected void addButtons(RepeatingView repeatingView) { + initOperationalButtons(repeatingView); + } + }; + + opButtonPanel.setOutputMarkupId(true); + opButtonPanel.add(new VisibleBehaviour(() -> isEditingFocus() && opButtonPanel.buttonsExist())); + + AjaxSelfUpdatingTimerBehavior behavior = new AjaxSelfUpdatingTimerBehavior(Duration.milliseconds(getRefreshInterval())) { + private static final long serialVersionUID = 1L; + + @Override + protected void onPostProcessTarget(AjaxRequestTarget target) { + refresh(target); + } + + @Override + protected boolean shouldTrigger() { + return isRefreshEnabled(); + } + }; + + opButtonPanel.add(behavior); + + add(opButtonPanel); + } + + public boolean isRefreshEnabled() { + return false; + } + + public void refresh(AjaxRequestTarget target) { + + } + + public int getRefreshInterval() { + return 30; + } + + protected void initOperationalButtons(RepeatingView repeatingView){ + if (getObjectArchetypeRef() != null) { + AjaxButton changeArchetype = new AjaxButton(repeatingView.newChildId(), createStringResource("PageAdminObjectDetails.button.changeArchetype")) { + @Override + public void onClick(AjaxRequestTarget target) { + changeArchetypeButtonClicked(target); + } + }; + changeArchetype.add(new VisibleBehaviour(() -> getObjectArchetypeRef() != null)); + changeArchetype.add(AttributeAppender.append("class", "btn-default")); + repeatingView.add(changeArchetype); + } + } + + protected OperationalButtonsPanel getOperationalButtonsPanel(){ + return (OperationalButtonsPanel) get(ID_BUTTONS); + } + + private void changeArchetypeButtonClicked(AjaxRequestTarget target){ + + AssignmentPopup changeArchetypePopup = new AssignmentPopup(getMainPopupBodyId()) { + + private static final long serialVersionUID = 1L; + + @Override + protected void addPerformed(AjaxRequestTarget target, List newAssignmentsList) { + super.addPerformed(target, newAssignmentsList); + try { + PrismContainerWrapper assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); + ((List) newAssignmentsList).forEach(assignment -> { + PrismContainerValue newAssignment = assignmentsWrapper.getItem().createNewValue(); + assignmentsWrapper.getValues().forEach(assignmentValue -> { + if (assignmentValue.getRealValue().getTargetRef() != null + && assignmentValue.getRealValue().getTargetRef().getType() != null + && QNameUtil.match(assignmentValue.getRealValue().getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)){ + assignmentValue.setStatus(ValueStatus.DELETED); + } + }); + AssignmentType assignmentType = newAssignment.asContainerable(); + assignmentType.setTargetRef(assignment.getTargetRef()); + WebPrismUtil.createNewValueWrapper(assignmentsWrapper, newAssignment, PageAdminObjectDetails.this, target); + OperationResult result = new OperationResult(OPERATION_EXECUTE_ARCHETYPE_CHANGES); + Task task = createSimpleTask(OPERATION_EXECUTE_ARCHETYPE_CHANGES); + try { + ObjectDelta archetypeDelta = getObjectWrapper().getObjectDelta(); + if (!archetypeDelta.isEmpty()) { + archetypeDelta.revive(getPrismContext()); + getModelService().executeChanges(WebComponentUtil.createDeltaCollection(archetypeDelta), null, task, result); + result.computeStatus(); + } + } catch (Exception e) { + LOGGER.error("Cannot save archetype assignment changes: {}", e.getMessage()); + } + showResult(result); + }); + } catch (SchemaException e) { + LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); + } + target.add(PageAdminObjectDetails.this.getFeedbackPanel()); + } + + @Override + protected List createAssignmentTabs() { + List tabs = new ArrayList<>(); + + tabs.add(new PanelTab(getPageBase().createStringResource("ObjectTypes.ARCHETYPE"), + new VisibleBehaviour(() -> true)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusTypeAssignmentPopupTabPanel(panelId, ObjectTypes.ARCHETYPE) { + private static final long serialVersionUID = 1L; + + @Override + protected PrismContainerWrapper getAssignmentWrapperModel() { + PrismContainerWrapper assignmentsWrapper = null; + try { + assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); + } catch (SchemaException e) { + LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); + } + return assignmentsWrapper; + } + + @Override + protected List getSupportedRelations() { + return Collections.singletonList(SchemaConstants.ORG_DEFAULT); + } + + @Override + protected void onSelectionPerformed(AjaxRequestTarget target, IModel> rowModel) { + target.add(getObjectListPanel()); + tabLabelPanelUpdate(target); + } + + @Override + protected IModel getObjectSelectCheckBoxEnableModel(IModel> rowModel){ + if (rowModel == null){ + return Model.of(false); + } + List selectedObjects = getSelectedObjectsList(); + return Model.of(selectedObjects == null || selectedObjects.size() == 0 + || (rowModel.getObject() != null && rowModel.getObject().isSelected())); + } + + + @Override + protected ObjectTypes getObjectType() { + return ObjectTypes.ARCHETYPE; + } + + @Override + protected ObjectQuery addFilterToContentQuery(ObjectQuery query){ + super.addFilterToContentQuery(query); + if (query == null) { + query = getPrismContext().queryFactory().createQuery(); + } + List archetypeOidsList = getFilteredArchetypeOidsList(); + ObjectFilter filter = getPrismContext().queryFor(ArchetypeType.class) + .id(archetypeOidsList.toArray(new String[0])) + .buildFilter(); + query.addFilter(filter); + return query; + } + }; + } + }); + return tabs; + } + }; + + changeArchetypePopup.setOutputMarkupPlaceholderTag(true); + showMainPopup(changeArchetypePopup, target); + + } + + private List getFilteredArchetypeOidsList(){ + OperationResult result = new OperationResult(OPERATION_LOAD_FILTERED_ARCHETYPES); + PrismObject obj = getObjectWrapper().getObject(); + List oidsList = new ArrayList<>(); + try { + List filteredArchetypes = getModelInteractionService().getFilteredArchetypesByHolderType(obj, result); + if (filteredArchetypes != null){ + filteredArchetypes.forEach(archetype -> oidsList.add(archetype.getOid())); + } + } catch (SchemaException ex){ + result.recordPartialError(ex.getLocalizedMessage()); + LOGGER.error("Couldn't load assignment target specification for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); + } + return oidsList; + } + + protected abstract AbstractObjectMainPanel createMainPanel(String id); + + protected String getObjectOidParameter() { + PageParameters parameters = getPageParameters(); + LOGGER.trace("Page parameters: {}", parameters); + StringValue oidValue = parameters.get(OnePageParameterEncoder.PARAMETER); + LOGGER.trace("OID parameter: {}", oidValue); + if (oidValue == null) { + return null; + } + String oid = oidValue.toString(); + if (StringUtils.isBlank(oid)) { + return null; + } + return oid; + } + + protected ObjectSummaryPanel getSummaryPanel() { + return (ObjectSummaryPanel) get(ID_SUMMARY_PANEL); + } + + public boolean isOidParameterExists() { + return getObjectOidParameter() != null; + } + + protected PrismObjectWrapper loadObjectWrapper(PrismObject objectToEdit, boolean isReadonly) { + Task task = createSimpleTask(OPERATION_LOAD_OBJECT); + OperationResult result = task.getResult(); + PrismObject object = null; + try { + if (!isOidParameterExists()) { + if (objectToEdit == null) { + LOGGER.trace("Loading object: New object (creating)"); + O focusType = createNewObject(); + + // Apply subtype using page parameters + List subtypes = getPageParameters().getValues(ObjectType.F_SUBTYPE.getLocalPart()); + subtypes.stream().filter(p -> !p.isEmpty()).forEach(c -> focusType.subtype(c.toString())); + + getMidpointApplication().getPrismContext().adopt(focusType); + object = (PrismObject) focusType.asPrismObject(); + } else { + LOGGER.trace("Loading object: New object (supplied): {}", objectToEdit); + object = objectToEdit; + } + } else { + + String focusOid = getObjectOidParameter(); + object = WebModelServiceUtils.loadObject(getCompileTimeClass(), focusOid, buildGetOptions(), this, task, result); + LOGGER.trace("Loading object: Existing object (loadled): {} -> {}", focusOid, object); + } + + result.recordSuccess(); + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + } + + showResult(result, false); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Loaded object:\n{}", object.debugDump()); + } + + if (object == null) { + if (isOidParameterExists()) { + getSession().error(getString("pageAdminFocus.message.cantEditFocus")); + } else { + getSession().error(getString("pageAdminFocus.message.cantNewFocus")); + } + throw new RestartResponseException(getRestartResponsePage()); + } + + ItemStatus itemStatus = isOidParameterExists() || editingFocus ? ItemStatus.NOT_CHANGED : ItemStatus.ADDED; + PrismObjectWrapper wrapper; + + PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(object.getDefinition()); + WrapperContext context = new WrapperContext(task, result); + context.setCreateIfEmpty(ItemStatus.ADDED == itemStatus); + //we don't want to set to false.. refactor this method to take either enum (READONLY, AUTO, ...) or + // Boolean instead of boolean isReadonly + if (isReadonly) { + context.setReadOnly(isReadonly); + } + + + try { + wrapper = factory.createObjectWrapper(object.clone(), itemStatus, context); + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + showResult(result, false); + throw new RestartResponseException(getRestartResponsePage()); + } + + showResult(result, false); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump()); + } + + return wrapper; + } + + protected Collection> buildGetOptions() { + return getOperationOptionsBuilder() + .item(UserType.F_JPEG_PHOTO).retrieve() + .build(); + } + +// private void loadParentOrgs(PrismObjectWrapper wrapper, Task task, OperationResult result) { +// OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS); +// PrismObject focus = wrapper.getObject(); +// // Load parent organizations (full objects). There are used in the +// // summary panel and also in the main form. +// // Do it here explicitly instead of using resolve option to have ability +// // to better handle (ignore) errors. +// for (ObjectReferenceType parentOrgRef : focus.asObjectable().getParentOrgRef()) { +// +// PrismObject parentOrg = null; +// try { +// +// parentOrg = getModelService().getObject(OrgType.class, parentOrgRef.getOid(), null, task, +// subResult); +// LOGGER.trace("Loaded parent org with result {}", +// new Object[] { subResult.getLastSubresult() }); +// } catch (AuthorizationException e) { +// // This can happen if the user has permission to read parentOrgRef but it does not have +// // the permission to read target org +// // It is OK to just ignore it. +// subResult.muteLastSubresultError(); +// LOGGER.debug("User {} does not have permission to read parent org unit {} (ignoring error)", task.getOwner().getName(), parentOrgRef.getOid()); +// } catch (Exception ex) { +// subResult.recordWarning(createStringResource("PageAdminObjectDetails.message.loadParentOrgs.warning", parentOrgRef.getOid()).getString(), ex); +// LOGGER.warn("Cannot load parent org {}: {}", parentOrgRef.getOid(), ex.getMessage(), ex); +// } +// +// if (parentOrg != null) { +// wrapper.getParentOrgs().add(parentOrg); +// } +// } +// subResult.computeStatus(); +// } + + protected abstract Class getRestartResponsePage(); + + // TODO put this into correct place + protected boolean previewRequested; + + /** + * This will be called from the main form when save button is pressed. + */ + public void savePerformed(AjaxRequestTarget target) { + progressPanel.onBeforeSave(); + OperationResult result = new OperationResult(OPERATION_SAVE); + previewRequested = false; + saveOrPreviewPerformed(target, result, false); + } + + public void previewPerformed(AjaxRequestTarget target) { + progressPanel.onBeforeSave(); + OperationResult result = new OperationResult(OPERATION_PREVIEW_CHANGES); + previewRequested = true; + saveOrPreviewPerformed(target, result, true); + } + + public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly) { + saveOrPreviewPerformed(target, result, previewOnly, null); + } + + public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly, Task task) { + boolean delegationChangesExist = processDeputyAssignments(previewOnly); + + PrismObjectWrapper objectWrapper = getObjectWrapper(); + LOGGER.debug("Saving object {}", objectWrapper); + + // todo: improve, delta variable is quickfix for MID-1006 + // redirecting to user list page everytime user is created in repository + // during user add in gui, + // and we're not taking care about account/assignment create errors + // (error message is still displayed) + delta = null; + + if(task == null) { + task = createSimpleTask(OPERATION_SEND_TO_SUBMIT); + } + + ModelExecuteOptions options = getOptions(previewOnly); + + LOGGER.debug("Using execute options {}.", options); + + try { + reviveModels(); + + delta = objectWrapper.getObjectDelta(); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) }); + } + } catch (Exception ex) { + result.recordFatalError(getString("pageAdminObjectDetails.message.cantCreateObject"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Create Object failed", ex); + showResult(result); + target.add(getFeedbackPanel()); + return; + } + + switch (objectWrapper.getStatus()) { + case ADDED: + try { + PrismObject objectToAdd = delta.getObjectToAdd(); + WebComponentUtil.encryptCredentials(objectToAdd, true, getMidpointApplication()); + prepareObjectForAdd(objectToAdd); + getPrismContext().adopt(objectToAdd, getCompileTimeClass()); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) }); + } + + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + + final Collection> deltas = WebComponentUtil.createDeltaCollection(delta); + final Collection validationErrors = performCustomValidation(objectToAdd, deltas); + if (checkValidationErrors(target, validationErrors)) { + return; + } + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else { + result.recordSuccess(); + } + } catch (Exception ex) { + result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex); + showResult(result); + } + break; + + case NOT_CHANGED: + try { + WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); + prepareObjectDeltaForModify(delta); //preparing of deltas for projections (ADD, DELETE, UNLINK) + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) }); + } + + Collection> deltas = new ArrayList<>(); + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + deltas.add(delta); + } + + List> additionalDeltas = getAdditionalModifyDeltas(result); + if (additionalDeltas != null) { + for (ObjectDelta additionalDelta : additionalDeltas) { + if (!additionalDelta.isEmpty()) { + additionalDelta.revive(getPrismContext()); + deltas.add(additionalDelta); + } + } + } + + if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) { + ObjectDelta emptyDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), + objectWrapper.getObject().getOid()); + deltas.add(emptyDelta); + + Collection validationErrors = performCustomValidation(null, deltas); + if (checkValidationErrors(target, validationErrors)) { + return; + } + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else if (!deltas.isEmpty()) { + Collection validationErrors = performCustomValidation(null, deltas); + if (checkValidationErrors(target, validationErrors)) { + return; + } + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else if (previewOnly && delta.isEmpty() && delegationChangesExist){ + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else { + progressPanel.clearProgressPanel(); // from previous attempts (useful only if we would call finishProcessing at the end, but that's not the case now) + if (!previewOnly) { + if (!delegationChangesExist) { + result.recordWarning(getString("PageAdminObjectDetails.noChangesSave")); + showResult(result); + } + redirectBack(); + } else { + if (!delegationChangesExist) { + warn(getString("PageAdminObjectDetails.noChangesPreview")); + target.add(getFeedbackPanel()); + } + } + } + + } catch (Exception ex) { + if (!executeForceDelete(objectWrapper, task, options, result)) { + result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex); + LoggingUtils.logUnexpectedException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex); + } else { + result.recomputeStatus(); + } + showResult(result); + } + break; + // support for add/delete containers (e.g. delete credentials) + default: + error(getString("pageAdminFocus.message.unsupportedState", objectWrapper.getStatus())); + } + +// result.recomputeStatus(); +// +// if (!result.isInProgress()) { +// LOGGER.trace("Result NOT in progress, calling finishProcessing"); +// finishProcessing(target, result, false); +// } + + LOGGER.trace("returning from saveOrPreviewPerformed"); + } + + protected boolean processDeputyAssignments(boolean previewOnly){ + return false; + } + + protected boolean checkValidationErrors(AjaxRequestTarget target, Collection validationErrors) { + if (validationErrors != null && !validationErrors.isEmpty()) { + for (SimpleValidationError error : validationErrors) { + LOGGER.error("Validation error, attribute: '" + error.printAttribute() + + "', message: '" + error.getMessage() + "'."); + error("Validation error, attribute: '" + error.printAttribute() + + "', message: '" + error.getMessage() + "'."); + } + + target.add(getFeedbackPanel()); + return true; + } + return false; + } + + @Override + public void startProcessing(AjaxRequestTarget target, OperationResult result) { + LOGGER.trace("startProcessing called, making main panel invisible"); + mainPanel.setVisible(false); + target.add(mainPanel); + } + + @NotNull + protected ModelExecuteOptions getOptions(boolean previewOnly) { + ModelExecuteOptions options = mainPanel.getExecuteChangeOptionsDto().createOptions(); + if (previewOnly) { + options.getOrCreatePartialProcessing().setApprovals(PartialProcessingTypeType.PROCESS); + } + return options; + } + + protected void prepareObjectForAdd(PrismObject object) throws SchemaException { + + } + + protected void prepareObjectDeltaForModify(ObjectDelta objectDelta) throws SchemaException { + + } + + protected List> getAdditionalModifyDeltas(OperationResult result) { + return null; + } + + protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, + OperationResult parentResult) { + return isForce(); + } + + protected boolean isForce() { + return getMainPanel().getExecuteChangeOptionsDto().isForce(); + } + + protected boolean isKeepDisplayingResults() { + return getMainPanel().getExecuteChangeOptionsDto().isKeepDisplayingResults(); + } + + protected boolean isSaveInBackground(){ + return getMainPanel().getExecuteChangeOptionsDto().isSaveInBackground(); + } + + protected Collection performCustomValidation(PrismObject object, + Collection> deltas) throws SchemaException { + Collection errors = null; + + if (object == null) { + if (getObjectWrapper() != null && getObjectWrapper().getObjectOld() != null) { + object = getObjectWrapper().getObjectOld().clone(); // otherwise original object could get corrupted e.g. by applying the delta below + + for (ObjectDelta delta : deltas) { + // because among deltas there can be also ShadowType deltas + if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) { + delta.applyTo(object); + } + } + } + } else { + object = object.clone(); + } + + performAdditionalValidation(object, deltas, errors); + + for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { + if (errors == null) { + errors = validator.validateObject(object, deltas); + } else { + errors.addAll(validator.validateObject(object, deltas)); + } + } + + return errors; + } + + protected void performAdditionalValidation(PrismObject object, + Collection> deltas, Collection errors) throws SchemaException { + + } + + public List getObjectFormTypes() { + CompiledGuiProfile adminGuiConfiguration = getCompiledGuiProfile(); + ObjectFormsType objectFormsType = adminGuiConfiguration.getObjectForms(); + if (objectFormsType == null) { + return null; + } + List objectForms = objectFormsType.getObjectForm(); + if (objectForms == null || objectForms.isEmpty()) { + return objectForms; + } + List validObjectForms = new ArrayList<>(); + for (ObjectFormType objectForm: objectForms) { + if (isSupportedObjectType(objectForm.getType())) { + validObjectForms.add(objectForm); + } + } + return validObjectForms; + } + + protected boolean isSupportedObjectType(QName type) { + ObjectTypes objectType = ObjectTypes.getObjectType(getCompileTimeClass()); + return QNameUtil.match(objectType.getTypeQName(),type); + } + + public void setSaveOnConfigure(boolean saveOnConfigure) { + this.saveOnConfigure = saveOnConfigure; + } + + public boolean isSaveOnConfigure() { + return saveOnConfigure; + } + + public boolean isForcedPreview() { + GuiObjectDetailsPageType objectDetails = getCompiledGuiProfile().findObjectDetailsConfiguration(getCompileTimeClass()); + return objectDetails != null && DetailsPageSaveMethodType.FORCED_PREVIEW.equals(objectDetails.getSaveMethod()); + } + + //TODO moved from PageAdminFocus.. maybe we need PageAssignmentHolderDetails? + @Override + public void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync) { + + if (previewRequested) { + finishPreviewProcessing(target, result); + return; + } + if (result.isSuccess() && getDelta() != null && SecurityUtils.getPrincipalUser().getOid().equals(getDelta().getOid())) { + Session.get().setLocale(WebModelServiceUtils.getLocale()); + LOGGER.debug("Using {} as locale", getLocale()); + WebSession.get().getClientInfo().getProperties(). + setTimeZone(WebModelServiceUtils.getTimezone()); + LOGGER.debug("Using {} as time zone", WebSession.get().getClientInfo().getProperties().getTimeZone()); + } + boolean focusAddAttempted = getDelta() != null && getDelta().isAdd(); + boolean focusAddSucceeded = focusAddAttempted && StringUtils.isNotEmpty(getDelta().getOid()); + + // we don't want to allow resuming editing if a new focal object was created (on second 'save' there would be a conflict with itself) + // and also in case of partial errors, like those related to projections (many deltas would be already executed, and this could cause problems on second 'save'). + boolean canContinueEditing = !focusAddSucceeded && result.isFatalError(); + + boolean canExitPage; + if (returningFromAsync) { + canExitPage = getProgressPanel().isAllSuccess() || result.isInProgress() || result.isHandledError(); // if there's at least a warning in the progress table, we would like to keep the table open + } else { + canExitPage = !canContinueEditing; // no point in staying on page if we cannot continue editing (in synchronous case i.e. no progress table present) + } + + if (!isKeepDisplayingResults() && canExitPage) { + showResult(result); + redirectBack(); + } else { + if (returningFromAsync) { + getProgressPanel().showBackButton(target); + getProgressPanel().hideAbortButton(target); + } + showResult(result); + target.add(getFeedbackPanel()); + + if (canContinueEditing) { + getProgressPanel().hideBackButton(target); + getProgressPanel().showContinueEditingButton(target); + } + } + } + + private void finishPreviewProcessing(AjaxRequestTarget target, OperationResult result) { + getMainPanel().setVisible(true); + getProgressPanel().hide(); + getProgressPanel().hideAbortButton(target); + getProgressPanel().hideBackButton(target); + getProgressPanel().hideContinueEditingButton(target); + + showResult(result); + target.add(getFeedbackPanel()); + + Map, ModelContext> modelContextMap = new LinkedHashMap<>(); + modelContextMap.put(getObjectWrapper().getObject(), getProgressPanel().getPreviewResult()); + + processAdditionalFocalObjectsForPreview(modelContextMap); + + navigateToNext(new PagePreviewChanges(modelContextMap, getModelInteractionService())); + } + + protected void processAdditionalFocalObjectsForPreview(Map, ModelContext> modelContextMap){ + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java index 405dbc55684..bf1ba0ac656 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java @@ -1,129 +1,129 @@ -/* - * Copyright (c) 2010-2019 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.page.admin.archetype; - -import java.util.List; - -import org.apache.wicket.Page; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; -import com.evolveum.midpoint.gui.impl.page.admin.configuration.component.ContainerOfSystemConfigurationPanel; -import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.web.application.AuthorizationAction; -import com.evolveum.midpoint.web.application.PageDescriptor; -import com.evolveum.midpoint.web.component.ObjectSummaryPanel; -import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; -import com.evolveum.midpoint.web.component.objectdetails.AbstractRoleMainPanel; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.web.page.admin.PageAdminAbstractRole; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypePolicyType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypeType; - -@PageDescriptor( - url = "/admin/archetype", - encoder = OnePageParameterEncoder.class, - action = { - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPES_ALL_URL, - label = "PageArchetypes.auth.archetypesAll.label", - description = "PageArchetypes.auth.archetypesAll.description"), - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPE_URL, - label = "PageArchetype.auth.user.label", - description = "PageArchetype.auth.archetype.description") - }) -public class PageArchetype extends PageAdminAbstractRole { - - private static final long serialVersionUID = 1L; - - public PageArchetype() { - super(); - } - - public PageArchetype(PageParameters parameters) { - super(parameters); - } - - public PageArchetype(final PrismObject role) { - super(role); - } - - public PageArchetype(final PrismObject userToEdit, boolean isNewObject) { - super(userToEdit, isNewObject); - } - - public PageArchetype(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { - super(abstractRole, isNewObject, isReadonly); - } - - - @Override - public Class getCompileTimeClass() { - return ArchetypeType.class; - } - - @Override - protected ArchetypeType createNewObject() { - return new ArchetypeType(getPrismContext()); - } - - @Override - protected ObjectSummaryPanel createSummaryPanel() { - IModel> valueModel = new PropertyModel>(getObjectModel(), "value"); - return new ArchetypeSummaryPanel(ID_SUMMARY_PANEL, new ItemRealValueModel(valueModel), this); - - } - - @Override - protected AbstractObjectMainPanel createMainPanel(String id) { - return new AbstractRoleMainPanel(id, getObjectModel(), getProjectionModel(), this) { - - private static final long serialVersionUID = 1L; - - @Override - public AbstractRoleMemberPanel createMemberPanel(String panelId) { - return new ArchetypeMembersPanel(panelId, new Model<>(getObject().asObjectable())); - } - - @Override - protected List createTabs(PageAdminObjectDetails parentPage) { - List tabs = super.createTabs(parentPage); - tabs.add( - new PanelTab(parentPage.createStringResource("PageArchetype.archetypePolicy"), - getTabVisibility(ComponentConstants.UI_ARCHTYPE_TAB_ARCHETYPE_POLICY_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new ContainerOfSystemConfigurationPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ArchetypeType.F_ARCHETYPE_POLICY), ArchetypePolicyType.COMPLEX_TYPE); - } - }); - - return tabs; - } - }; - - } - - @Override - protected Class getRestartResponsePage() { - return PageArchetypes.class; - } - -} +/* + * Copyright (c) 2010-2019 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin.archetype; + +import java.util.List; + +import org.apache.wicket.Page; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; +import com.evolveum.midpoint.gui.impl.page.admin.configuration.component.ContainerOfSystemConfigurationPanel; +import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.security.api.AuthorizationConstants; +import com.evolveum.midpoint.web.application.AuthorizationAction; +import com.evolveum.midpoint.web.application.PageDescriptor; +import com.evolveum.midpoint.web.component.ObjectSummaryPanel; +import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.objectdetails.AbstractRoleMainPanel; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.web.page.admin.PageAdminAbstractRole; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; +import com.evolveum.midpoint.web.util.OnePageParameterEncoder; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypePolicyType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypeType; + +@PageDescriptor( + url = "/admin/archetype", + encoder = OnePageParameterEncoder.class, + action = { + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPES_ALL_URL, + label = "PageArchetypes.auth.archetypesAll.label", + description = "PageArchetypes.auth.archetypesAll.description"), + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPE_URL, + label = "PageArchetype.auth.user.label", + description = "PageArchetype.auth.archetype.description") + }) +public class PageArchetype extends PageAdminAbstractRole { + + private static final long serialVersionUID = 1L; + + public PageArchetype() { + super(); + } + + public PageArchetype(PageParameters parameters) { + super(parameters); + } + + public PageArchetype(final PrismObject role) { + super(role); + } + + public PageArchetype(final PrismObject userToEdit, boolean isNewObject) { + super(userToEdit, isNewObject); + } + + public PageArchetype(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { + super(abstractRole, isNewObject, isReadonly); + } + + + @Override + public Class getCompileTimeClass() { + return ArchetypeType.class; + } + + @Override + protected ArchetypeType createNewObject() { + return new ArchetypeType(getPrismContext()); + } + + @Override + protected ObjectSummaryPanel createSummaryPanel() { + IModel> valueModel = new PropertyModel<>(getObjectModel(), "value"); + return new ArchetypeSummaryPanel(ID_SUMMARY_PANEL, new ItemRealValueModel<>(valueModel), this); + + } + + @Override + protected AbstractObjectMainPanel createMainPanel(String id) { + return new AbstractRoleMainPanel(id, getObjectModel(), getProjectionModel(), this) { + + private static final long serialVersionUID = 1L; + + @Override + public AbstractRoleMemberPanel createMemberPanel(String panelId) { + return new ArchetypeMembersPanel(panelId, new Model<>(getObject().asObjectable())); + } + + @Override + protected List createTabs(PageAdminObjectDetails parentPage) { + List tabs = super.createTabs(parentPage); + tabs.add( + new PanelTab(parentPage.createStringResource("PageArchetype.archetypePolicy"), + getTabVisibility(ComponentConstants.UI_ARCHTYPE_TAB_ARCHETYPE_POLICY_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new ContainerOfSystemConfigurationPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ArchetypeType.F_ARCHETYPE_POLICY), ArchetypePolicyType.COMPLEX_TYPE); + } + }); + + return tabs; + } + }; + + } + + @Override + protected Class getRestartResponsePage() { + return PageArchetypes.class; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java index f8b1e7513fa..c8fdd454e16 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java @@ -80,7 +80,7 @@ public void onClick(AjaxRequestTarget target) { public void yesPerformed(AjaxRequestTarget target) { getPageBase().getCounterManager().removeCounter(counter); target.add(InternalsCountersPanel.this); - }; + } }; getPageBase().showMainPopup(confirmPanel, target); target.add(InternalsCountersPanel.this); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java index 2bcf4ccf948..6c5a662dfcf 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java @@ -63,7 +63,7 @@ protected void onError(AjaxRequestTarget target) { } }; form.add(update); - }; + } private void updateDebugPerformed(AjaxRequestTarget target){ getModelObject().saveDebugUtil(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java index 3f772b2d523..30c4d85be29 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java @@ -83,7 +83,7 @@ protected void onError(AjaxRequestTarget target) { } }; form.add(update); - }; + } private void updateTraces(AjaxRequestTarget target){ for (Entry entry: tracesMap.entrySet()) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java index 4c0ba85da28..e8e3e7a9a8c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java @@ -29,7 +29,7 @@ public class PasswordQuestionsDto implements Serializable{ }*/ public PasswordQuestionsDto(){ - }; + } public PasswordQuestionsDto(String passwQuestion, String passAnswer){ this.passwQuestion = passwQuestion; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java index 8677a761273..e8cb34ef72b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java @@ -1,237 +1,245 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.web.page.admin.reports; - -import com.evolveum.midpoint.gui.api.GuiStyleConstants; -import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; -import com.evolveum.midpoint.model.api.AssignmentObjectRelation; -import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; -import com.evolveum.midpoint.prism.PrismContainer; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.application.AuthorizationAction; -import com.evolveum.midpoint.web.application.PageDescriptor; -import com.evolveum.midpoint.web.application.Url; -import com.evolveum.midpoint.web.component.data.Table; -import com.evolveum.midpoint.web.component.data.column.ColumnMenuAction; -import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; -import com.evolveum.midpoint.web.component.util.SelectableBean; -import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; -import com.evolveum.midpoint.web.page.admin.PageAdmin; -import com.evolveum.midpoint.web.page.admin.configuration.PageAdminConfiguration; -import com.evolveum.midpoint.web.page.admin.reports.component.RunReportPopupPanel; -import com.evolveum.midpoint.web.session.UserProfileStorage; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportEngineSelectionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportParameterType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import java.util.ArrayList; -import java.util.List; - - -/** - * @author lazyman - */ -@PageDescriptor( - urls = { - @Url(mountUrl = "/admin/reports", matchUrlForSecurity = "/admin/reports") - }, - action = { - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_ALL_URL, - label = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_LABEL, - description = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_DESCRIPTION), - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_URL, - label = "PageReports.auth.reports.label", - description = "PageReports.auth.reports.description")}) -public class PageReports extends PageAdmin { - - private static final Trace LOGGER = TraceManager.getTrace(PageReports.class); - - private static final String DOT_CLASS = PageReports.class.getName() + "."; - private static final String OPERATION_RUN_REPORT = DOT_CLASS + "runReport"; - - private static final String ID_MAIN_FORM = "mainForm"; - private static final String ID_REPORTS_TABLE = "reportsTable"; - - public PageReports() { - initLayout(); - } - - private void initLayout() { - Form mainForm = new com.evolveum.midpoint.web.component.form.Form(ID_MAIN_FORM); - add(mainForm); - - MainObjectListPanel table = - new MainObjectListPanel(ID_REPORTS_TABLE, ReportType.class, UserProfileStorage.TableId.PAGE_REPORTS, - null) { - - @Override - protected IColumn, String> createCheckboxColumn() { - return null; - } - - @Override - public void objectDetailsPerformed(AjaxRequestTarget target, ReportType report) { - if (report != null) { - PageReports.this.reportDetailsPerformed(target, report.getOid()); - } - } - - @Override - protected List, String>> createColumns() { - return PageReports.this.initColumns(); - } - - @Override - protected List createInlineMenu() { - return PageReports.this.createInlineMenu(); - } - - @Override - protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { - navigateToNext(PageNewReport.class); - } - }; - table.setOutputMarkupId(true); - mainForm.add(table); - - } - - private List, String>> initColumns() { - List, String>> columns = new ArrayList<>(); - - IColumn column = new PropertyColumn(createStringResource("PageReports.table.description"), "value.description"); - columns.add(column); - - return columns; - } - - private void reportDetailsPerformed(AjaxRequestTarget target, String oid) { - PageParameters params = new PageParameters(); - params.add(OnePageParameterEncoder.PARAMETER, oid); - navigateToNext(PageCreatedReports.class, params); - } - - private List createInlineMenu(){ - List menu = new ArrayList<>(); - menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.run")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new ColumnMenuAction>() { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - ReportType report = getRowModel().getObject().getValue(); - runReportPerformed(target, report); - } - }; - } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_START_MENU_ITEM; - } - - @Override - public boolean isHeaderMenuItem(){ - return false; - } - }); - menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.configure")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new ColumnMenuAction>() { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - ReportType reportObject = getRowModel().getObject().getValue(); - configurePerformed(target, reportObject); - } - }; - } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_EDIT_MENU_ITEM; - } - - @Override - public boolean isHeaderMenuItem(){ - return false; - } - }); - return menu; - - } - - private void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { - OperationResult result = new OperationResult(OPERATION_RUN_REPORT); - Task task = createSimpleTask(OPERATION_RUN_REPORT); - try { - getReportManager().runReport(reportType.asPrismObject(), reportParam, task, result); - } catch (Exception ex) { - result.recordFatalError(ex); - } finally { - result.computeStatusIfUnknown(); - } - - showResult(result); - target.add(getFeedbackPanel(), get(createComponentPath(ID_MAIN_FORM))); - hideMainPopup(target); - - } - - protected void runReportPerformed(AjaxRequestTarget target, ReportType report) { - - if(report.getReportEngine() != null && report.getReportEngine().equals(ReportEngineSelectionType.DASHBOARD)) { - runConfirmPerformed(target, report, null); - return; - } - - RunReportPopupPanel runReportPopupPanel = new RunReportPopupPanel(getMainPopupBodyId(), report) { - - private static final long serialVersionUID = 1L; - - protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { - PageReports.this.runConfirmPerformed(target, reportType, reportParam); - hideMainPopup(target); - - }; - }; - showMainPopup(runReportPopupPanel, target); - - } - - private void configurePerformed(AjaxRequestTarget target, ReportType report) { - PageParameters params = new PageParameters(); - params.add(OnePageParameterEncoder.PARAMETER, report.getOid()); - navigateToNext(PageReport.class, params); - } - - private Table getReportTable() { - return (Table) get(createComponentPath(ID_MAIN_FORM, ID_REPORTS_TABLE)); - } -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.web.page.admin.reports; + +import com.evolveum.midpoint.gui.api.GuiStyleConstants; +import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; +import com.evolveum.midpoint.model.api.AssignmentObjectRelation; +import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; +import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.schema.constants.ObjectTypes; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.security.api.AuthorizationConstants; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.application.AuthorizationAction; +import com.evolveum.midpoint.web.application.PageDescriptor; +import com.evolveum.midpoint.web.application.Url; +import com.evolveum.midpoint.web.component.data.Table; +import com.evolveum.midpoint.web.component.data.column.ColumnMenuAction; +import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; +import com.evolveum.midpoint.web.component.util.SelectableBean; +import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; +import com.evolveum.midpoint.web.page.admin.PageAdmin; +import com.evolveum.midpoint.web.page.admin.configuration.PageAdminConfiguration; +import com.evolveum.midpoint.web.page.admin.reports.component.RunReportPopupPanel; +import com.evolveum.midpoint.web.session.UserProfileStorage; +import com.evolveum.midpoint.web.util.OnePageParameterEncoder; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportEngineSelectionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportParameterType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; + +import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import java.util.ArrayList; +import java.util.List; + + +/** + * @author lazyman + */ +@PageDescriptor( + urls = { + @Url(mountUrl = "/admin/reports", matchUrlForSecurity = "/admin/reports") + }, + action = { + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_ALL_URL, + label = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_LABEL, + description = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_DESCRIPTION), + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_URL, + label = "PageReports.auth.reports.label", + description = "PageReports.auth.reports.description")}) +public class PageReports extends PageAdmin { + + private static final Trace LOGGER = TraceManager.getTrace(PageReports.class); + + private static final String DOT_CLASS = PageReports.class.getName() + "."; + private static final String OPERATION_RUN_REPORT = DOT_CLASS + "runReport"; + + private static final String ID_MAIN_FORM = "mainForm"; + private static final String ID_REPORTS_TABLE = "reportsTable"; + + public PageReports() { + initLayout(); + } + + private void initLayout() { + Form mainForm = new com.evolveum.midpoint.web.component.form.Form(ID_MAIN_FORM); + add(mainForm); + + MainObjectListPanel table = + new MainObjectListPanel(ID_REPORTS_TABLE, ReportType.class, UserProfileStorage.TableId.PAGE_REPORTS, + null) { + + @Override + protected IColumn, String> createCheckboxColumn() { + return null; + } + + @Override + public void objectDetailsPerformed(AjaxRequestTarget target, ReportType report) { + if (report != null) { + PageReports.this.reportDetailsPerformed(target, report.getOid()); + } + } + + @Override + protected List, String>> createColumns() { + return PageReports.this.initColumns(); + } + + @Override + protected List createInlineMenu() { + return PageReports.this.createInlineMenu(); + } + + @Override + protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { + navigateToNext(PageNewReport.class); + } + }; + table.setOutputMarkupId(true); + mainForm.add(table); + + } + + private List, String>> initColumns() { + List, String>> columns = new ArrayList<>(); + + IColumn column = new PropertyColumn(createStringResource("PageReports.table.description"), "value.description"); + columns.add(column); + + return columns; + } + + private void reportDetailsPerformed(AjaxRequestTarget target, String oid) { + PageParameters params = new PageParameters(); + params.add(OnePageParameterEncoder.PARAMETER, oid); + navigateToNext(PageCreatedReports.class, params); + } + + private List createInlineMenu(){ + List menu = new ArrayList<>(); + menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.run")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new ColumnMenuAction>() { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ReportType report = getRowModel().getObject().getValue(); + runReportPerformed(target, report); + } + }; + } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_START_MENU_ITEM; + } + + @Override + public boolean isHeaderMenuItem(){ + return false; + } + }); + menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.configure")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new ColumnMenuAction>() { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ReportType reportObject = getRowModel().getObject().getValue(); + configurePerformed(target, reportObject); + } + }; + } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_EDIT_MENU_ITEM; + } + + @Override + public boolean isHeaderMenuItem(){ + return false; + } + }); + return menu; + + } + + private void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { + OperationResult result = new OperationResult(OPERATION_RUN_REPORT); + Task task = createSimpleTask(OPERATION_RUN_REPORT); + task.getUpdatedTaskObject().asObjectable().getAssignment() + .add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_REPORT_TASK.value(), ObjectTypes.ARCHETYPE, getPrismContext())); + task.getUpdatedTaskObject().asObjectable().getArchetypeRef() + .add(ObjectTypeUtil.createObjectRef(SystemObjectsType.ARCHETYPE_REPORT_TASK.value(), ObjectTypes.ARCHETYPE)); + try { + getReportManager().runReport(reportType.asPrismObject(), reportParam, task, result); + } catch (Exception ex) { + result.recordFatalError(ex); + } finally { + result.computeStatusIfUnknown(); + } + + showResult(result); + target.add(getFeedbackPanel(), get(createComponentPath(ID_MAIN_FORM))); + hideMainPopup(target); + + } + + protected void runReportPerformed(AjaxRequestTarget target, ReportType report) { + + if(report.getReportEngine() != null && report.getReportEngine().equals(ReportEngineSelectionType.DASHBOARD)) { + runConfirmPerformed(target, report, null); + return; + } + + RunReportPopupPanel runReportPopupPanel = new RunReportPopupPanel(getMainPopupBodyId(), report) { + + private static final long serialVersionUID = 1L; + + protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { + PageReports.this.runConfirmPerformed(target, reportType, reportParam); + hideMainPopup(target); + + } + }; + showMainPopup(runReportPopupPanel, target); + + } + + private void configurePerformed(AjaxRequestTarget target, ReportType report) { + PageParameters params = new PageParameters(); + params.add(OnePageParameterEncoder.PARAMETER, report.getOid()); + navigateToNext(PageReport.class, params); + } + + private Table getReportTable() { + return (Table) get(createComponentPath(ID_MAIN_FORM, ID_REPORTS_TABLE)); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java index 5fc8c40919e..6404482376e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java @@ -326,7 +326,7 @@ public boolean isVisible() { initButton(ID_IMPORT, "Import", " fa-download", TaskCategory.IMPORTING_ACCOUNTS, SystemObjectsType.ARCHETYPE_IMPORT_TASK.value()); initButton(ID_RECONCILIATION, "Reconciliation", " fa-link", TaskCategory.RECONCILIATION, SystemObjectsType.ARCHETYPE_RECONCILIATION_TASK.value()); - initButton(ID_LIVE_SYNC, "Live Sync", " fa-refresh", TaskCategory.LIVE_SYNCHRONIZATION, SystemObjectsType.ARCHETYPE_LIVE_SYNCH_TASK.value()); + initButton(ID_LIVE_SYNC, "Live Sync", " fa-refresh", TaskCategory.LIVE_SYNCHRONIZATION, SystemObjectsType.ARCHETYPE_LIVE_SYNC_TASK.value()); initCustomLayout(); } @@ -525,7 +525,7 @@ private List getTasksForKind(List> tasks) { protected void initCustomLayout() { // Nothing to do, for subclass extension - }; + } protected ObjectQuery createQuery() { ObjectQuery baseQuery = null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java index f90c8bcba3c..fa0d04fe500 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java @@ -1,1248 +1,1256 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.page.admin.roles; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.gui.impl.component.icon.CompositedIcon; -import com.evolveum.midpoint.gui.impl.component.icon.CompositedIconBuilder; -import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; -import com.evolveum.midpoint.model.api.AssignmentObjectRelation; -import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.QueryFactory; -import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty; -import com.evolveum.midpoint.schema.constants.RelationTypes; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.web.component.MultiFunctinalButtonDto; -import com.evolveum.midpoint.web.component.MultifunctionalButton; -import com.evolveum.midpoint.web.component.data.column.ColumnUtils; -import com.evolveum.midpoint.web.component.dialog.ConfigureTaskConfirmationPanel; -import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; -import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; -import com.evolveum.midpoint.web.component.util.SelectableBean; -import com.evolveum.midpoint.web.page.admin.configuration.component.HeaderMenuAction; -import com.evolveum.midpoint.web.session.MemberPanelStorage; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Component; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; -import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; - -import com.evolveum.midpoint.gui.api.GuiStyleConstants; -import com.evolveum.midpoint.gui.api.component.BasePanel; -import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.prism.PrismConstants; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.dialog.ChooseFocusTypeAndRelationDialogPanel; -import com.evolveum.midpoint.web.component.form.CheckFormGroup; -import com.evolveum.midpoint.web.component.form.DropDownFormGroup; -import com.evolveum.midpoint.web.component.input.QNameObjectTypeChoiceRenderer; -import com.evolveum.midpoint.web.component.input.RelationDropDownChoicePanel; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; -import com.evolveum.midpoint.web.component.search.Search; -import com.evolveum.midpoint.web.component.search.SearchFactory; -import com.evolveum.midpoint.web.component.util.EnableBehaviour; -import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; -import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.component.ChooseTypePanel; -import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto; -import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; -import com.evolveum.midpoint.web.session.UserProfileStorage.TableId; - -import org.apache.wicket.model.StringResourceModel; - -import static com.evolveum.midpoint.web.component.data.column.ColumnUtils.createStringResource; - -public abstract class AbstractRoleMemberPanel extends BasePanel { - - private static final long serialVersionUID = 1L; - - protected enum QueryScope { - SELECTED, ALL, ALL_DIRECT - } - - protected enum MemberOperation { - ADD, REMOVE, RECOMPUTE - } - - private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMemberPanel.class); - private static final String DOT_CLASS = AbstractRoleMemberPanel.class.getName() + "."; - protected static final String OPERATION_LOAD_MEMBER_RELATIONS = DOT_CLASS + "loadMemberRelationsList"; - protected static final String OPERATION_LOAD_ARCHETYPE_OBJECT = DOT_CLASS + "loadArchetypeObject"; - - protected static final String ID_FORM = "form"; - - protected static final String ID_CONTAINER_MEMBER = "memberContainer"; - protected static final String ID_CHILD_TABLE = "childUnitTable"; - protected static final String ID_MEMBER_TABLE = "memberTable"; - - private static final String ID_OBJECT_TYPE = "type"; - private static final String ID_TENANT = "tenant"; - private static final String ID_PROJECT = "project"; - private static final String ID_INDIRECT_MEMBERS = "indirectMembers"; - - protected static final String ID_SEARCH_SCOPE = "searchScope"; - protected SearchBoxScopeType scopeDefaultValue = null; - protected QName objectTypeDefaultValue = null; - - protected static final String ID_SEARCH_BY_RELATION = "searchByRelation"; - - private static Map> authorizations = new HashMap<>(); - private static Map tablesId = new HashMap<>(); - - static { - tablesId.put(RoleType.COMPLEX_TYPE, TableId.ROLE_MEMEBER_PANEL); - tablesId.put(ServiceType.COMPLEX_TYPE, TableId.SERVICE_MEMEBER_PANEL); - tablesId.put(OrgType.COMPLEX_TYPE, TableId.ORG_MEMEBER_PANEL); - tablesId.put(ArchetypeType.COMPLEX_TYPE, TableId.ARCHETYPE_MEMEBER_PANEL); - } - - static { - authorizations.put(RoleType.COMPLEX_TYPE, GuiAuthorizationConstants.ROLE_MEMBERS_AUTHORIZATIONS); - authorizations.put(ServiceType.COMPLEX_TYPE, GuiAuthorizationConstants.SERVICE_MEMBERS_AUTHORIZATIONS); - authorizations.put(OrgType.COMPLEX_TYPE, GuiAuthorizationConstants.ORG_MEMBERS_AUTHORIZATIONS); - authorizations.put(ArchetypeType.COMPLEX_TYPE, GuiAuthorizationConstants.ARCHETYPE_MEMBERS_AUTHORIZATIONS); - } - - public AbstractRoleMemberPanel(String id, IModel model) { - super(id, model); - } - - @Override - protected void onInitialize(){ - super.onInitialize(); - initLayout(); - } - - protected void initLayout() { - Form form = new com.evolveum.midpoint.web.component.form.Form(ID_FORM); - form.setOutputMarkupId(true); - add(form); - initDefaultSearchParameters(); - initSearch(form); - initMemberTable(form); - setOutputMarkupId(true); - - } - - private void initDefaultSearchParameters(){ - GuiObjectListPanelConfigurationType additionalPanel = getAdditionalPanelConfig(); - if (additionalPanel != null && additionalPanel.getSearchBoxConfiguration() != null) { - scopeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultScope(); - objectTypeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultObjectType(); - } - if (scopeDefaultValue == null){ - scopeDefaultValue = SearchBoxScopeType.ONE_LEVEL; - } - if (objectTypeDefaultValue == null){ - objectTypeDefaultValue = WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType()); - } - if (getMemberPanelStorage() != null){ - if (getMemberPanelStorage().getOrgSearchScope() == null){ - getMemberPanelStorage().setOrgSearchScope(scopeDefaultValue); - } - if (getMemberPanelStorage().getType() == null){ - getMemberPanelStorage().setType(ObjectTypes.getObjectType(objectTypeDefaultValue.getLocalPart())); - } - } - } - - protected Form getForm() { - return (Form) get(ID_FORM); - } - - private void initMemberTable(Form form) { - WebMarkupContainer memberContainer = new WebMarkupContainer(ID_CONTAINER_MEMBER); - memberContainer.setOutputMarkupId(true); - memberContainer.setOutputMarkupPlaceholderTag(true); - form.add(memberContainer); - - PageBase pageBase = getPageBase(); - Class type = getMemberPanelStorage() != null && getMemberPanelStorage().getType() != null ? - getMemberPanelStorage().getType().getClassDefinition() : ObjectType.class; - //TODO QName defines a relation value which will be used for new member creation - MainObjectListPanel childrenListPanel = new MainObjectListPanel( - ID_MEMBER_TABLE, type, getTableId(getComplexTypeQName()), getSearchOptions()) { - - private static final long serialVersionUID = 1L; - - @Override - protected void objectDetailsPerformed(AjaxRequestTarget target, ObjectType object) { - detailsPerformed(target, object); - } - - @Override - protected boolean isObjectDetailsEnabled(IModel> rowModel) { - if (rowModel == null || rowModel.getObject() == null - || rowModel.getObject().getValue() == null) { - return false; - } - Class objectClass = rowModel.getObject().getValue().getClass(); - return WebComponentUtil.hasDetailsPage(objectClass); - } - - @Override - protected DisplayType getNewObjectButtonSpecialDisplayType(){ - return getCreateMemberButtonDisplayType(); - } - - @Override - protected DisplayType getNewObjectButtonStandardDisplayType(){ - return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", - createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); - } - - @Override - protected List loadButtonDescriptions() { - return createAdditionalButtonsDescription(); - } - - @Override - protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { - AbstractRoleMemberPanel.this.createFocusMemberPerformed(target, relation); - } - - @Override - protected List createToolbarButtonsList(String buttonId){ - List buttonsList = super.createToolbarButtonsList(buttonId); - MultifunctionalButton assignButton = createAssignButton(buttonId); - buttonsList.add(1, assignButton); - return buttonsList; - } - - @Override - protected IColumn, String> createIconColumn(){ - return (IColumn) ColumnUtils.createIconColumn(pageBase); - } - - @Override - protected List, String>> createColumns() { - return createMembersColumns(); - } - - @Override - protected List createInlineMenu() { - return createRowActions(); - } - - @Override - protected Search createSearch() { - return getMemberPanelStorage() != null && getMemberPanelStorage().getSearch() != null ? - getMemberPanelStorage().getSearch() : SearchFactory.createSearch(getDefaultObjectType(), pageBase); - } - - @Override - protected ObjectQuery createContentQuery() { - ObjectQuery q = super.createContentQuery(); - - ObjectQuery members = AbstractRoleMemberPanel.this.createContentQuery(); - - List filters = new ArrayList<>(); - - if (q != null && q.getFilter() != null) { - filters.add(q.getFilter()); - } - - if (members != null && members.getFilter() != null) { - filters.add(members.getFilter()); - } - - QueryFactory queryFactory = pageBase.getPrismContext().queryFactory(); - if (filters.size() == 1) { - return queryFactory.createQuery(filters.iterator().next()); - } else { - return queryFactory.createQuery(queryFactory.createAnd(filters)); - } - } - - @Override - protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ - return AbstractRoleMemberPanel.this.getAdditionalPanelConfig(); - } - - @Override - protected boolean isAdditionalPanel(){ - return true; - } - - protected boolean isTypeChanged(Class newTypeClass){ - return true; - } - }; - childrenListPanel.setOutputMarkupId(true); - memberContainer.add(childrenListPanel); - } - - private List createAdditionalButtonsDescription() { - List multiFunctinalButtonDtos = new ArrayList<>(); - List loadedRelations = loadMemberRelationsList(); - if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(loadedRelations)) { - List relations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadedRelations); - relations.forEach(relation -> { - MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); - DisplayType additionalButtonDisplayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(getPageBase(), relation, - "abstractRoleMemberPanel.menu.createMember"); - buttonDto.setAdditionalButtonDisplayType(additionalButtonDisplayType); - buttonDto.setCompositedIcon(createCompositedIcon(relation, additionalButtonDisplayType)); - buttonDto.setAssignmentObjectRelation(relation); - multiFunctinalButtonDtos.add(buttonDto); - }); - } - return multiFunctinalButtonDtos; - } - - private CompositedIcon createCompositedIcon(AssignmentObjectRelation relation, DisplayType additionalButtonDisplayType) { - CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(getPageBase(), relation, - additionalButtonDisplayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green")); - if (builder == null) { - return null; - } - return builder.build(); - } - - private MultifunctionalButton createAssignButton(String buttonId) { - MultifunctionalButton assignButton = new MultifunctionalButton(buttonId, createAssignmentAdditionalButtons()) { - private static final long serialVersionUID = 1L; - - - @Override - protected void buttonClickPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { - List relations = relation != null && !CollectionUtils.isEmpty(relation.getRelations()) ? - Arrays.asList(relation.getRelations().get(0)) : getSupportedRelations().getAvailableRelationList(); - AvailableRelationDto avariableRelations = new AvailableRelationDto(relations, getSupportedRelations().getDefaultRelation()); - List objectTypes = relation != null && !CollectionUtils.isEmpty(relation.getObjectTypes()) ? - relation.getObjectTypes() : null; - List archetypeRefList = relation != null && !CollectionUtils.isEmpty(relation.getArchetypeRefs()) ? - relation.getArchetypeRefs() : null; - assignMembers(target, avariableRelations, objectTypes, archetypeRefList, relation == null); - } - - @Override - protected DisplayType getMainButtonDisplayType(){ - return getAssignMemberButtonDisplayType(); - } - - @Override - protected DisplayType getDefaultObjectButtonDisplayType(){ - return getAssignMemberButtonDisplayType(); - } - - }; - assignButton.add(AttributeAppender.append("class", "btn-margin-right")); - - - return assignButton; - } - - private List createAssignmentAdditionalButtons() { - List additionalAssignmentButtons = new ArrayList<>(); - List assignmentObjectRelations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadMemberRelationsList()); - if (assignmentObjectRelations == null) { - return additionalAssignmentButtons; - } - assignmentObjectRelations.forEach(relation -> { - MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); - buttonDto.setAssignmentObjectRelation(relation); - - DisplayType additionalDispayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(AbstractRoleMemberPanel.this.getPageBase(), relation, - "abstractRoleMemberPanel.menu.assignMember"); - //TODO null additinalDisplayType - CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(AbstractRoleMemberPanel.this.getPageBase(), relation, - additionalDispayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green")); - CompositedIcon icon = builder.build(); - buttonDto.setAdditionalButtonDisplayType(additionalDispayType); - buttonDto.setCompositedIcon(icon); - additionalAssignmentButtons.add(buttonDto); - }); - - return additionalAssignmentButtons; - - } - - protected TableId getTableId(QName complextType) { - return tablesId.get(complextType); - } - - protected Map getAuthorizations(QName complexType) { - return authorizations.get(complexType); - } - - protected QName getComplexTypeQName() { - return getModelObject().asPrismObject().getComplexTypeDefinition().getTypeName(); - } - - private DisplayType getCreateMemberButtonDisplayType(){ - return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", - AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); - } - - private DisplayType getAssignMemberButtonDisplayType(){ - return WebComponentUtil.createDisplayType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green", - AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.assignMember", "", "").getString()); - } - - protected List createRowActions() { - List menu = new ArrayList<>(); - createAssignMemberRowAction(menu); - - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_UNASSIGN)) { - menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.unassign")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - unassignMembersPerformed(target); - } - }; - - } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_UNASSIGN; - } - }); - } - - createRecomputeMemberRowAction(menu); - - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_CREATE)) { - menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.create")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - createFocusMemberPerformed(target); - } - }; - } - }); - } - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_DELETE)) { - menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.delete")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - deleteMembersPerformed(target); - } - }; - } - - }); - } - return menu; - } - - protected void createAssignMemberRowAction(List menu) { - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_ASSIGN)) { - menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.assign")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - MemberOperationsHelper.assignMembers(getPageBase(), AbstractRoleMemberPanel.this.getModelObject(), target, getSupportedRelations(), null); - } - }; - } - }); - } - } - - protected void createRecomputeMemberRowAction(List menu) { - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_RECOMPUTE)) { - menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.recompute")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - recomputeMembersPerformed(target); - } - }; - } - -// @Override -// public IModel getConfirmationMessageModel() { -// return getMemberTable().getSelectedObjectsCount() > 0 ? -// createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") -// : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); -// } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_RECONCILE_MENU_ITEM; - } - - }); - } - } - - - - protected abstract AvailableRelationDto getSupportedRelations(); - - protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ - return null; - } - - private boolean isAuthorized(String action) { - Map memeberAuthz = getAuthorizations(getComplexTypeQName()); - return WebComponentUtil.isAuthorized(memeberAuthz.get(action)); - } - - - - private List loadMemberRelationsList(){ - List assignmentTargetRelations = new ArrayList<>(); - AssignmentCandidatesSpecification spec = loadCandidateSpecification(); - assignmentTargetRelations = spec != null ? spec.getAssignmentObjectRelations() : new ArrayList<>(); - return assignmentTargetRelations; - } - - private AssignmentCandidatesSpecification loadCandidateSpecification(){ - OperationResult result = new OperationResult(OPERATION_LOAD_MEMBER_RELATIONS); - PrismObject obj = getModelObject().asPrismObject(); - AssignmentCandidatesSpecification spec = null; - try { - spec = getPageBase().getModelInteractionService() - .determineAssignmentHolderSpecification(obj, result); - } catch (SchemaException | ConfigurationException ex){ - result.recordPartialError(ex.getLocalizedMessage()); - LOGGER.error("Couldn't load member relations list for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); - } - return spec; - } - - protected void assignMembers(AjaxRequestTarget target, AvailableRelationDto availableRelationList, - List objectTypes, List archetypeRefList, boolean isOrgTreePanelVisible) { - MemberOperationsHelper.assignMembers(getPageBase(), getModelObject(), target, availableRelationList, - objectTypes, archetypeRefList, isOrgTreePanelVisible); - } - - private void unassignMembersPerformed(AjaxRequestTarget target) { - QueryScope scope = getQueryScope(false); - - ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), - createStringResource("abstractRoleMemberPanel.unassignAllMembersConfirmationLabel")) { - private static final long serialVersionUID = 1L; - - @Override - protected List getSupportedObjectTypes() { - return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); - } - - @Override - protected List getSupportedRelations() { - return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); - } - - @Override - protected boolean isFocusTypeSelectorVisible() { - return !QueryScope.SELECTED.equals(scope); - } - - - protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - unassignMembersPerformed(type, scope, relations, target); - } - - @Override - protected QName getDefaultObjectType() { - return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), - AbstractRoleMemberPanel.this.getDefaultObjectType()); - } - }; - - getPageBase().showMainPopup(chooseTypePopupContent, target); - } - - private void deleteMembersPerformed(AjaxRequestTarget target) { - QueryScope scope = getQueryScope(false); - ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), - createStringResource("abstractRoleMemberPanel.deleteAllMembersConfirmationLabel")) { - private static final long serialVersionUID = 1L; - - @Override - protected List getSupportedObjectTypes() { - return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); - } - - @Override - protected List getSupportedRelations() { - return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); - } - - protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - deleteMembersPerformed(type, scope, relations, target); - - } - - @Override - protected boolean isFocusTypeSelectorVisible() { - return !QueryScope.SELECTED.equals(scope); - } - - @Override - protected QName getDefaultObjectType() { - return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), - AbstractRoleMemberPanel.this.getDefaultObjectType()); - } - - }; - - getPageBase().showMainPopup(chooseTypePopupContent, target); - - } - - protected void createFocusMemberPerformed(AjaxRequestTarget target) { - createFocusMemberPerformed(target, null); - } - - protected void createFocusMemberPerformed(AjaxRequestTarget target, AssignmentObjectRelation relationSpec) { - if (relationSpec != null){ - try { - List newReferences = new ArrayList<>(); - if (CollectionUtils.isEmpty(relationSpec.getRelations())){ - relationSpec.setRelations(Arrays.asList(RelationTypes.MEMBER.getRelation())); - } - ObjectReferenceType memberRef = ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relationSpec.getRelations().get(0)); - newReferences.add(memberRef); - if (CollectionUtils.isNotEmpty(relationSpec.getArchetypeRefs())) { - newReferences.add(relationSpec.getArchetypeRefs().get(0)); - } - QName newMemberType = CollectionUtils.isNotEmpty(relationSpec.getObjectTypes()) ? relationSpec.getObjectTypes().get(0) : - getSupportedObjectTypes(false).get(0); - WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), newMemberType, newReferences); - } catch (SchemaException e) { - throw new SystemException(e.getMessage(), e); - } - } else { - ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel( - getPageBase().getMainPopupBodyId()) { - private static final long serialVersionUID = 1L; - - @Override - protected List getSupportedObjectTypes() { - return AbstractRoleMemberPanel.this.getNewMemberObjectTypes(); - } - - @Override - protected List getSupportedRelations() { - return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); - } - - protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - if (type == null) { - getSession().warn("No type was selected. Cannot create member"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - if (relations == null || relations.isEmpty()) { - getSession().warn("No relation was selected. Cannot create member"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - AbstractRoleMemberPanel.this.getPageBase().hideMainPopup(target); - try { - List newReferences = new ArrayList<>(); - for (QName relation : relations) { - newReferences.add(ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relation)); - } - WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), type, newReferences); - } catch (SchemaException e) { - throw new SystemException(e.getMessage(), e); - } - - } - - @Override - protected QName getDefaultObjectType() { - if (relationSpec != null && CollectionUtils.isNotEmpty(relationSpec.getObjectTypes())) { - return relationSpec.getObjectTypes().get(0); - } - return super.getDefaultObjectType(); - } - - @Override - protected boolean isFocusTypeSelectorVisible() { - return relationSpec == null; - } - }; - - getPageBase().showMainPopup(chooseTypePopupContent, target); - } - } - - protected void deleteMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { - if (relations == null || relations.isEmpty()) { - getSession().warn("No relation was selected. Cannot perform delete members"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - MemberOperationsHelper.deleteMembersPerformed(getPageBase(), scope, getActionQuery(scope, relations), type, target); - } - - protected void unassignMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { - if (relations == null || relations.isEmpty()) { - getSession().warn("No relation was selected. Cannot perform unassign members"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - MemberOperationsHelper.unassignMembersPerformed(getPageBase(), getModelObject(), scope, getActionQuery(scope, relations), relations, type, target); - } - - private ObjectViewDto getParameter(String panelId) { - ChooseTypePanel tenantChoice = (ChooseTypePanel) get(createComponentPath(ID_FORM, panelId)); - return tenantChoice.getModelObject(); - } - - protected ObjectQuery getActionQuery(QueryScope scope, Collection relations) { - switch (scope) { - case ALL: - return createAllMemberQuery(relations); - case ALL_DIRECT: - return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); - case SELECTED: - return MemberOperationsHelper.createSelectedObjectsQuery(getMemberTable().getSelectedObjects(), getPrismContext()); - } - - return null; - } - - protected void initSearch(Form form) { - - List scopeValues = Arrays.asList(SearchBoxScopeType.values()); - DropDownFormGroup searchScrope = createDropDown(ID_SEARCH_SCOPE, - Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getOrgSearchScope() : scopeDefaultValue), - scopeValues, - WebComponentUtil.getEnumChoiceRenderer(AbstractRoleMemberPanel.this), - "abstractRoleMemberPanel.searchScope", "abstractRoleMemberPanel.searchScope.tooltip", true); - searchScrope.add(new VisibleBehaviour(() -> getModelObject() instanceof OrgType)); - form.add(searchScrope); - - List supportedTypes = getSupportedObjectTypes(false); - DropDownFormGroup typeSelect = createDropDown(ID_OBJECT_TYPE, - Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType())), - supportedTypes, new QNameObjectTypeChoiceRenderer(){ - private static final long serialVersionUID = 1L; - - @Override - public Object getDisplayValue(QName qname) { - if (qname == null || getObjectTypesListParentType().equals(qname)){ - return StringUtils.leftPad(createStringResource("ObjectTypes.all").getString(), 1); - } else { - return super.getDisplayValue(qname); - } - } - - @Override - public QName getObject(String id, IModel> choices) { - QName qname = super.getObject(id, choices); - if (qname == null){ - return getObjectTypesListParentType(); - } - return qname; - } - - }, - "abstractRoleMemberPanel.type", "abstractRoleMemberPanel.type.tooltip", false); - form.add(typeSelect); - - RelationDropDownChoicePanel relationSelector = new RelationDropDownChoicePanel(ID_SEARCH_BY_RELATION, - getMemberPanelStorage() != null ? getMemberPanelStorage().getRelation() : getSupportedRelations().getDefaultRelation(), - getSupportedRelations().getAvailableRelationList(), true){ - private static final long serialVersionUID = 1L; - - @Override - protected void onValueChanged(AjaxRequestTarget target){ - refreshAll(target); - } - - @Override - protected String getNullValidDisplayValue(){ - return getString("RelationTypes.ANY"); - } - }; - form.add(relationSelector); - - ChooseTypePanel tenant = createParameterPanel(ID_TENANT, true); - form.add(tenant); - tenant.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); - - ChooseTypePanel project = createParameterPanel(ID_PROJECT, false); - form.add(project); - project.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); - - CheckFormGroup includeIndirectMembers = new CheckFormGroup(ID_INDIRECT_MEMBERS, - Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getIndirect() : false), - createStringResource("abstractRoleMemberPanel.indirectMembers"), "abstractRoleMemberPanel.indirectMembers.tooltip", false, "col-md-4", "col-md-2"); - includeIndirectMembers.getCheck().add(new AjaxFormComponentUpdatingBehavior("change") { - - private static final long serialVersionUID = 1L; - - protected void onUpdate(AjaxRequestTarget target) { - refreshAll(target); - }; - - }); - - includeIndirectMembers.getCheck().add(new EnableBehaviour(() -> - getSearchScopeValue().equals(SearchBoxScopeType.ONE_LEVEL) || !searchScrope.isVisible())); - includeIndirectMembers.setOutputMarkupId(true); - form.add(includeIndirectMembers); - - } - - protected List getSupportedObjectTypes(boolean includeAbstractTypes) { - return WebComponentUtil.createFocusTypeList(includeAbstractTypes); - } - - protected QName getObjectTypesListParentType(){ - return FocusType.COMPLEX_TYPE; - } - - protected List getNewMemberObjectTypes() { - return WebComponentUtil.createFocusTypeList(); - } - - private ChooseTypePanel createParameterPanel(String id, boolean isTenant) { - - ChooseTypePanel orgSelector = new ChooseTypePanel(id, Model.of(new ObjectViewDto())) { - - private static final long serialVersionUID = 1L; - - @Override - protected void executeCustomAction(AjaxRequestTarget target, OrgType object) { - refreshAll(target); - } - - @Override - protected void executeCustomRemoveAction(AjaxRequestTarget target) { - refreshAll(target); - } - - @Override - protected ObjectQuery getChooseQuery() { - S_FilterEntryOrEmpty q = getPrismContext().queryFor(OrgType.class); - if (isTenant) { - return q.item(OrgType.F_TENANT).eq(true).build(); - } else { - return q.not().item(OrgType.F_TENANT).eq(true).build(); - } - } - - @Override - protected boolean isSearchEnabled() { - return true; - } - - @Override - public Class getObjectTypeClass() { - return OrgType.class; - } - - @Override - protected AttributeAppender getInputStyleClass(){ - return AttributeAppender.append("class", "col-md-10"); - } - - }; - orgSelector.setOutputMarkupId(true); - orgSelector.setOutputMarkupPlaceholderTag(true); - return orgSelector; - - } - - private DropDownFormGroup createDropDown(String id, IModel defaultModel, final List values, - IChoiceRenderer renderer, String labelKey, String tooltipKey, boolean required) { - DropDownFormGroup listSelect = new DropDownFormGroup(id, defaultModel, Model.ofList(values), renderer, createStringResource(labelKey), - tooltipKey, false, "col-md-4", "col-md-8", required){ - private static final long serialVersionUID = 1L; - - @Override - protected String getNullValidDisplayValue(){ - return getString("ObjectTypes.all"); - } - }; - - listSelect.getInput().add(new OnChangeAjaxBehavior() { - private static final long serialVersionUID = 1L; - - @Override - protected void onUpdate(AjaxRequestTarget target) { - refreshAll(target); - } - }); - listSelect.setOutputMarkupId(true); - return listSelect; - } - - protected void refreshAll(AjaxRequestTarget target) { - updateMembersPanelSessionStorage(); - - DropDownFormGroup typeChoice = (DropDownFormGroup) get(createComponentPath(ID_FORM, ID_OBJECT_TYPE)); - QName type = getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : typeChoice.getModelObject(); - getMemberTable().clearCache(); - getMemberTable().refreshTable(WebComponentUtil.qnameToClass(getPrismContext(), type, FocusType.class), target); - target.add(this); - } - - - private MainObjectListPanel getMemberTable() { - return (MainObjectListPanel) get(createComponentPath(ID_FORM, ID_CONTAINER_MEMBER, ID_MEMBER_TABLE)); - } - - protected QueryScope getQueryScope(boolean isRecompute) { - if (CollectionUtils.isNotEmpty(MemberOperationsHelper.getFocusOidToRecompute(getMemberTable().getSelectedObjects()))) { - return QueryScope.SELECTED; - } - - if (getIndirectmembersPanel().getValue()) { - return QueryScope.ALL; - } - - return QueryScope.ALL_DIRECT; - } - - private CheckFormGroup getIndirectmembersPanel() { - return (CheckFormGroup) get(createComponentPath(ID_FORM, ID_INDIRECT_MEMBERS)); - } - - protected void recomputeMembersPerformed(AjaxRequestTarget target) { - - StringResourceModel confirmModel = getMemberTable().getSelectedObjectsCount() > 0 ? - createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") - : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); - - ConfigureTaskConfirmationPanel dialog = new ConfigureTaskConfirmationPanel(((PageBase)getPage()).getMainPopupBodyId(), - confirmModel) { - - private static final long serialVersionUID = 1L; - - @Override - protected PrismObject getTask(AjaxRequestTarget target) { - Task task = MemberOperationsHelper.createRecomputeMembersTask(getPageBase(), getQueryScope(true), - getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); - return task.getClonedTaskObject(); - } - - @Override - public StringResourceModel getTitle() { - return createStringResource("pageUsers.message.confirmActionPopupTitle"); - } - - @Override - public void yesPerformed(AjaxRequestTarget target) { - MemberOperationsHelper.recomputeMembersPerformed(getPageBase(), getQueryScope(true), - getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); - } - }; - ((PageBase)getPage()).showMainPopup(dialog, target); - } - - protected ObjectQuery createContentQuery() { - CheckFormGroup isIndirect = getIndirectmembersPanel(); - List relations = QNameUtil.match(getSelectedRelation(), PrismConstants.Q_ANY) ? getSupportedRelations().getAvailableRelationList() : Arrays.asList(getSelectedRelation()); - return createMemberQuery(isIndirect != null ? isIndirect.getValue() : false, relations); - - } - - protected QName getSelectedRelation(){ - MemberPanelStorage storage = getMemberPanelStorage(); - if (storage != null){ - return storage.getRelation(); - } - RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); - return relationDropDown.getRelationValue(); - } - - private SearchBoxScopeType getSearchScopeValue(){ - if (getMemberPanelStorage() != null){ - return getMemberPanelStorage().getOrgSearchScope(); - } - DropDownFormGroup searchScopeComponent = (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); - return searchScopeComponent.getModelObject(); - } - - protected ObjectTypes getSearchType() { - DropDownFormGroup searchByTypeChoice = (DropDownFormGroup) get( - createComponentPath(ID_FORM, ID_OBJECT_TYPE)); - QName typeName = searchByTypeChoice.getModelObject(); - return ObjectTypes.getObjectTypeFromTypeQName(typeName); - } - - protected ObjectQuery createMemberQuery(boolean indirect, Collection relations) { - if (indirect) { - return createAllMemberQuery(relations); - } - - return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); - } - - - protected ObjectQuery createAllMemberQuery(Collection relations) { - return getPrismContext().queryFor(FocusType.class) - .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(MemberOperationsHelper.createReferenceValuesList(getModelObject(), relations)) - .build(); - } - - - protected ObjectReferenceType createReference() { - ObjectReferenceType ref = ObjectTypeUtil.createObjectRef(getModelObject(), getPageBase().getPrismContext()); - return ref; - } - - protected void detailsPerformed(AjaxRequestTarget target, ObjectType object) { - if (WebComponentUtil.hasDetailsPage(object.getClass())) { - WebComponentUtil.dispatchToObjectDetailsPage(object.getClass(), object.getOid(), this, true); - } else { - error("Could not find proper response page"); - throw new RestartResponseException(getPageBase()); - } - } - - protected List, String>> createMembersColumns() { - List, String>> columns = new ArrayList<>(); - - IColumn, String> column = new AbstractExportableColumn, String>( - createStringResource("TreeTablePanel.fullName.displayName")) { - private static final long serialVersionUID = 1L; - - @Override - public void populateItem(Item>> cellItem, - String componentId, IModel> rowModel) { - SelectableBean bean = rowModel.getObject(); - ObjectType object = bean.getValue(); - cellItem.add(new Label(componentId, - getMemberObjectDisplayName(object, true))); - } - - @Override - public IModel getDataModel(IModel> rowModel) { - return Model.of(getMemberObjectDisplayName(rowModel.getObject().getValue(), true)); - } - - }; - columns.add(column); - - column = new AbstractExportableColumn, String>( - createStringResource("TreeTablePanel.identifier.description")) { - private static final long serialVersionUID = 1L; - - @Override - public void populateItem(Item>> cellItem, - String componentId, IModel> rowModel) { - SelectableBean bean = rowModel.getObject(); - ObjectType object = bean.getValue(); - cellItem.add(new Label(componentId, getMemberObjectIdentifier(object))); - } - - @Override - public IModel getDataModel(IModel> rowModel) { - return Model.of(getMemberObjectIdentifier(rowModel.getObject().getValue())); - } - - }; - columns.add(column); -// if (isRelationColumnVisible()){ - columns.add(createRelationColumn()); -// } - return columns; - } - - protected IColumn, String> createRelationColumn() { - return new AbstractExportableColumn, String>( - createStringResource("roleMemberPanel.relation")) { - private static final long serialVersionUID = 1L; - - @Override - public void populateItem(Item>> cellItem, - String componentId, IModel> rowModel) { - cellItem.add(new Label(componentId, - getRelationValue(rowModel.getObject().getValue()))); - } - - @Override - public IModel getDataModel(IModel> rowModel) { - return Model.of(getRelationValue(rowModel.getObject().getValue())); - } - - }; - } - - protected boolean isRelationColumnVisible(){ - return false; - } - - - private String getMemberObjectDisplayName(ObjectType object){ - return getMemberObjectDisplayName(object, false); - } - - private String getMemberObjectDisplayName(ObjectType object, boolean translate){ - if (object == null){ - return ""; - } - if (object instanceof UserType) { - return WebComponentUtil.getTranslatedPolyString(((UserType) object).getFullName()); - } else if (object instanceof AbstractRoleType) { - return WebComponentUtil.getTranslatedPolyString(((AbstractRoleType) object).getDisplayName()); - } else { - return ""; - } - } - - private String getMemberObjectIdentifier(ObjectType object){ - if (object == null){ - return ""; - } - if (object instanceof UserType) { - return ((UserType) object).getEmailAddress(); - } else if (object instanceof AbstractRoleType) { - return ((AbstractRoleType) object).getIdentifier(); - } else { - return object.getDescription(); - } - } - - private Collection> getSearchOptions(){ - return SelectorOptions - .createCollection(GetOperationOptions.createDistinct()); - } - - protected Class getDefaultObjectType(){ - return (Class) FocusType.class; - } - - protected Form getFormComponent(){ - return (Form) get(ID_FORM); - } - - - private String getRelationValue(ObjectType focusObject){ - String relation = ""; - if (FocusType.class.isAssignableFrom(focusObject.getClass())) { - // Do NOT take relation from an assignment. Use roleMembershipRef instead. Reasons: - // 1. Authorizations (MID-4893). User may be authorized just for roleMemberhsipRef and not for assignment - // Authorization for roleMembershipRef is enough to display member panel. - // 2. There may be assignments that are not valid. We do not want to display relation for those. - for (ObjectReferenceType roleMembershipRef : getMembershipReferenceList((FocusType) focusObject)) { - relation = buildRelation(roleMembershipRef, relation); - } - - } - return relation; - - } - - protected List getMembershipReferenceList(FocusType focusObject){ - return focusObject.getRoleMembershipRef(); - } - - private String buildRelation(ObjectReferenceType roleMembershipRef, String relation) { - if (roleMembershipRef.getOid().equals(getModelObject().getOid())) { - QName assignmentRelation = roleMembershipRef.getRelation(); - if (getSupportedRelations().getAvailableRelationList().stream().anyMatch(r -> QNameUtil.match(r, assignmentRelation))) { - if (!StringUtils.isBlank(relation)) { - relation += ","; - } - relation += assignmentRelation.getLocalPart(); - } - } - return relation; - } - - protected void updateMembersPanelSessionStorage(){ - MemberPanelStorage storage = getMemberPanelStorage(); - if (storage != null){ - storage.setType(getSearchType()); - - RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); - storage.setRelation(relationDropDown.getRelationValue()); - - CheckFormGroup indirectPanel = getIndirectmembersPanel(); - if (indirectPanel != null){ - storage.setIndirect(indirectPanel.getValue()); - } - - DropDownFormGroup searchScopeComponent = - (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); - storage.setOrgSearchScope(searchScopeComponent.getModelObject()); - } - } - - protected MemberPanelStorage getMemberPanelStorage(){ - return null; - } -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin.roles; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import com.evolveum.midpoint.gui.impl.component.icon.CompositedIcon; +import com.evolveum.midpoint.gui.impl.component.icon.CompositedIconBuilder; +import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; +import com.evolveum.midpoint.model.api.AssignmentObjectRelation; +import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.polystring.PolyString; +import com.evolveum.midpoint.prism.query.QueryFactory; +import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty; +import com.evolveum.midpoint.schema.constants.RelationTypes; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.exception.ConfigurationException; +import com.evolveum.midpoint.web.component.MultiFunctinalButtonDto; +import com.evolveum.midpoint.web.component.MultifunctionalButton; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.component.data.column.ColumnUtils; +import com.evolveum.midpoint.web.component.dialog.ConfigureTaskConfirmationPanel; +import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; +import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; +import com.evolveum.midpoint.web.component.util.SelectableBean; +import com.evolveum.midpoint.web.page.admin.configuration.component.HeaderMenuAction; +import com.evolveum.midpoint.web.session.MemberPanelStorage; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.Component; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; + +import com.evolveum.midpoint.gui.api.GuiStyleConstants; +import com.evolveum.midpoint.gui.api.component.BasePanel; +import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.prism.PrismConstants; +import com.evolveum.midpoint.prism.query.ObjectFilter; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.ObjectTypes; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.dialog.ChooseFocusTypeAndRelationDialogPanel; +import com.evolveum.midpoint.web.component.form.CheckFormGroup; +import com.evolveum.midpoint.web.component.form.DropDownFormGroup; +import com.evolveum.midpoint.web.component.input.QNameObjectTypeChoiceRenderer; +import com.evolveum.midpoint.web.component.input.RelationDropDownChoicePanel; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; +import com.evolveum.midpoint.web.component.search.Search; +import com.evolveum.midpoint.web.component.search.SearchFactory; +import com.evolveum.midpoint.web.component.util.EnableBehaviour; +import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; +import com.evolveum.midpoint.web.component.util.VisibleBehaviour; +import com.evolveum.midpoint.web.page.admin.configuration.component.ChooseTypePanel; +import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto; +import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; +import com.evolveum.midpoint.web.session.UserProfileStorage.TableId; + +import org.apache.wicket.model.StringResourceModel; + +import static com.evolveum.midpoint.web.component.data.column.ColumnUtils.createStringResource; + +public abstract class AbstractRoleMemberPanel extends BasePanel { + + private static final long serialVersionUID = 1L; + + protected enum QueryScope { + SELECTED, ALL, ALL_DIRECT + } + + protected enum MemberOperation { + ADD, REMOVE, RECOMPUTE + } + + private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMemberPanel.class); + private static final String DOT_CLASS = AbstractRoleMemberPanel.class.getName() + "."; + protected static final String OPERATION_LOAD_MEMBER_RELATIONS = DOT_CLASS + "loadMemberRelationsList"; + protected static final String OPERATION_LOAD_ARCHETYPE_OBJECT = DOT_CLASS + "loadArchetypeObject"; + + protected static final String ID_FORM = "form"; + + protected static final String ID_CONTAINER_MEMBER = "memberContainer"; + protected static final String ID_CHILD_TABLE = "childUnitTable"; + protected static final String ID_MEMBER_TABLE = "memberTable"; + + private static final String ID_OBJECT_TYPE = "type"; + private static final String ID_TENANT = "tenant"; + private static final String ID_PROJECT = "project"; + private static final String ID_INDIRECT_MEMBERS = "indirectMembers"; + + protected static final String ID_SEARCH_SCOPE = "searchScope"; + protected SearchBoxScopeType scopeDefaultValue = null; + protected QName objectTypeDefaultValue = null; + + protected static final String ID_SEARCH_BY_RELATION = "searchByRelation"; + + private static Map> authorizations = new HashMap<>(); + private static Map tablesId = new HashMap<>(); + + static { + tablesId.put(RoleType.COMPLEX_TYPE, TableId.ROLE_MEMEBER_PANEL); + tablesId.put(ServiceType.COMPLEX_TYPE, TableId.SERVICE_MEMEBER_PANEL); + tablesId.put(OrgType.COMPLEX_TYPE, TableId.ORG_MEMEBER_PANEL); + tablesId.put(ArchetypeType.COMPLEX_TYPE, TableId.ARCHETYPE_MEMEBER_PANEL); + } + + static { + authorizations.put(RoleType.COMPLEX_TYPE, GuiAuthorizationConstants.ROLE_MEMBERS_AUTHORIZATIONS); + authorizations.put(ServiceType.COMPLEX_TYPE, GuiAuthorizationConstants.SERVICE_MEMBERS_AUTHORIZATIONS); + authorizations.put(OrgType.COMPLEX_TYPE, GuiAuthorizationConstants.ORG_MEMBERS_AUTHORIZATIONS); + authorizations.put(ArchetypeType.COMPLEX_TYPE, GuiAuthorizationConstants.ARCHETYPE_MEMBERS_AUTHORIZATIONS); + } + + public AbstractRoleMemberPanel(String id, IModel model) { + super(id, model); + } + + @Override + protected void onInitialize(){ + super.onInitialize(); + initLayout(); + } + + protected void initLayout() { + Form form = new com.evolveum.midpoint.web.component.form.Form(ID_FORM); + form.setOutputMarkupId(true); + add(form); + initDefaultSearchParameters(); + initSearch(form); + initMemberTable(form); + setOutputMarkupId(true); + + } + + private void initDefaultSearchParameters(){ + GuiObjectListPanelConfigurationType additionalPanel = getAdditionalPanelConfig(); + if (additionalPanel != null && additionalPanel.getSearchBoxConfiguration() != null) { + scopeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultScope(); + objectTypeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultObjectType(); + } + if (scopeDefaultValue == null){ + scopeDefaultValue = SearchBoxScopeType.ONE_LEVEL; + } + if (objectTypeDefaultValue == null){ + objectTypeDefaultValue = WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType()); + } + if (getMemberPanelStorage() != null){ + if (getMemberPanelStorage().getOrgSearchScope() == null){ + getMemberPanelStorage().setOrgSearchScope(scopeDefaultValue); + } + if (getMemberPanelStorage().getType() == null){ + getMemberPanelStorage().setType(ObjectTypes.getObjectType(objectTypeDefaultValue.getLocalPart())); + } + } + } + + protected Form getForm() { + return (Form) get(ID_FORM); + } + + private void initMemberTable(Form form) { + WebMarkupContainer memberContainer = new WebMarkupContainer(ID_CONTAINER_MEMBER); + memberContainer.setOutputMarkupId(true); + memberContainer.setOutputMarkupPlaceholderTag(true); + form.add(memberContainer); + + PageBase pageBase = getPageBase(); + Class type = getMemberPanelStorage() != null && getMemberPanelStorage().getType() != null ? + getMemberPanelStorage().getType().getClassDefinition() : ObjectType.class; + //TODO QName defines a relation value which will be used for new member creation + MainObjectListPanel childrenListPanel = new MainObjectListPanel( + ID_MEMBER_TABLE, type, getTableId(getComplexTypeQName()), getSearchOptions()) { + + private static final long serialVersionUID = 1L; + + @Override + protected void objectDetailsPerformed(AjaxRequestTarget target, ObjectType object) { + detailsPerformed(target, object); + } + + @Override + protected boolean isObjectDetailsEnabled(IModel> rowModel) { + if (rowModel == null || rowModel.getObject() == null + || rowModel.getObject().getValue() == null) { + return false; + } + Class objectClass = rowModel.getObject().getValue().getClass(); + return WebComponentUtil.hasDetailsPage(objectClass); + } + + @Override + protected DisplayType getNewObjectButtonSpecialDisplayType(){ + return getCreateMemberButtonDisplayType(); + } + + @Override + protected DisplayType getNewObjectButtonStandardDisplayType(){ + return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", + createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); + } + + @Override + protected List loadButtonDescriptions() { + return createAdditionalButtonsDescription(); + } + + @Override + protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { + AbstractRoleMemberPanel.this.createFocusMemberPerformed(target, relation); + } + + @Override + protected List createToolbarButtonsList(String buttonId){ + List buttonsList = super.createToolbarButtonsList(buttonId); + MultifunctionalButton assignButton = createAssignButton(buttonId); + buttonsList.add(1, assignButton); + return buttonsList; + } + + @Override + protected IColumn, String> createIconColumn(){ + return (IColumn) ColumnUtils.createIconColumn(pageBase); + } + + @Override + protected List, String>> createColumns() { + return createMembersColumns(); + } + + @Override + protected List createInlineMenu() { + return createRowActions(); + } + + @Override + protected Search createSearch() { + return getMemberPanelStorage() != null && getMemberPanelStorage().getSearch() != null ? + getMemberPanelStorage().getSearch() : SearchFactory.createSearch(getDefaultObjectType(), pageBase); + } + + @Override + protected ObjectQuery createContentQuery() { + ObjectQuery q = super.createContentQuery(); + + ObjectQuery members = AbstractRoleMemberPanel.this.createContentQuery(); + + List filters = new ArrayList<>(); + + if (q != null && q.getFilter() != null) { + filters.add(q.getFilter()); + } + + if (members != null && members.getFilter() != null) { + filters.add(members.getFilter()); + } + + QueryFactory queryFactory = pageBase.getPrismContext().queryFactory(); + if (filters.size() == 1) { + return queryFactory.createQuery(filters.iterator().next()); + } else { + return queryFactory.createQuery(queryFactory.createAnd(filters)); + } + } + + @Override + protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ + return AbstractRoleMemberPanel.this.getAdditionalPanelConfig(); + } + + @Override + protected boolean isAdditionalPanel(){ + return true; + } + + protected boolean isTypeChanged(Class newTypeClass){ + return true; + } + }; + childrenListPanel.setOutputMarkupId(true); + memberContainer.add(childrenListPanel); + } + + private List createAdditionalButtonsDescription() { + List multiFunctinalButtonDtos = new ArrayList<>(); + List loadedRelations = loadMemberRelationsList(); + if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(loadedRelations)) { + List relations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadedRelations); + relations.forEach(relation -> { + MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); + DisplayType additionalButtonDisplayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(getPageBase(), relation, + "abstractRoleMemberPanel.menu.createMember"); + buttonDto.setAdditionalButtonDisplayType(additionalButtonDisplayType); + buttonDto.setCompositedIcon(createCompositedIcon(relation, additionalButtonDisplayType)); + buttonDto.setAssignmentObjectRelation(relation); + multiFunctinalButtonDtos.add(buttonDto); + }); + } + return multiFunctinalButtonDtos; + } + + private CompositedIcon createCompositedIcon(AssignmentObjectRelation relation, DisplayType additionalButtonDisplayType) { + CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(getPageBase(), relation, + additionalButtonDisplayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green")); + if (builder == null) { + return null; + } + return builder.build(); + } + + private MultifunctionalButton createAssignButton(String buttonId) { + MultifunctionalButton assignButton = new MultifunctionalButton(buttonId, createAssignmentAdditionalButtons()) { + private static final long serialVersionUID = 1L; + + + @Override + protected void buttonClickPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { + List relations = relation != null && !CollectionUtils.isEmpty(relation.getRelations()) ? + Arrays.asList(relation.getRelations().get(0)) : getSupportedRelations().getAvailableRelationList(); + AvailableRelationDto avariableRelations = new AvailableRelationDto(relations, getSupportedRelations().getDefaultRelation()); + List objectTypes = relation != null && !CollectionUtils.isEmpty(relation.getObjectTypes()) ? + relation.getObjectTypes() : null; + List archetypeRefList = relation != null && !CollectionUtils.isEmpty(relation.getArchetypeRefs()) ? + relation.getArchetypeRefs() : null; + assignMembers(target, avariableRelations, objectTypes, archetypeRefList, relation == null); + } + + @Override + protected DisplayType getMainButtonDisplayType(){ + return getAssignMemberButtonDisplayType(); + } + + @Override + protected DisplayType getDefaultObjectButtonDisplayType(){ + return getAssignMemberButtonDisplayType(); + } + + }; + assignButton.add(AttributeAppender.append("class", "btn-margin-right")); + + + return assignButton; + } + + private List createAssignmentAdditionalButtons() { + List additionalAssignmentButtons = new ArrayList<>(); + List assignmentObjectRelations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadMemberRelationsList()); + if (assignmentObjectRelations == null) { + return additionalAssignmentButtons; + } + assignmentObjectRelations.forEach(relation -> { + MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); + buttonDto.setAssignmentObjectRelation(relation); + + DisplayType additionalDispayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(AbstractRoleMemberPanel.this.getPageBase(), relation, + "abstractRoleMemberPanel.menu.assignMember"); + //TODO null additinalDisplayType + CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(AbstractRoleMemberPanel.this.getPageBase(), relation, + additionalDispayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green")); + CompositedIcon icon = builder.build(); + buttonDto.setAdditionalButtonDisplayType(additionalDispayType); + buttonDto.setCompositedIcon(icon); + additionalAssignmentButtons.add(buttonDto); + }); + + return additionalAssignmentButtons; + + } + + protected TableId getTableId(QName complextType) { + return tablesId.get(complextType); + } + + protected Map getAuthorizations(QName complexType) { + return authorizations.get(complexType); + } + + protected QName getComplexTypeQName() { + return getModelObject().asPrismObject().getComplexTypeDefinition().getTypeName(); + } + + private DisplayType getCreateMemberButtonDisplayType(){ + return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", + AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); + } + + private DisplayType getAssignMemberButtonDisplayType(){ + return WebComponentUtil.createDisplayType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green", + AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.assignMember", "", "").getString()); + } + + protected List createRowActions() { + List menu = new ArrayList<>(); + createAssignMemberRowAction(menu); + + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_UNASSIGN)) { + menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.unassign")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + unassignMembersPerformed(target); + } + }; + + } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_UNASSIGN; + } + }); + } + + createRecomputeMemberRowAction(menu); + + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_CREATE)) { + menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.create")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + createFocusMemberPerformed(target); + } + }; + } + }); + } + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_DELETE)) { + menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.delete")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + deleteMembersPerformed(target); + } + }; + } + + }); + } + return menu; + } + + protected void createAssignMemberRowAction(List menu) { + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_ASSIGN)) { + menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.assign")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + MemberOperationsHelper.assignMembers(getPageBase(), AbstractRoleMemberPanel.this.getModelObject(), target, getSupportedRelations(), null); + } + }; + } + }); + } + } + + protected void createRecomputeMemberRowAction(List menu) { + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_RECOMPUTE)) { + menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.recompute")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + recomputeMembersPerformed(target); + } + }; + } + +// @Override +// public IModel getConfirmationMessageModel() { +// return getMemberTable().getSelectedObjectsCount() > 0 ? +// createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") +// : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); +// } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_RECONCILE_MENU_ITEM; + } + + }); + } + } + + + + protected abstract AvailableRelationDto getSupportedRelations(); + + protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ + return null; + } + + private boolean isAuthorized(String action) { + Map memeberAuthz = getAuthorizations(getComplexTypeQName()); + return WebComponentUtil.isAuthorized(memeberAuthz.get(action)); + } + + + + private List loadMemberRelationsList(){ + List assignmentTargetRelations = new ArrayList<>(); + AssignmentCandidatesSpecification spec = loadCandidateSpecification(); + assignmentTargetRelations = spec != null ? spec.getAssignmentObjectRelations() : new ArrayList<>(); + return assignmentTargetRelations; + } + + private AssignmentCandidatesSpecification loadCandidateSpecification(){ + OperationResult result = new OperationResult(OPERATION_LOAD_MEMBER_RELATIONS); + PrismObject obj = getModelObject().asPrismObject(); + AssignmentCandidatesSpecification spec = null; + try { + spec = getPageBase().getModelInteractionService() + .determineAssignmentHolderSpecification(obj, result); + } catch (SchemaException | ConfigurationException ex){ + result.recordPartialError(ex.getLocalizedMessage()); + LOGGER.error("Couldn't load member relations list for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); + } + return spec; + } + + protected void assignMembers(AjaxRequestTarget target, AvailableRelationDto availableRelationList, + List objectTypes, List archetypeRefList, boolean isOrgTreePanelVisible) { + MemberOperationsHelper.assignMembers(getPageBase(), getModelObject(), target, availableRelationList, + objectTypes, archetypeRefList, isOrgTreePanelVisible); + } + + private void unassignMembersPerformed(AjaxRequestTarget target) { + QueryScope scope = getQueryScope(false); + + ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), + createStringResource("abstractRoleMemberPanel.unassignAllMembersConfirmationLabel")) { + private static final long serialVersionUID = 1L; + + @Override + protected List getSupportedObjectTypes() { + return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); + } + + @Override + protected List getSupportedRelations() { + return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); + } + + @Override + protected boolean isFocusTypeSelectorVisible() { + return !QueryScope.SELECTED.equals(scope); + } + + + protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { + unassignMembersPerformed(type, scope, relations, target); + } + + @Override + protected QName getDefaultObjectType() { + return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), + AbstractRoleMemberPanel.this.getDefaultObjectType()); + } + }; + + getPageBase().showMainPopup(chooseTypePopupContent, target); + } + + private void deleteMembersPerformed(AjaxRequestTarget target) { + QueryScope scope = getQueryScope(false); + ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), + createStringResource("abstractRoleMemberPanel.deleteAllMembersConfirmationLabel")) { + private static final long serialVersionUID = 1L; + + @Override + protected List getSupportedObjectTypes() { + return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); + } + + @Override + protected List getSupportedRelations() { + return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); + } + + protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { + deleteMembersPerformed(type, scope, relations, target); + + } + + @Override + protected boolean isFocusTypeSelectorVisible() { + return !QueryScope.SELECTED.equals(scope); + } + + @Override + protected QName getDefaultObjectType() { + return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), + AbstractRoleMemberPanel.this.getDefaultObjectType()); + } + + }; + + getPageBase().showMainPopup(chooseTypePopupContent, target); + + } + + protected void createFocusMemberPerformed(AjaxRequestTarget target) { + createFocusMemberPerformed(target, null); + } + + protected void createFocusMemberPerformed(AjaxRequestTarget target, AssignmentObjectRelation relationSpec) { + if (relationSpec != null){ + try { + List newReferences = new ArrayList<>(); + if (CollectionUtils.isEmpty(relationSpec.getRelations())){ + relationSpec.setRelations(Arrays.asList(RelationTypes.MEMBER.getRelation())); + } + ObjectReferenceType memberRef = ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relationSpec.getRelations().get(0)); + newReferences.add(memberRef); + if (CollectionUtils.isNotEmpty(relationSpec.getArchetypeRefs())) { + newReferences.add(relationSpec.getArchetypeRefs().get(0)); + } + QName newMemberType = CollectionUtils.isNotEmpty(relationSpec.getObjectTypes()) ? relationSpec.getObjectTypes().get(0) : + getSupportedObjectTypes(false).get(0); + WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), newMemberType, newReferences); + } catch (SchemaException e) { + throw new SystemException(e.getMessage(), e); + } + } else { + ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel( + getPageBase().getMainPopupBodyId()) { + private static final long serialVersionUID = 1L; + + @Override + protected List getSupportedObjectTypes() { + return AbstractRoleMemberPanel.this.getNewMemberObjectTypes(); + } + + @Override + protected List getSupportedRelations() { + return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); + } + + protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { + if (type == null) { + getSession().warn("No type was selected. Cannot create member"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + if (relations == null || relations.isEmpty()) { + getSession().warn("No relation was selected. Cannot create member"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + AbstractRoleMemberPanel.this.getPageBase().hideMainPopup(target); + try { + List newReferences = new ArrayList<>(); + for (QName relation : relations) { + newReferences.add(ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relation)); + } + WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), type, newReferences); + } catch (SchemaException e) { + throw new SystemException(e.getMessage(), e); + } + + } + + @Override + protected QName getDefaultObjectType() { + if (relationSpec != null && CollectionUtils.isNotEmpty(relationSpec.getObjectTypes())) { + return relationSpec.getObjectTypes().get(0); + } + return super.getDefaultObjectType(); + } + + @Override + protected boolean isFocusTypeSelectorVisible() { + return relationSpec == null; + } + }; + + getPageBase().showMainPopup(chooseTypePopupContent, target); + } + } + + protected void deleteMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { + if (relations == null || relations.isEmpty()) { + getSession().warn("No relation was selected. Cannot perform delete members"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + MemberOperationsHelper.deleteMembersPerformed(getPageBase(), scope, getActionQuery(scope, relations), type, target); + } + + protected void unassignMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { + if (relations == null || relations.isEmpty()) { + getSession().warn("No relation was selected. Cannot perform unassign members"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + MemberOperationsHelper.unassignMembersPerformed(getPageBase(), getModelObject(), scope, getActionQuery(scope, relations), relations, type, target); + } + + private ObjectViewDto getParameter(String panelId) { + ChooseTypePanel tenantChoice = (ChooseTypePanel) get(createComponentPath(ID_FORM, panelId)); + return tenantChoice.getModelObject(); + } + + protected ObjectQuery getActionQuery(QueryScope scope, Collection relations) { + switch (scope) { + case ALL: + return createAllMemberQuery(relations); + case ALL_DIRECT: + return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); + case SELECTED: + return MemberOperationsHelper.createSelectedObjectsQuery(getMemberTable().getSelectedObjects(), getPrismContext()); + } + + return null; + } + + protected void initSearch(Form form) { + + List scopeValues = Arrays.asList(SearchBoxScopeType.values()); + DropDownFormGroup searchScrope = createDropDown(ID_SEARCH_SCOPE, + Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getOrgSearchScope() : scopeDefaultValue), + scopeValues, + WebComponentUtil.getEnumChoiceRenderer(AbstractRoleMemberPanel.this), + "abstractRoleMemberPanel.searchScope", "abstractRoleMemberPanel.searchScope.tooltip", true); + searchScrope.add(new VisibleBehaviour(() -> getModelObject() instanceof OrgType)); + form.add(searchScrope); + + List supportedTypes = getSupportedObjectTypes(false); + DropDownFormGroup typeSelect = createDropDown(ID_OBJECT_TYPE, + Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType())), + supportedTypes, new QNameObjectTypeChoiceRenderer(){ + private static final long serialVersionUID = 1L; + + @Override + public Object getDisplayValue(QName qname) { + if (qname == null || getObjectTypesListParentType().equals(qname)){ + return StringUtils.leftPad(createStringResource("ObjectTypes.all").getString(), 1); + } else { + return super.getDisplayValue(qname); + } + } + + @Override + public QName getObject(String id, IModel> choices) { + QName qname = super.getObject(id, choices); + if (qname == null){ + return getObjectTypesListParentType(); + } + return qname; + } + + }, + "abstractRoleMemberPanel.type", "abstractRoleMemberPanel.type.tooltip", false); + form.add(typeSelect); + + RelationDropDownChoicePanel relationSelector = new RelationDropDownChoicePanel(ID_SEARCH_BY_RELATION, + getMemberPanelStorage() != null ? getMemberPanelStorage().getRelation() : getSupportedRelations().getDefaultRelation(), + getSupportedRelations().getAvailableRelationList(), true){ + private static final long serialVersionUID = 1L; + + @Override + protected void onValueChanged(AjaxRequestTarget target){ + refreshAll(target); + } + + @Override + protected String getNullValidDisplayValue(){ + return getString("RelationTypes.ANY"); + } + }; + form.add(relationSelector); + + ChooseTypePanel tenant = createParameterPanel(ID_TENANT, true); + form.add(tenant); + tenant.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); + + ChooseTypePanel project = createParameterPanel(ID_PROJECT, false); + form.add(project); + project.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); + + CheckFormGroup includeIndirectMembers = new CheckFormGroup(ID_INDIRECT_MEMBERS, + Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getIndirect() : false), + createStringResource("abstractRoleMemberPanel.indirectMembers"), "abstractRoleMemberPanel.indirectMembers.tooltip", false, "col-md-4", "col-md-2"); + includeIndirectMembers.getCheck().add(new AjaxFormComponentUpdatingBehavior("change") { + + private static final long serialVersionUID = 1L; + + protected void onUpdate(AjaxRequestTarget target) { + refreshAll(target); + } + + }); + + includeIndirectMembers.getCheck().add(new EnableBehaviour(() -> + getSearchScopeValue().equals(SearchBoxScopeType.ONE_LEVEL) || !searchScrope.isVisible())); + includeIndirectMembers.setOutputMarkupId(true); + form.add(includeIndirectMembers); + + } + + protected List getSupportedObjectTypes(boolean includeAbstractTypes) { + return WebComponentUtil.createFocusTypeList(includeAbstractTypes); + } + + protected QName getObjectTypesListParentType(){ + return FocusType.COMPLEX_TYPE; + } + + protected List getNewMemberObjectTypes() { + return WebComponentUtil.createFocusTypeList(); + } + + private ChooseTypePanel createParameterPanel(String id, boolean isTenant) { + + ChooseTypePanel orgSelector = new ChooseTypePanel(id, Model.of(new ObjectViewDto())) { + + private static final long serialVersionUID = 1L; + + @Override + protected void executeCustomAction(AjaxRequestTarget target, OrgType object) { + refreshAll(target); + } + + @Override + protected void executeCustomRemoveAction(AjaxRequestTarget target) { + refreshAll(target); + } + + @Override + protected ObjectQuery getChooseQuery() { + S_FilterEntryOrEmpty q = getPrismContext().queryFor(OrgType.class); + if (isTenant) { + return q.item(OrgType.F_TENANT).eq(true).build(); + } else { + return q.not().item(OrgType.F_TENANT).eq(true).build(); + } + } + + @Override + protected boolean isSearchEnabled() { + return true; + } + + @Override + public Class getObjectTypeClass() { + return OrgType.class; + } + + @Override + protected AttributeAppender getInputStyleClass(){ + return AttributeAppender.append("class", "col-md-10"); + } + + }; + orgSelector.setOutputMarkupId(true); + orgSelector.setOutputMarkupPlaceholderTag(true); + return orgSelector; + + } + + private DropDownFormGroup createDropDown(String id, IModel defaultModel, final List values, + IChoiceRenderer renderer, String labelKey, String tooltipKey, boolean required) { + DropDownFormGroup listSelect = new DropDownFormGroup(id, defaultModel, Model.ofList(values), renderer, createStringResource(labelKey), + tooltipKey, false, "col-md-4", "col-md-8", required){ + private static final long serialVersionUID = 1L; + + @Override + protected String getNullValidDisplayValue(){ + return getString("ObjectTypes.all"); + } + }; + + listSelect.getInput().add(new OnChangeAjaxBehavior() { + private static final long serialVersionUID = 1L; + + @Override + protected void onUpdate(AjaxRequestTarget target) { + refreshAll(target); + } + }); + listSelect.setOutputMarkupId(true); + return listSelect; + } + + protected void refreshAll(AjaxRequestTarget target) { + updateMembersPanelSessionStorage(); + + DropDownFormGroup typeChoice = (DropDownFormGroup) get(createComponentPath(ID_FORM, ID_OBJECT_TYPE)); + QName type = getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : typeChoice.getModelObject(); + getMemberTable().clearCache(); + getMemberTable().refreshTable(WebComponentUtil.qnameToClass(getPrismContext(), type, FocusType.class), target); + target.add(this); + } + + + private MainObjectListPanel getMemberTable() { + return (MainObjectListPanel) get(createComponentPath(ID_FORM, ID_CONTAINER_MEMBER, ID_MEMBER_TABLE)); + } + + protected QueryScope getQueryScope(boolean isRecompute) { + if (CollectionUtils.isNotEmpty(MemberOperationsHelper.getFocusOidToRecompute(getMemberTable().getSelectedObjects()))) { + return QueryScope.SELECTED; + } + + if (getIndirectmembersPanel().getValue()) { + return QueryScope.ALL; + } + + return QueryScope.ALL_DIRECT; + } + + private CheckFormGroup getIndirectmembersPanel() { + return (CheckFormGroup) get(createComponentPath(ID_FORM, ID_INDIRECT_MEMBERS)); + } + + protected void recomputeMembersPerformed(AjaxRequestTarget target) { + + StringResourceModel confirmModel = getMemberTable().getSelectedObjectsCount() > 0 ? + createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") + : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); + + ConfigureTaskConfirmationPanel dialog = new ConfigureTaskConfirmationPanel(((PageBase)getPage()).getMainPopupBodyId(), + confirmModel) { + + private static final long serialVersionUID = 1L; + + @Override + protected PrismObject getTask(AjaxRequestTarget target) { + Task task = MemberOperationsHelper.createRecomputeMembersTask(getPageBase(), getQueryScope(true), + getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); + if (task == null) { + return null; + } + PrismObject recomputeTask = task.getClonedTaskObject(); + TaskType recomputeTaskType = recomputeTask.asObjectable(); + recomputeTaskType.getAssignment().add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value(), ObjectTypes.ARCHETYPE, getPrismContext())); + return recomputeTask; + } + + @Override + public StringResourceModel getTitle() { + return createStringResource("pageUsers.message.confirmActionPopupTitle"); + } + + @Override + public void yesPerformed(AjaxRequestTarget target) { + MemberOperationsHelper.recomputeMembersPerformed(getPageBase(), getQueryScope(true), + getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); + } + }; + ((PageBase)getPage()).showMainPopup(dialog, target); + } + + protected ObjectQuery createContentQuery() { + CheckFormGroup isIndirect = getIndirectmembersPanel(); + List relations = QNameUtil.match(getSelectedRelation(), PrismConstants.Q_ANY) ? getSupportedRelations().getAvailableRelationList() : Arrays.asList(getSelectedRelation()); + return createMemberQuery(isIndirect != null ? isIndirect.getValue() : false, relations); + + } + + protected QName getSelectedRelation(){ + MemberPanelStorage storage = getMemberPanelStorage(); + if (storage != null){ + return storage.getRelation(); + } + RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); + return relationDropDown.getRelationValue(); + } + + private SearchBoxScopeType getSearchScopeValue(){ + if (getMemberPanelStorage() != null){ + return getMemberPanelStorage().getOrgSearchScope(); + } + DropDownFormGroup searchScopeComponent = (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); + return searchScopeComponent.getModelObject(); + } + + protected ObjectTypes getSearchType() { + DropDownFormGroup searchByTypeChoice = (DropDownFormGroup) get( + createComponentPath(ID_FORM, ID_OBJECT_TYPE)); + QName typeName = searchByTypeChoice.getModelObject(); + return ObjectTypes.getObjectTypeFromTypeQName(typeName); + } + + protected ObjectQuery createMemberQuery(boolean indirect, Collection relations) { + if (indirect) { + return createAllMemberQuery(relations); + } + + return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); + } + + + protected ObjectQuery createAllMemberQuery(Collection relations) { + return getPrismContext().queryFor(FocusType.class) + .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(MemberOperationsHelper.createReferenceValuesList(getModelObject(), relations)) + .build(); + } + + + protected ObjectReferenceType createReference() { + ObjectReferenceType ref = ObjectTypeUtil.createObjectRef(getModelObject(), getPageBase().getPrismContext()); + return ref; + } + + protected void detailsPerformed(AjaxRequestTarget target, ObjectType object) { + if (WebComponentUtil.hasDetailsPage(object.getClass())) { + WebComponentUtil.dispatchToObjectDetailsPage(object.getClass(), object.getOid(), this, true); + } else { + error("Could not find proper response page"); + throw new RestartResponseException(getPageBase()); + } + } + + protected List, String>> createMembersColumns() { + List, String>> columns = new ArrayList<>(); + + IColumn, String> column = new AbstractExportableColumn, String>( + createStringResource("TreeTablePanel.fullName.displayName")) { + private static final long serialVersionUID = 1L; + + @Override + public void populateItem(Item>> cellItem, + String componentId, IModel> rowModel) { + SelectableBean bean = rowModel.getObject(); + ObjectType object = bean.getValue(); + cellItem.add(new Label(componentId, + getMemberObjectDisplayName(object, true))); + } + + @Override + public IModel getDataModel(IModel> rowModel) { + return Model.of(getMemberObjectDisplayName(rowModel.getObject().getValue(), true)); + } + + }; + columns.add(column); + + column = new AbstractExportableColumn, String>( + createStringResource("TreeTablePanel.identifier.description")) { + private static final long serialVersionUID = 1L; + + @Override + public void populateItem(Item>> cellItem, + String componentId, IModel> rowModel) { + SelectableBean bean = rowModel.getObject(); + ObjectType object = bean.getValue(); + cellItem.add(new Label(componentId, getMemberObjectIdentifier(object))); + } + + @Override + public IModel getDataModel(IModel> rowModel) { + return Model.of(getMemberObjectIdentifier(rowModel.getObject().getValue())); + } + + }; + columns.add(column); +// if (isRelationColumnVisible()){ + columns.add(createRelationColumn()); +// } + return columns; + } + + protected IColumn, String> createRelationColumn() { + return new AbstractExportableColumn, String>( + createStringResource("roleMemberPanel.relation")) { + private static final long serialVersionUID = 1L; + + @Override + public void populateItem(Item>> cellItem, + String componentId, IModel> rowModel) { + cellItem.add(new Label(componentId, + getRelationValue(rowModel.getObject().getValue()))); + } + + @Override + public IModel getDataModel(IModel> rowModel) { + return Model.of(getRelationValue(rowModel.getObject().getValue())); + } + + }; + } + + protected boolean isRelationColumnVisible(){ + return false; + } + + + private String getMemberObjectDisplayName(ObjectType object){ + return getMemberObjectDisplayName(object, false); + } + + private String getMemberObjectDisplayName(ObjectType object, boolean translate){ + if (object == null){ + return ""; + } + if (object instanceof UserType) { + return WebComponentUtil.getTranslatedPolyString(((UserType) object).getFullName()); + } else if (object instanceof AbstractRoleType) { + return WebComponentUtil.getTranslatedPolyString(((AbstractRoleType) object).getDisplayName()); + } else { + return ""; + } + } + + private String getMemberObjectIdentifier(ObjectType object){ + if (object == null){ + return ""; + } + if (object instanceof UserType) { + return ((UserType) object).getEmailAddress(); + } else if (object instanceof AbstractRoleType) { + return ((AbstractRoleType) object).getIdentifier(); + } else { + return object.getDescription(); + } + } + + private Collection> getSearchOptions(){ + return SelectorOptions + .createCollection(GetOperationOptions.createDistinct()); + } + + protected Class getDefaultObjectType(){ + return (Class) FocusType.class; + } + + protected Form getFormComponent(){ + return (Form) get(ID_FORM); + } + + + private String getRelationValue(ObjectType focusObject){ + String relation = ""; + if (FocusType.class.isAssignableFrom(focusObject.getClass())) { + // Do NOT take relation from an assignment. Use roleMembershipRef instead. Reasons: + // 1. Authorizations (MID-4893). User may be authorized just for roleMemberhsipRef and not for assignment + // Authorization for roleMembershipRef is enough to display member panel. + // 2. There may be assignments that are not valid. We do not want to display relation for those. + for (ObjectReferenceType roleMembershipRef : getMembershipReferenceList((FocusType) focusObject)) { + relation = buildRelation(roleMembershipRef, relation); + } + + } + return relation; + + } + + protected List getMembershipReferenceList(FocusType focusObject){ + return focusObject.getRoleMembershipRef(); + } + + private String buildRelation(ObjectReferenceType roleMembershipRef, String relation) { + if (roleMembershipRef.getOid().equals(getModelObject().getOid())) { + QName assignmentRelation = roleMembershipRef.getRelation(); + if (getSupportedRelations().getAvailableRelationList().stream().anyMatch(r -> QNameUtil.match(r, assignmentRelation))) { + if (!StringUtils.isBlank(relation)) { + relation += ","; + } + relation += assignmentRelation.getLocalPart(); + } + } + return relation; + } + + protected void updateMembersPanelSessionStorage(){ + MemberPanelStorage storage = getMemberPanelStorage(); + if (storage != null){ + storage.setType(getSearchType()); + + RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); + storage.setRelation(relationDropDown.getRelationValue()); + + CheckFormGroup indirectPanel = getIndirectmembersPanel(); + if (indirectPanel != null){ + storage.setIndirect(indirectPanel.getValue()); + } + + DropDownFormGroup searchScopeComponent = + (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); + storage.setOrgSearchScope(searchScopeComponent.getModelObject()); + } + } + + protected MemberPanelStorage getMemberPanelStorage(){ + return null; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java index 89e618dfdbf..16f0e867599 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java @@ -18,6 +18,7 @@ import com.evolveum.midpoint.gui.api.component.ChooseArchetypeMemberPopup; import com.evolveum.midpoint.prism.query.QueryFactory; import com.evolveum.midpoint.prism.query.builder.S_FilterEntry; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -143,7 +144,22 @@ public static void recomputeMembersPerformed(PageBa public static Task createRecomputeMembersTask(PageBase pageBase, QueryScope scope, ObjectQuery query, AjaxRequestTarget target) { - return createRecomputeOrDeleteMembersTask(pageBase, scope, query, target, "recompute", RECOMPUTE_OPERATION); + Task operationalTask = pageBase.createSimpleTask(getTaskName(RECOMPUTE_OPERATION, scope)); + OperationResult parentResult = operationalTask.getResult(); + try { + operationalTask.getClonedTaskObject().asObjectable().getAssignment() + .add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value(), ObjectTypes.ARCHETYPE, pageBase.getPrismContext())); + operationalTask.getClonedTaskObject().asObjectable().getArchetypeRef() + .add(ObjectTypeUtil.createObjectRef(SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value(), ObjectTypes.ARCHETYPE)); + return WebComponentUtil.createRecomputeMemberOperationTask(operationalTask, AssignmentHolderType.COMPLEX_TYPE, query, + null, parentResult, pageBase); + } catch (SchemaException e) { + parentResult.recordFatalError(parentResult.getOperation(), e); + LoggingUtils.logUnexpectedException(LOGGER, + "Failed to execute operation " + parentResult.getOperation(), e); + target.add(pageBase.getFeedbackPanel()); + } + return null; } private static Task createRecomputeOrDeleteMembersTask(PageBase pageBase, QueryScope scope, @@ -398,6 +414,10 @@ protected static void executeMemberOperation(PageBase modelServiceLocator, Task try { Task executableTask = WebComponentUtil.createMemberOperationTask(operationalTask, type, memberQuery, script, option, parentResult, modelServiceLocator); if (executableTask != null) { + executableTask.getUpdatedTaskObject().asObjectable().getAssignment() + .add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_ITERATIVE_BULK_ACTION_TASK.value(), ObjectTypes.ARCHETYPE, modelServiceLocator.getPrismContext())); + executableTask.getUpdatedTaskObject().asObjectable().getArchetypeRef() + .add(ObjectTypeUtil.createObjectRef(SystemObjectsType.ARCHETYPE_ITERATIVE_BULK_ACTION_TASK.value(), ObjectTypes.ARCHETYPE)); WebComponentUtil.executeMemberOperation(executableTask, parentResult, modelServiceLocator); } } catch (SchemaException e) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html new file mode 100644 index 00000000000..7c560abdb3b --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html @@ -0,0 +1,35 @@ + + + + + +

+

+
+ +
+
+
+

+ + +

+ + +

+ + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java new file mode 100644 index 00000000000..e85fac6d28d --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2020 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin.server; + +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.delta.builder.S_ValuesEntry; +import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnChangeAjaxFormUpdatingBehavior; + +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; + +import com.evolveum.midpoint.gui.api.component.BasePanel; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.impl.prism.PrismPropertyWrapper; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismProperty; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.dialog.Popupable; +import com.evolveum.midpoint.web.component.input.TextPanel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; + +public class LivesyncTokenEditorPanel extends BasePanel> implements Popupable { + + private static final transient Trace LOGGER = TraceManager.getTrace(LivesyncTokenEditorPanel.class); + + private static final String ID_TOKEN = "token"; + private static final String ID_OK = "ok"; + private static final String ID_CANCEL = "cancel"; + + private ItemPath tokenPath = ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN); + + public LivesyncTokenEditorPanel(String id, IModel> model) { + super(id, model); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + private void initLayout() { + IModel syncTokenModel = new IModel() { + + @Override + public T getObject() { + PrismObjectWrapper taskWrapper = getModelObject(); + PrismObject task = taskWrapper.getObject(); + PrismProperty token = task.findProperty(tokenPath); + + if (token == null) { + return null; + } + + return token.getRealValue(); + } + + @Override + public void setObject(T object) { + PrismObjectWrapper taskWrapper = getModelObject(); + PrismObject task = taskWrapper.getObject(); + PrismProperty token = task.findProperty(tokenPath); + + if (token == null) { + try { + token = task.findOrCreateProperty(tokenPath); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot create token property", e); + getSession().error("Cannot create token property: " + e.getMessage()); + return; + } + } + + token.setRealValue(object); + } + }; + + TextPanel tokenPanel = new TextPanel<>(ID_TOKEN, syncTokenModel); + tokenPanel.getBaseFormComponent().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); + add(tokenPanel); + + AjaxButton okButton = new AjaxButton(ID_OK, createStringResource("button.ok")) { + + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + getPageBase().hideMainPopup(ajaxRequestTarget); + ObjectDelta tokenDelta = getTokenDelta(ajaxRequestTarget); + if (tokenDelta == null) { + getSession().warn("Nothing to save. Token was not changed"); + return; + } + saveTokenPerformed(tokenDelta, ajaxRequestTarget); + } + }; + add(okButton); + + AjaxButton cancelButton = new AjaxButton(ID_CANCEL, createStringResource("button.cancel")) { + + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + getPageBase().hideMainPopup(ajaxRequestTarget); + } + }; + add(cancelButton); + } + + private ObjectDelta getTokenDelta(AjaxRequestTarget target) { + TextPanel tokenPanel = (TextPanel)get(ID_TOKEN); + T newTokenValue = tokenPanel.getBaseFormComponent().getModelObject(); + try { + PrismProperty tokenProperty = getModelObject().getObject().findProperty(tokenPath); + + S_ValuesEntry valuesEntry = getPrismContext().deltaFor(TaskType.class).item(tokenPath, tokenProperty.getDefinition()); + if (newTokenValue == null) { + return valuesEntry.replace().asObjectDelta(getModelObject().getOid()); + } + return valuesEntry.replace(newTokenValue).asObjectDelta(getModelObject().getOid()); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot modify token", e); + getSession().error("Cannot modify token: " + e.getMessage()); + target.add(getPageBase().getFeedbackPanel()); + return null; + } + } + + protected void saveTokenPerformed(ObjectDelta tokenDelta, AjaxRequestTarget target) { + + } + + @Override + public int getWidth() { + return 400; + } + + @Override + public int getHeight() { + return 200; + } + + @Override + public String getWidthUnit() { + return "px"; + } + + @Override + public String getHeightUnit() { + return "px"; + } + + @Override + public StringResourceModel getTitle() { + return createStringResource("LivesyncTokenEditorPanel.manage.token"); + } + + @Override + public Component getComponent() { + return this; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java index 3c4332850b8..039aaecd5eb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java @@ -1,66 +1,60 @@ package com.evolveum.midpoint.web.page.admin.server; +import java.io.InputStream; +import java.util.Collection; +import java.util.Collections; + +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.report.api.ReportConstants; +import com.evolveum.midpoint.report.api.ReportManager; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromStream; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; + +import com.evolveum.midpoint.web.page.admin.reports.PageCreatedReports; + +import org.apache.wicket.Component; +import org.apache.wicket.Page; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; + import com.evolveum.midpoint.gui.api.GuiStyleConstants; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.ItemEditabilityHandler; -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; -import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; -import com.evolveum.midpoint.prism.Containerable; +import com.evolveum.midpoint.gui.impl.prism.PrismPropertyWrapper; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskCategory; +import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.application.AuthorizationAction; import com.evolveum.midpoint.web.application.PageDescriptor; import com.evolveum.midpoint.web.application.Url; -import com.evolveum.midpoint.web.component.*; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.AjaxIconButton; +import com.evolveum.midpoint.web.component.ObjectSummaryPanel; import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; -import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.refresh.Refreshable; import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.server.dto.TaskDtoExecutionStatus; import com.evolveum.midpoint.web.util.OnePageParameterEncoder; import com.evolveum.midpoint.web.util.TaskOperationUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationStatsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskExecutionStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskRecurrenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; - -import org.apache.wicket.Component; -import org.apache.wicket.Page; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.behavior.Behavior; -import org.apache.wicket.extensions.markup.html.tabs.AbstractTab; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.util.time.Duration; - -import javax.xml.namespace.QName; -import java.util.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @PageDescriptor( urls = { @@ -81,12 +75,9 @@ public class PageTask extends PageAdminObjectDetails implements Refres private static final transient Trace LOGGER = TraceManager.getTrace(PageTask.class); private static final String DOT_CLASS = PageTask.class.getName() + "."; protected static final String OPERATION_EXECUTE_TASK_CHANGES = DOT_CLASS + "executeTaskChanges"; + private static final String OPERATION_LOAD_REPORT_OUTPUT = DOT_CLASS + "loadReport"; - private static final int REFRESH_INTERVAL_IF_RUNNING = 2000; - private static final int REFRESH_INTERVAL_IF_RUNNABLE = 2000; - private static final int REFRESH_INTERVAL_IF_SUSPENDED = 2000; - private static final int REFRESH_INTERVAL_IF_WAITING = 2000; - private static final int REFRESH_INTERVAL_IF_CLOSED = 2000; + private static final int REFRESH_INTERVAL = 2000; private Boolean refreshEnabled; @@ -136,22 +127,50 @@ protected Collection> buildGetOptions() { .build(); } - @Override - protected void initLayout() { - super.initLayout(); - - } - private void afterOperation(AjaxRequestTarget target, OperationResult result) { showResult(result); getObjectModel().reset(); refresh(target); } - - protected void initOperationalButtons(RepeatingView repeatingView) { super.initOperationalButtons(repeatingView); + + createSuspendButton(repeatingView); + createResumeButton(repeatingView); + createRunNowButton(repeatingView); + + createManageLivesyncTokenButton(repeatingView); + createDownloadReportButton(repeatingView); + createCleanupPerformanceButton(repeatingView); + createCleanupResultsButton(repeatingView); + + createRefreshNowIconButton(repeatingView); + createResumePauseButton(repeatingView); + + + +// AjaxIconButton cleanupErrors = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), +// createStringResource("operationalButtonsPanel.cleanupErrors")) { +// +// @Override +// public void onClick(AjaxRequestTarget target) { +// refresh(target); +// } +// }; +// cleanupErrors.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); +// cleanupErrors.add(new VisibleBehaviour(this::isNotRunning)); +// repeatingView.add(cleanupErrors); + + setOutputMarkupId(true); + + final Label status = new Label(repeatingView.newChildId(), this::createRefreshingLabel); + status.setOutputMarkupId(true); + repeatingView.add(status); + + } + + private void createSuspendButton(RepeatingView repeatingView) { AjaxButton suspend = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.suspend")) { @Override public void onClick(AjaxRequestTarget target) { @@ -163,7 +182,9 @@ public void onClick(AjaxRequestTarget target) { suspend.add(new VisibleBehaviour(() -> WebComponentUtil.canSuspendTask(getTask(), PageTask.this))); suspend.add(AttributeAppender.append("class", "btn-danger")); repeatingView.add(suspend); + } + private void createResumeButton(RepeatingView repeatingView) { AjaxButton resume = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.resume")) { @Override public void onClick(AjaxRequestTarget target) { @@ -175,7 +196,9 @@ public void onClick(AjaxRequestTarget target) { resume.add(AttributeAppender.append("class", "btn-primary")); resume.add(new VisibleBehaviour(() -> WebComponentUtil.canResumeTask(getTask(), PageTask.this))); repeatingView.add(resume); + } + private void createRunNowButton(RepeatingView repeatingView) { AjaxButton runNow = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.runNow")) { @Override public void onClick(AjaxRequestTarget target) { @@ -188,7 +211,113 @@ public void onClick(AjaxRequestTarget target) { runNow.add(AttributeAppender.append("class", "btn-success")); runNow.add(new VisibleBehaviour(() -> WebComponentUtil.canRunNowTask(getTask(), PageTask.this))); repeatingView.add(runNow); + } + + private void createManageLivesyncTokenButton(RepeatingView repeatingView) { + AjaxButton manageLivesyncToken = new AjaxButton(repeatingView.newChildId(), createStringResource("PageTask.livesync.token")) { + + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + LivesyncTokenEditorPanel tokenEditor = new LivesyncTokenEditorPanel(PageTask.this.getMainPopupBodyId(), getObjectModel()) { + + @Override + protected void saveTokenPerformed(ObjectDelta tokenDelta, AjaxRequestTarget target) { + saveTaskChanges(target, tokenDelta); + } + }; + tokenEditor.setOutputMarkupId(true); + PageTask.this.showMainPopup(tokenEditor, ajaxRequestTarget); + } + }; + manageLivesyncToken.add(new VisibleEnableBehaviour() { + @Override + public boolean isVisible() { + return WebComponentUtil.isLiveSync(getTask()) && isNotRunning(); + } + + @Override + public boolean isEnabled() { + return isNotRunning(); + } + }); + manageLivesyncToken.add(AttributeAppender.append("class", "btn-default")); + manageLivesyncToken.setOutputMarkupId(true); + repeatingView.add(manageLivesyncToken); + } + private void createDownloadReportButton(RepeatingView repeatingView) { + final AjaxDownloadBehaviorFromStream ajaxDownloadBehavior = new AjaxDownloadBehaviorFromStream() { + private static final long serialVersionUID = 1L; + + @Override + protected InputStream initStream() { + ReportOutputType reportObject = getReportOutput(); + if (reportObject != null) { + return PageCreatedReports.createReport(reportObject, this, PageTask.this); + } else { + return null; + } + } + + + @Override + public String getFileName() { + ReportOutputType reportObject = getReportOutput(); + return PageCreatedReports.getReportFileName(reportObject); + } + }; + add(ajaxDownloadBehavior); + + AjaxButton download = new AjaxButton(repeatingView.newChildId(), createStringResource("PageTask.download.report")) { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ajaxDownloadBehavior.initiate(target); + } + }; + download.add(new VisibleBehaviour(() -> isDownloadReportVisible())); + download.add(AttributeAppender.append("class", "btn-primary")); + repeatingView.add(download); + } + + private boolean isDownloadReportVisible() { + return WebComponentUtil.isReport(getTask()) + && getReportOutputProperty() != null; + } + + private ReportOutputType getReportOutput() { + PrismProperty reportOutput = getReportOutputProperty(); + if (reportOutput == null) { + return null; + } + + String reportOutputOid = reportOutput.getRealValue(); + if (reportOutputOid == null) { + return null; + } + + Task opTask = createSimpleTask(OPERATION_LOAD_REPORT_OUTPUT); + OperationResult result = opTask.getResult(); + + PrismObject report = WebModelServiceUtils.loadObject(ReportOutputType.class, reportOutputOid, this, opTask, result); + if (report == null) { + return null; + } + result.computeStatusIfUnknown(); + showResult(result, false); + + return report.asObjectable(); + + } + + private PrismProperty getReportOutputProperty() { + PrismObject task = getTask().asPrismObject(); + return task.findProperty(ItemPath.create(TaskType.F_EXTENSION, ReportConstants.REPORT_OUTPUT_OID_PROPERTY_NAME)); + } + + private void createRefreshNowIconButton(RepeatingView repeatingView) { AjaxIconButton refreshNow = new AjaxIconButton(repeatingView.newChildId(), new Model<>("fa fa-refresh"), createStringResource("autoRefreshPanel.refreshNow")) { @Override @@ -198,19 +327,22 @@ public void onClick(AjaxRequestTarget target) { }; refreshNow.add(AttributeAppender.append("class", "btn btn-default btn-sm")); repeatingView.add(refreshNow); + } - AjaxIconButton resumePauseRefreshing = new AjaxIconButton(repeatingView.newChildId(), (IModel) this::createResumePauseButton, createStringResource("autoRefreshPanel.resumeRefreshing")) { + private void createResumePauseButton(RepeatingView repeatingView) { + AjaxIconButton resumePauseRefreshing = new AjaxIconButton(repeatingView.newChildId(), (IModel) this::createResumePauseButtonLabel, createStringResource("autoRefreshPanel.resumeRefreshing")) { @Override public void onClick(AjaxRequestTarget target) { refreshEnabled = !isRefreshEnabled(); -// getModelObject().setEnabled(!getModelObject().isEnabled()); refresh(target); } }; resumePauseRefreshing.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); repeatingView.add(resumePauseRefreshing); + } + private void createCleanupPerformanceButton(RepeatingView repeatingView) { AjaxIconButton cleanupPerformance = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), createStringResource("operationalButtonsPanel.cleanupEnvironmentalPerformance")) { @@ -222,14 +354,15 @@ public void onClick(AjaxRequestTarget target) { } catch (SchemaException e){ LOGGER.error("Cannot clear task results: {}", e.getMessage()); } - saveTaskChanges(); - refresh(target); + saveTaskChanges(target); } }; cleanupPerformance.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); cleanupPerformance.add(new VisibleBehaviour(this::isNotRunning)); repeatingView.add(cleanupPerformance); + } + private void createCleanupResultsButton(RepeatingView repeatingView) { AjaxIconButton cleanupResults = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), createStringResource("operationalButtonsPanel.cleanupResults")) { @@ -241,51 +374,89 @@ public void onClick(AjaxRequestTarget target) { } catch (SchemaException e){ LOGGER.error("Cannot clear task results: {}", e.getMessage()); } - saveTaskChanges(); + saveTaskChanges(target); refresh(target); } }; cleanupResults.add(new VisibleBehaviour(this::isNotRunning)); cleanupResults.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); repeatingView.add(cleanupResults); + } -// AjaxIconButton cleanupErrors = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), -// createStringResource("operationalButtonsPanel.cleanupErrors")) { -// -// @Override -// public void onClick(AjaxRequestTarget target) { -// refresh(target); -// } -// }; -// cleanupErrors.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); -// cleanupErrors.add(new VisibleBehaviour(this::isNotRunning)); -// repeatingView.add(cleanupErrors); - - setOutputMarkupId(true); - - final Label status = new Label(repeatingView.newChildId(), () -> createRefreshingLabel()); - status.setOutputMarkupId(true); - repeatingView.add(status); - + private void saveTaskChanges(AjaxRequestTarget target) { + try { + ObjectDelta taskDelta = getObjectWrapper().getObjectDelta(); + saveTaskChanges(target, taskDelta); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot get task delta.", e); + getSession().error("Cannot save changes, there were problems with computing changes: " + e.getMessage()); + target.add(getFeedbackPanel()); + } } - private void saveTaskChanges(){ + private void saveTaskChanges(AjaxRequestTarget target, ObjectDelta taskDelta){ + if (taskDelta.isEmpty()) { + getSession().warn("Nothing to save, no changes were made."); + return; + } + OperationResult result = new OperationResult(OPERATION_EXECUTE_TASK_CHANGES); Task task = createSimpleTask(OPERATION_EXECUTE_TASK_CHANGES); + try { - ObjectDelta taskDelta = getObjectWrapper().getObjectDelta(); - if (!taskDelta.isEmpty()) { - taskDelta.revive(getPrismContext()); - getModelService().executeChanges(WebComponentUtil.createDeltaCollection(taskDelta), null, task, result); - result.computeStatus(); - getObjectModel().reset(); - } + taskDelta.revive(getPrismContext()); //do we need revive here? + getModelService().executeChanges(MiscUtil.createCollection(taskDelta), null, task, result); + result.computeStatus(); + getObjectModel().reset(); } catch (Exception e) { - LOGGER.error("Cannot save tasks changes: {}", e.getMessage()); + LoggingUtils.logUnexpectedException(LOGGER, "Cannot save tasks changes", e); + result.recordFatalError("Cannot save tasks changes, " + e.getMessage(), e); } - showResult(result); +// showResult(result); + afterOperation(target, result); } + public void saveAndRunPerformed(AjaxRequestTarget target) { + PrismObjectWrapper taskWrapper = getObjectWrapper(); + try { + PrismPropertyWrapper executionStatus = taskWrapper.findProperty(ItemPath.create(TaskType.F_EXECUTION_STATUS)); + executionStatus.getValue().setRealValue(TaskExecutionStatusType.RUNNABLE); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Error while setting task execution status", e); + target.add(getFeedbackPanel()); + return; + } + + if (!checkScheduleFilledForReccurentTask(taskWrapper)) { + getSession().error("Cannot run recurring task without setting scheduling for it."); + target.add(getFeedbackPanel()); + return; + } + + super.savePerformed(target); + } + + private boolean checkScheduleFilledForReccurentTask(PrismObjectWrapper taskWrapper) { + PrismObject task = taskWrapper.getObject(); + + PrismProperty recurrenceType = task.findProperty(ItemPath.create(TaskType.F_RECURRENCE)); + if (recurrenceType == null) { + return true; + } + + TaskRecurrenceType recurenceValue = recurrenceType.getRealValue(); + if (recurenceValue == null || TaskRecurrenceType.SINGLE == recurenceValue) { + return true; + } + + ScheduleType schedule = task.asObjectable().getSchedule(); + //if schedule is not set and task is recurring, show warning. + return schedule.getCronLikePattern() != null || schedule.getEarliestStartTime() != null + || schedule.getInterval() != null || schedule.getLatestFinishTime() != null + || schedule.getLatestStartTime() != null || schedule.getMisfireAction() != null; + } + + private String createRefreshingLabel() { if (isRefreshEnabled()) { return createStringResource("autoRefreshPanel.refreshingEach", getRefreshInterval() / 1000).getString(); @@ -294,7 +465,7 @@ private String createRefreshingLabel() { } } - private String createResumePauseButton() { + private String createResumePauseButtonLabel() { if (isRefreshEnabled()) { return "fa fa-pause"; } @@ -318,263 +489,10 @@ protected TaskType load() { @Override protected AbstractObjectMainPanel createMainPanel(String id) { - - return new AbstractObjectMainPanel(id, getObjectModel(), this) { - - @Override - protected boolean getOptionsPanelVisibility() { - return false; - } - - @Override - protected List createTabs(PageAdminObjectDetails parentPage) { - List tabs = new ArrayList<>(); - TaskTabsVisibility taskTabsVisibility = new TaskTabsVisibility(); - taskTabsVisibility.computeAll(PageTask.this, getObjectWrapper()); - - ObjectTabVisibleBehavior basicTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isBasicVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.basic.title"), basicTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> getBasicTabVisibility(wrapper.getPath()); - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, getObjectModel(), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior scheduleTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isSchedulingVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.schedule.title"), scheduleTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_SCHEDULE), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior workManagementTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isWorkManagementVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.workManagement.title"), workManagementTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_WORK_MANAGEMENT), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior cleanupPoliciesTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isCleanupPolicyVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.cleanupPolicies.title"), cleanupPoliciesTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES)), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior subtasksTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isSubtasksAndThreadsVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.subtasks.title"), subtasksTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskSubtasksAndThreadsTabPanel(panelId, getObjectModel()); - } - - }); - - ObjectTabVisibleBehavior operationStatsAndInternalPerfTabsVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isInternalPerformanceVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.operationStats.title"), operationStatsAndInternalPerfTabsVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskOperationStatisticsPanel(panelId, getObjectModel()); - } - - }); - - ObjectTabVisibleBehavior envPerfTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isEnvironmentalPerformanceVisible(); - } - }; - tabs.add(new PanelTab(parentPage.createStringResource("pageTask.environmentalPerformance.title"), envPerfTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskPerformanceTabPanel(panelId, getObjectModel()); - } - - }); - - ObjectTabVisibleBehavior operationTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isOperationVisible(); - } - }; - tabs.add(new PanelTab(parentPage.createStringResource("pageTaskEdit.operation"), operationTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskOperationTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_MODEL_OPERATION_CONTEXT)); - } - }); - - tabs.add(new PanelTab(createStringResource("pageTask.internalPerformance.title"), operationStatsAndInternalPerfTabsVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskInternalPerformanceTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_OPERATION_STATS)); - } - }); - - ObjectTabVisibleBehavior resultTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isResultVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.result.title"), resultTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskResultTabPanel(panelId, getObjectModel()); - } - }); - - - ObjectTabVisibleBehavior errorsTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isErrorsVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.errors.title"), errorsTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskErrorsTabPanel(panelId, getObjectModel()); - } - }); - - return tabs; - } - }; - } - - - - private Panel createContainerPanel(String id, QName typeName, IModel> model, ItemVisibilityHandler visibilityHandler) { - try { - ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder() - .visibilityHandler(visibilityHandler) - .editabilityHandler(getTaskEditabilityHandler()) - .showOnTopLevel(true); - Panel panel = initItemPanel(id, typeName, model, builder.build()); - return panel; - } catch (SchemaException e) { - LOGGER.error("Cannot create panel for {}, {}", typeName, e.getMessage(), e); - getSession().error("Cannot create panel for " + typeName); // TODO opertion result? localization? - } - - return null; + return new TaskMainPanel(id, getObjectModel(), this); } - private ItemVisibility getBasicTabVisibility(ItemPath path) { - if (ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES).equivalent(path)) { - return ItemVisibility.HIDDEN; - } - return ItemVisibility.AUTO; - } - - private ItemEditabilityHandler getTaskEditabilityHandler(){ - ItemEditabilityHandler editableHandler = wrapper -> !WebComponentUtil.isRunningTask(getTask()); - return editableHandler; - } - - private TaskType getTask(){ + TaskType getTask(){ return getObjectWrapper().getObject().asObjectable(); } @@ -583,68 +501,23 @@ protected Class getRestartResponsePage() { return PageTasks.class; } - @Override - public void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync) { - if (!isKeepDisplayingResults()) { - showResult(result); - redirectBack(); - } - } - @Override public void continueEditing(AjaxRequestTarget target) { } - @Override - protected List getAdditionalOperationalButtonPanelBehaviors(){ - AjaxSelfUpdatingTimerBehavior behavior = new AjaxSelfUpdatingTimerBehavior(Duration.milliseconds(getRefreshInterval())) { - private static final long serialVersionUID = 1L; - - @Override - protected void onPostProcessTarget(AjaxRequestTarget target) { - refresh(target); - } - - @Override - protected boolean shouldTrigger() { - PageTask.this.getObjectModel().reset(); - return isRefreshEnabled(); - } - }; - return Collections.singletonList(behavior); - } - @Override public int getRefreshInterval() { - TaskType task = getTask(); - TaskDtoExecutionStatus exec = TaskDtoExecutionStatus.fromTaskExecutionStatus(task.getExecutionStatus(), task.getNodeAsObserved() != null); - if (exec == null) { - return REFRESH_INTERVAL_IF_CLOSED; - } - switch (exec) { - case RUNNING: - case SUSPENDING: return REFRESH_INTERVAL_IF_RUNNING; - case RUNNABLE:return REFRESH_INTERVAL_IF_RUNNABLE; - case SUSPENDED: return REFRESH_INTERVAL_IF_SUSPENDED; - case WAITING: return REFRESH_INTERVAL_IF_WAITING; - case CLOSED: return REFRESH_INTERVAL_IF_CLOSED; - } - return REFRESH_INTERVAL_IF_RUNNABLE; - } - - @Override - public Component getRefreshingBehaviorParent() { - return null; //nothing to do, this method will be removed + return REFRESH_INTERVAL; } public void refresh(AjaxRequestTarget target) { -// getObjectModel().reset(); + getObjectModel().reset(); target.add(getSummaryPanel()); target.add(getOperationalButtonsPanel()); target.add(getFeedbackPanel()); - target.add(getMainPanel()); +// target.add(getMainPanel()); for (Component component : getMainPanel().getTabbedPanel()) { if (component instanceof TaskTabPanel) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java index 1ff15955a20..ab16a4fd84e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java @@ -186,6 +186,7 @@ private Collection> createOperationOptions( propertiesToGet.add(TaskType.F_NODE_AS_OBSERVED); propertiesToGet.add(TaskType.F_NEXT_RUN_START_TIMESTAMP); propertiesToGet.add(TaskType.F_NEXT_RETRY_TIMESTAMP); + propertiesToGet.add(TaskType.F_SUBTASK); GetOperationOptionsBuilder getOperationOptionsBuilder = getSchemaHelper().getOperationOptionsBuilder(); getOperationOptionsBuilder = getOperationOptionsBuilder.resolveNames(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html new file mode 100644 index 00000000000..2e8bf153a32 --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java new file mode 100644 index 00000000000..9f9d328c427 --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin.server; + +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.impl.prism.ItemEditabilityHandler; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; +import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; +import com.evolveum.midpoint.prism.Containerable; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.AjaxSubmitButton; +import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.prism.ItemVisibility; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.List; + +public class TaskMainPanel extends AbstractObjectMainPanel { + + private static final transient Trace LOGGER = TraceManager.getTrace(TaskMainPanel.class); + + private static final String ID_SAVE_AND_RUN = "saveAndRun"; + private static final String ID_FORM = "taskForm"; + + public TaskMainPanel(String id, LoadableModel> objectModel, PageAdminObjectDetails parentPage) { + super(id, objectModel, parentPage); + } + + @Override + protected boolean getOptionsPanelVisibility() { + return false; + } + + @Override + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { + super.initLayoutButtons(parentPage); + initLayoutSaveAndRunButton(); + } + + @Override + protected List createTabs(PageAdminObjectDetails parentPage) { + List tabs = new ArrayList<>(); + TaskTabsVisibility taskTabsVisibility = new TaskTabsVisibility(); + taskTabsVisibility.computeAll((PageTask) parentPage, getObjectWrapper()); + + ObjectTabVisibleBehavior basicTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", (PageTask) parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isBasicVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.basic.title"), basicTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> getBasicTabVisibility(wrapper.getPath()); + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, getObjectModel(), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior scheduleTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isSchedulingVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.schedule.title"), scheduleTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_SCHEDULE), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior workManagementTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isWorkManagementVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.workManagement.title"), workManagementTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_WORK_MANAGEMENT), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior cleanupPoliciesTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isCleanupPolicyVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.cleanupPolicies.title"), cleanupPoliciesTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES)), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior subtasksTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isSubtasksAndThreadsVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.subtasks.title"), subtasksTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskSubtasksAndThreadsTabPanel(panelId, getObjectModel()); + } + + }); + + ObjectTabVisibleBehavior operationStatsAndInternalPerfTabsVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isInternalPerformanceVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.operationStats.title"), operationStatsAndInternalPerfTabsVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskOperationStatisticsPanel(panelId, getObjectModel()); + } + + }); + + ObjectTabVisibleBehavior envPerfTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isEnvironmentalPerformanceVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.environmentalPerformance.title"), envPerfTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskPerformanceTabPanel(panelId, getObjectModel()); + } + + }); + + ObjectTabVisibleBehavior operationTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isOperationVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTaskEdit.operation"), operationTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskOperationTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_MODEL_OPERATION_CONTEXT)); + } + }); + + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.internalPerformance.title"), operationStatsAndInternalPerfTabsVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskInternalPerformanceTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_OPERATION_STATS)); + } + }); + + ObjectTabVisibleBehavior resultTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isResultVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.result.title"), resultTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskResultTabPanel(panelId, getObjectModel()); + } + }); + + + ObjectTabVisibleBehavior errorsTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isErrorsVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.errors.title"), errorsTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskErrorsTabPanel(panelId, getObjectModel()); + } + }); + + return tabs; + } + + protected void initLayoutSaveAndRunButton() { + AjaxSubmitButton saveButton = new AjaxSubmitButton(ID_SAVE_AND_RUN, getDetailsPage().createStringResource("pageAdminFocus.button.saveAndRun")) { + private static final long serialVersionUID = 1L; + + @Override + protected void onSubmit(AjaxRequestTarget target) { + ((PageTask)getDetailsPage()).saveAndRunPerformed(target); + } + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(getDetailsPage().getFeedbackPanel()); + } + }; + saveButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return !getObjectWrapper().isReadOnly() && + !getDetailsPage().isForcedPreview(); + } + + @Override + public boolean isEnabled() { + return !ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) + || getObjectWrapper().canModify(); + } + }); + saveButton.setOutputMarkupId(true); + saveButton.setOutputMarkupPlaceholderTag(true); + getMainForm().add(saveButton); + } + + + private Panel createContainerPanel(String id, QName typeName, IModel> model, ItemVisibilityHandler visibilityHandler) { + try { + ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder() + .visibilityHandler(visibilityHandler) + .editabilityHandler(getTaskEditabilityHandler()) + .showOnTopLevel(true); + Panel panel = getDetailsPage().initItemPanel(id, typeName, model, builder.build()); + return panel; + } catch (SchemaException e) { + LOGGER.error("Cannot create panel for {}, {}", typeName, e.getMessage(), e); + getSession().error("Cannot create panel for " + typeName); // TODO opertion result? localization? + } + + return null; + } + + private ItemVisibility getBasicTabVisibility(ItemPath path) { + if (ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES).equivalent(path)) { + return ItemVisibility.HIDDEN; + } + return ItemVisibility.AUTO; + } + + + private ItemEditabilityHandler getTaskEditabilityHandler(){ + ItemEditabilityHandler editableHandler = wrapper -> !WebComponentUtil.isRunningTask(((PageTask)getDetailsPage()).getTask()); + return editableHandler; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java index f9998829cf0..974cfaa0044 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java @@ -37,6 +37,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.stream.Stream; public class TaskOperationStatisticsPanel extends BasePanel> implements TaskTabPanel { @@ -69,29 +70,39 @@ private LoadableModel createOperationStatsModel() { protected OperationStatsType load() { PrismObject task = getModelObject().getObject(); - IterativeTaskInformationType iterativeTaskInformation = new IterativeTaskInformationType(); - SynchronizationInformationType synchronizationInformation = new SynchronizationInformationType(); - ActionsExecutedInformationType actionsExecutedInformation = new ActionsExecutedInformationType(); - - if (TaskTypeUtil.isPartitionedMaster(task.asObjectable())) { - List subTasks = resolveSubTasks(); - for (TaskType taskDto : subTasks) { - OperationStatsType operationStats = taskDto.getOperationStats(); - if (operationStats != null) { - IterativeTaskInformation.addTo(iterativeTaskInformation, operationStats.getIterativeTaskInformation(), true); - SynchronizationInformation.addTo(synchronizationInformation, operationStats.getSynchronizationInformation()); - ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStats.getActionsExecutedInformation()); - } - } - - return new OperationStatsType(getPrismContext()) - .iterativeTaskInformation(iterativeTaskInformation) - .synchronizationInformation(synchronizationInformation) - .actionsExecutedInformation(actionsExecutedInformation); - - } - - return task.asObjectable().getOperationStats(); + return TaskTypeUtil.getAggregatedOperationStats(task.asObjectable(), getPrismContext()); +// IterativeTaskInformationType iterativeTaskInformation = new IterativeTaskInformationType(); +// SynchronizationInformationType synchronizationInformation = new SynchronizationInformationType(); +// ActionsExecutedInformationType actionsExecutedInformation = new ActionsExecutedInformationType(); +// +// if (TaskTypeUtil.isPartitionedMaster(task.asObjectable())) { +//// List subTasks = resolveSubTasks(); +// Stream subTasks = TaskTypeUtil.getAllTasksStream(task.asObjectable()); +// subTasks.forEach(subTask -> { +// OperationStatsType operationStatsType = subTask.getOperationStats(); +// if (operationStatsType != null) { +// IterativeTaskInformation.addTo(iterativeTaskInformation, operationStatsType.getIterativeTaskInformation(), true); +// SynchronizationInformation.addTo(synchronizationInformation, operationStatsType.getSynchronizationInformation()); +// ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStatsType.getActionsExecutedInformation()); +// } +// }); +//// for (TaskType taskDto : subTasks) { +//// OperationStatsType operationStats = taskDto.getOperationStats(); +//// if (operationStats != null) { +//// IterativeTaskInformation.addTo(iterativeTaskInformation, operationStats.getIterativeTaskInformation(), true); +//// SynchronizationInformation.addTo(synchronizationInformation, operationStats.getSynchronizationInformation()); +//// ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStats.getActionsExecutedInformation()); +//// } +//// } +// +// return new OperationStatsType(getPrismContext()) +// .iterativeTaskInformation(iterativeTaskInformation) +// .synchronizationInformation(synchronizationInformation) +// .actionsExecutedInformation(actionsExecutedInformation); +// +// } +// +// return task.asObjectable().getOperationStats(); } }; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java index f334c8330c8..067327d2ec2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java @@ -46,6 +46,7 @@ import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -227,6 +228,7 @@ protected List, String>> initCustomTaskColumns( columns.add(createTaskExecutionStatusColumn()); columns.add(createProgressColumn("pageTasks.task.progress")); + columns.add(createErrorsColumn("pageTasks.task.errors")); columns.add(new IconColumn>(createStringResource("pageTasks.task.status"), TaskType.F_RESULT_STATUS.getLocalPart()) { @@ -296,6 +298,17 @@ public IModel getDataModel(IModel> rowModel) { }; } + private AbstractColumn, String> createErrorsColumn(String titleKey) { + return new AbstractColumn, String>(createStringResource(titleKey)) { + @Override + public void populateItem(Item>> cellItem, String componentId, IModel> rowModel) { + TaskType task = rowModel.getObject().getValue(); + cellItem.add(new Label(componentId, new Model<>(TaskTypeUtil.getObjectsProcessedFailures(task, getPrismContext())))); + + } + }; + } + private String getProgressDescription(SelectableBean task) { Long stalledSince = getStalledSince(task.getValue()); if (stalledSince != null) { @@ -415,7 +428,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); boolean visible = WebComponentUtil.canSuspendTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase()); return Model.of(visible); } @@ -452,7 +465,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); boolean visible = WebComponentUtil.canResumeTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase()); return Model.of(visible); } @@ -490,7 +503,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); return Model.of(WebComponentUtil.canRunNowTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase())); } @@ -664,7 +677,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); return Model.of(WebComponentUtil.canSuspendTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase())); } @@ -699,6 +712,7 @@ public IModel getConfirmationMessageModel() { } //region Task-level actions + //TODO unify with TaskOperationUtils private void suspendTasksPerformed(AjaxRequestTarget target, IModel> selectedTask) { List selectedTasks = getSelectedTasks(target, selectedTask); if (selectedTasks == null) { @@ -842,12 +856,8 @@ private void deleteTaskConfirmedPerformed(AjaxRequestTarget target, IModel> task) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java index a369f22bbd1..dbcb2242ac4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java @@ -82,23 +82,25 @@ public boolean computeSubtasksAndThreadsVisible(PageTask parentPage, PrismObject } public boolean configuresWorkerThreads(TaskType task) { - return isReconciliation(task) || isImport(task) || isRecomputation(task) || isExecuteChanges(task.getHandlerUri()) + return WebComponentUtil.isReconciliation(task) || WebComponentUtil.isImport(task) || WebComponentUtil.isRecomputation(task) || isExecuteChanges(task.getHandlerUri()) || isShadowIntegrityCheck(task.getHandlerUri()) || isFocusValidityScanner(task.getHandlerUri()) || isTriggerScanner(task.getHandlerUri()); } public boolean computeEnvironmentalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { final OperationStatsType operationStats = taskWrapper.getObject().asObjectable().getOperationStats(); - environmentalPerformanceVisible = !parentPage.isAdd() && !parentPage.isEditingFocus() - && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) - && operationStats != null - && !StatisticsUtil.isEmpty(operationStats.getEnvironmentalPerformanceInformation()); + environmentalPerformanceVisible = parentPage.isEditingFocus(); + //todo does it make sense to check operationStats? it may be null for partitioned task +// && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) +// && operationStats != null +// && !StatisticsUtil.isEmpty(operationStats.getEnvironmentalPerformanceInformation()); return environmentalPerformanceVisible; } public boolean computeInternalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { - internalPerformanceVisible = !parentPage.isAdd() &&!parentPage.isEditingFocus() - && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) - && taskWrapper.getObject().asObjectable().getOperationStats() != null; + internalPerformanceVisible = parentPage.isEditingFocus(); + //todo doea it make sense to check operationStats? it may be null for partitioned task +// && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) +// && taskWrapper.getObject().asObjectable().getOperationStats() != null; return internalPerformanceVisible; } @@ -109,7 +111,7 @@ public boolean computeOperationVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { - resultVisible = !parentPage.isAdd() && !parentPage.isEditingFocus() + resultVisible = parentPage.isEditingFocus() && isTaskItemReadable(taskWrapper, TaskType.F_RESULT) && !WebComponentUtil.isWorkflowTask(taskWrapper.getObject().asObjectable()); return resultVisible; } public boolean computeErrorsVisible(PageTask parentPage, TaskType task) { - errorsVisible = !parentPage.isAdd() && !parentPage.isEditingFocus() + errorsVisible = parentPage.isEditingFocus() && !WebComponentUtil.isWorkflowTask(task); return errorsVisible; } @@ -144,7 +146,7 @@ public void computeAll(PageTask parentPage, PrismObjectWrapper taskWra } public boolean computeProgressVisible(PageTask parentPage) { - progressVisible = !parentPage.isEditingFocus(); + progressVisible = parentPage.isEditingFocus(); return progressVisible; } @@ -165,44 +167,6 @@ private boolean isExecuteChanges(String handlerUri) { return ModelPublicConstants.EXECUTE_CHANGES_TASK_HANDLER_URI.equals(handlerUri); } - private boolean isReconciliation(TaskType task){ - ObjectReferenceType archetypeRef = getArchetypeReference(task); - if (archetypeRef == null){ - return false; - } - return SystemObjectsType.ARCHETYPE_RECONCILIATION_TASK.value().equals(archetypeRef.getOid()); - } - - private boolean isRecomputation(TaskType task){ - ObjectReferenceType archetypeRef = getArchetypeReference(task); - if (archetypeRef == null){ - return false; - } - return SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value().equals(archetypeRef.getOid()); - } - - private boolean isImport(TaskType task){ - ObjectReferenceType archetypeRef = getArchetypeReference(task); - if (archetypeRef == null){ - return false; - } - return SystemObjectsType.ARCHETYPE_IMPORT_TASK.value().equals(archetypeRef.getOid()); - } - - private ObjectReferenceType getArchetypeReference(TaskType task) { - ObjectReferenceType archetypeRef = null; - if (task.getAssignment() == null || task.getAssignment().size() == 0) { - return archetypeRef; - } - for (AssignmentType assignment : task.getAssignment()) { - if (StringUtils.isNotEmpty(assignment.getTargetRef().getOid()) - && assignment.getTargetRef() != null && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { - archetypeRef = assignment.getTargetRef(); - } - } - return archetypeRef; - } - private boolean isTaskItemReadable(PrismObjectWrapper taskWrapper, ItemPath itemPath){ ItemWrapper taskProperty = null; try { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java index fde0dd09d59..7b28f50546f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java @@ -6,21 +6,34 @@ */ package com.evolveum.midpoint.web.page.admin.users; +import static org.apache.commons.collections4.CollectionUtils.addIgnoreNull; + +import java.util.*; + +import org.apache.commons.lang3.StringUtils; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; + import com.evolveum.midpoint.gui.api.ComponentConstants; import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; import com.evolveum.midpoint.gui.api.model.LoadableModel; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.model.api.context.ModelContext; -import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.PrismContainerDefinition; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; @@ -43,23 +56,7 @@ import com.evolveum.midpoint.web.page.admin.users.component.UserSummaryPanel; import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RelationKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.apache.commons.lang3.StringUtils; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import java.util.*; - -import static org.apache.commons.collections4.CollectionUtils.addIgnoreNull; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author lazyman @@ -140,7 +137,7 @@ protected FocusSummaryPanel createSummaryPanel() { Model.of(getObjectModel().getObject().getObject().asObjectable()) : Model.of(), this); } - protected void cancelPerformed(AjaxRequestTarget target) { + protected void cancelPerformed() { redirectBack(); } @@ -266,8 +263,10 @@ protected boolean getOptionsPanelVisibility() { @Override protected boolean areSavePreviewButtonsEnabled(){ - return super.areSavePreviewButtonsEnabled() || - (userDelegationsTabPanel != null ? userDelegationsTabPanel.isDelegationsModelChanged() : false); + if (super.areSavePreviewButtonsEnabled()) { + return true; + } + return userDelegationsTabPanel != null && userDelegationsTabPanel.isDelegationsModelChanged(); } @Override @@ -356,7 +355,7 @@ protected boolean processDeputyAssignments(boolean previewOnly) { /** * for now used only for delegation changes - * @param modelContextMap + * @param modelContextMap preview changes deltas */ @Override protected void processAdditionalFocalObjectsForPreview(Map, ModelContext> modelContextMap){ @@ -420,31 +419,4 @@ public boolean isLoggedInUserPage(){ getObjectWrapper().getObject().asObjectable().getOid().equals(WebModelServiceUtils.getLoggedInFocusOid()); } - protected int countConsents() { - int consentCounter = 0; - PrismObject focus = getObjectModel().getObject().getObject(); - List assignments = focus.asObjectable().getAssignment(); - for (AssignmentType assignment : assignments) { - if (isConsentAssignment(assignment)) { - consentCounter++; - } - } - return consentCounter; - } - - private boolean isConsentAssignment(AssignmentType assignment) { - return assignment.getTargetRef() != null && QNameUtil.match(assignment.getTargetRef().getRelation(), SchemaConstants.ORG_CONSENT); - } - - protected List getConsentsList(List assignments, UserDtoStatus status){ - List list = new ArrayList<>(); - for (AssignmentType assignment : assignments) { - if (isConsentAssignment(assignment)) { - //TODO set status - list.add(assignment); - } - } - return list; - } - } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java index 227665f1c91..facbe3e60fc 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java @@ -203,7 +203,7 @@ private void initLayout(){ public boolean isVisible() { return (level != null && level.getFormRef() != null && level.getFormRef().getOid() != null); - }; + } }); if (level != null && level.getFormRef() != null && level.getFormRef().getOid() != null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java index 0c64025ca8b..c28250a7d5c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java @@ -144,7 +144,7 @@ public boolean isVisible() { public boolean isVisible() { return getResetPasswordPolicy().getResetMethod() == ResetMethod.SECURITY_QUESTIONS; - }; + } }); WebMarkupContainer emailContainer = new WebMarkupContainer(ID_EMAIL_CONTAINER); @@ -161,7 +161,7 @@ public boolean isVisible() { public boolean isVisible() { ResetMethod resetMethod = getResetPasswordPolicy().getResetMethod(); return resetMethod == ResetMethod.SECURITY_QUESTIONS || resetMethod == ResetMethod.MAIL; - }; + } }); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java index 7bd299198cf..23323d42848 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java @@ -112,7 +112,7 @@ public boolean isVisible() { public boolean isVisible() { return oldPasswordVisible; - }; + } }); PasswordPanel passwordPanel = new PasswordPanel(ID_PASSWORD_PANEL, new PropertyModel<>(model, MyPasswordsDto.F_PASSWORD)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java index 178cded1ddd..1db1ce1e0f3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java @@ -99,7 +99,7 @@ protected void initLayout() { public IModel getBody() { return searchTypes.get(selectedSearchType); - }; + } @Override protected void onSubmit(AjaxRequestTarget target) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java index d976b320e9d..726b8576a3e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java @@ -102,7 +102,7 @@ protected AuthenticationProvider getProvider(AbstractCredentialAuthenticationMod } return getObjectObjectPostProcessor().postProcess(createProvider(usedPolicy)); - }; + } protected abstract ModuleAuthentication createEmptyModuleAuthentication(AbstractAuthenticationModuleType moduleType, C configuration); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java index c8c7d3f727e..99280585905 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java @@ -123,7 +123,7 @@ protected AuthenticationProvider getProvider(AuthenticationModuleLdapType module getObjectObjectPostProcessor().postProcess(provider); return provider; - }; + } protected ModuleWebSecurityConfig createModule(ModuleWebSecurityConfiguration configuration) { return getObjectObjectPostProcessor().postProcess(new LdapWebSecurityConfig((LdapModuleWebSecurityConfiguration) configuration)); diff --git a/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml b/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml index 16abb199a58..06b08f58cc8 100644 --- a/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml +++ b/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml @@ -475,6 +475,7 @@ 910 + hidden @@ -488,90 +489,7 @@ stalledSince - - 990 - - - - - objectRef - - - extension/mext:objectType - - - extension/mext:diagnose - - - extension/mext:fix - - - extension/mext:duplicateShadowsResolver - - - extension/mext:checkDuplicatesOnPrimaryIdentifiersOnly - - - extension/mext:dryRun - - - extension/mext:retryLiveSyncErrors - - - extension/mext:freshnessInterval - - - extension/mext:finishOperationsOnly - - - extension/mext:lastScanTimestamp - - - extension/mext:searchOptions - - - extension/mext:useRepositoryDirectly - - - extension/mext:iterationMethod - - - extension/mext:objectDelta - - - extension/mext:objectDeltas - - - extension/mext:executeOptions - - - extension/mext:filename - - - extension/mext:endpoint - - - extension/mext:optionRaw - - - extension/mext:objectclass - - - extension/mext:kind - - - extension/mext:intent - - - extension/mext:objectQuery - - - extension/mext:updateLiveSyncTokenInDryRun - - - extension/mext:modelExecuteOptions - - + diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java index 3b350c164a5..6db0cfc1ab0 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java @@ -72,11 +72,6 @@ public String toStringContent() { return super.toStringContent() + ", password=" + password; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override protected void extendDebugDump(StringBuilder sb, int indent) { sb.append("\n"); diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java index ecc53817ddc..c838b5b8851 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java @@ -68,11 +68,6 @@ public String toStringContent() { return super.toStringContent() + ", members=" + getMembers(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override protected void extendDebugDump(StringBuilder sb, int indent) { sb.append("\n"); diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java index 16b69863536..b151a88b9ed 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java @@ -1075,12 +1075,6 @@ private void traceOperation(String opName, long counter) { } } - - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(toString()); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java index 293d6579418..c77ecaf6904 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java @@ -715,11 +715,6 @@ public boolean equals(Object obj) { return true; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { return debugDump(indent, (LayerType) null); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java index a792a746e2f..fe6753bdb44 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java @@ -57,11 +57,6 @@ public void setAccess(PropertyAccessType access) { this.access = access; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java index c32ce9ecde6..bc2d499f90b 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java @@ -1183,10 +1183,6 @@ private void add(RefinedAttributeDefinition refinedAttributeDefinition) { //endregion //region Diagnostic output, hashCode/equals ========================================================= - @Override - public String debugDump() { - return debugDump(0); - } @Override public String debugDump(int indent) { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java index ce9d9ed0784..c81f8f9f79c 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java @@ -17,7 +17,7 @@ public class LegacyValidationMessage { public enum Type { WARNING, ERROR - }; + } public Type type; public String oid; diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java index 2de55c702ca..912bd922ebf 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java @@ -36,7 +36,7 @@ public interface LocalDefinitionStore { @SuppressWarnings("unchecked") default ID findLocalItemDefinition(@NotNull QName name) { return (ID) findLocalItemDefinition(name, ItemDefinition.class, false); - }; + } @SuppressWarnings("unchecked") default ID findItemDefinition(@NotNull ItemPath path) { diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java index a61fb016497..8a5c3ae5a3f 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java @@ -58,11 +58,6 @@ public int hashCode() { return Objects.hash(delta, residualPath); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java index cc2776e7771..7e25e30f375 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java @@ -14,14 +14,14 @@ import java.util.List; import java.util.Map; +import javax.xml.namespace.QName; + /** * @author semancik * */ public interface UniformItemPath extends Serializable, Cloneable, ShortDumpable, ItemPath { - UniformItemPath EMPTY_PATH = UniformItemPathImpl.EMPTY_PATH; - @NotNull List getSegments(); @@ -95,4 +95,30 @@ default UniformItemPath rest() { void setNamespaceMap(Map namespaceMap); Map getNamespaceMap(); + + static UniformItemPath empty() { + return UniformItemPathImpl.EMPTY_PATH; + } + + static UniformItemPath create(Object... segments) { + return UniformItemPathImpl.create(segments); + } + + static @NotNull UniformItemPath from(ItemPath path) { + return UniformItemPathImpl.fromItemPath(path); + } + + static ItemPathSegment createSegment(QName qname, boolean variable) { + if (ParentPathSegment.QNAME.equals(qname)) { + return new ParentPathSegment(); + } else if (ObjectReferencePathSegment.QNAME.equals(qname)) { + return new ObjectReferencePathSegment(); + } else if (IdentifierPathSegment.QNAME.equals(qname)) { + return new IdentifierPathSegment(); + } else if (variable) { + return new VariableItemPathSegment(qname); + } else { + return new NameItemPathSegment(qname); + } + } } diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java index 93cb90c7943..a31d1102210 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java @@ -18,7 +18,7 @@ * @author semancik * */ -public class UniformItemPathImpl implements UniformItemPath { +class UniformItemPathImpl implements UniformItemPath { public static final UniformItemPathImpl EMPTY_PATH = UniformItemPathImpl.createEmpty(); @@ -42,20 +42,6 @@ public static UniformItemPathImpl fromItemPath(ItemPath itemPath) { } } - public static ItemPathSegment createSegment(QName qname, boolean variable) { - if (ParentPathSegment.QNAME.equals(qname)) { - return new ParentPathSegment(); - } else if (ObjectReferencePathSegment.QNAME.equals(qname)) { - return new ObjectReferencePathSegment(); - } else if (IdentifierPathSegment.QNAME.equals(qname)) { - return new IdentifierPathSegment(); - } else if (variable) { - return new VariableItemPathSegment(qname); - } else { - return new NameItemPathSegment(qname); - } - } - public void setNamespaceMap(Map namespaceMap) { this.namespaceMap = namespaceMap; } @@ -216,7 +202,7 @@ private void add(Object object) { } private void add(QName qname) { - this.segments.add(createSegment(qname, false)); + this.segments.add(UniformItemPath.createSegment(qname, false)); } private void add(ItemPathSegment segment) { @@ -426,4 +412,8 @@ public String toString() { shortDump(sb); return sb.toString(); } + + static UniformItemPath create(Object... segments) { + return new UniformItemPathImpl(segments); + } } diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java index c002c5fa7f2..ea353ebb5f9 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java @@ -97,25 +97,9 @@ public interface ValueFilter ext @Override ValueFilter clone(); - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - boolean equals(Object o); - @Override boolean equals(Object o, boolean exact); - @Override - int hashCode(); - - @Override - String debugDump(); - - @Override - String debugDump(int indent); - - @Override - String toString(); - //String getFilterName(); //void debugDump(int indent, StringBuilder sb); diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java index 22a30976ca6..4bcfc6cd21c 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java @@ -185,6 +185,10 @@ public static Date toDate(XMLGregorianCalendar xmlCal) { return xmlCal != null ? new Date(xmlCal.toGregorianCalendar().getTimeInMillis()) : null; } + public static XMLGregorianCalendar fromNow(String timeSpec) { + return fromNow(XmlTypeConverter.createDuration(timeSpec)); + } + public static XMLGregorianCalendar fromNow(Duration duration) { XMLGregorianCalendar rv = createXMLGregorianCalendar(System.currentTimeMillis()); rv.add(duration); diff --git a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java index aa32ef7baa7..b226014a81d 100644 --- a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java +++ b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java @@ -612,11 +612,6 @@ public QueryType clone() { } } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java index 3d574221c23..4f8d402866e 100644 --- a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java +++ b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java @@ -267,11 +267,6 @@ public SearchFilterType clone() { return clone; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java index ef13edaa38f..04978714f13 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java @@ -16,7 +16,6 @@ import com.evolveum.midpoint.prism.impl.crypto.KeyStoreBasedProtectorImpl; import com.evolveum.midpoint.prism.impl.marshaller.*; import com.evolveum.midpoint.prism.impl.path.CanonicalItemPathImpl; -import com.evolveum.midpoint.prism.path.UniformItemPathImpl; import com.evolveum.midpoint.prism.impl.schema.SchemaDefinitionFactory; import com.evolveum.midpoint.prism.impl.schema.SchemaFactoryImpl; import com.evolveum.midpoint.prism.impl.schema.SchemaRegistryImpl; @@ -563,12 +562,12 @@ public ParsingContext createParsingContextForCompatibilityMode() { @Override public UniformItemPath emptyPath() { - return UniformItemPathImpl.EMPTY_PATH; + return UniformItemPath.empty(); } @Override public UniformItemPath path(Object... namesOrIdsOrSegments) { - return new UniformItemPathImpl(namesOrIdsOrSegments); + return UniformItemPath.create(namesOrIdsOrSegments); } @Override @@ -601,17 +600,17 @@ public KeyStoreBasedProtector createProtector(KeyStoreBasedProtectorBuilder buil @NotNull @Override public UniformItemPath toUniformPath(ItemPath path) { - return UniformItemPathImpl.fromItemPath(path); + return UniformItemPath.from(path); } @Override public UniformItemPath toUniformPathKeepNull(ItemPath path) { - return path != null ? UniformItemPathImpl.fromItemPath(path) : null; + return path != null ? UniformItemPath.from(path) : null; } @Override public UniformItemPath toUniformPath(ItemPathType path) { - return UniformItemPathImpl.fromItemPath(path.getItemPath()); + return UniformItemPath.from(path.getItemPath()); } @Override diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java index fce69617d79..7351733491c 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java @@ -261,14 +261,6 @@ private void dumpMap(StringBuilder sb, String label, Map set) { sb.append(label).append(": ").append(set).append("; "); } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java index 106446f6929..0499804c23f 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java @@ -387,14 +387,6 @@ private void dumpSet(StringBuilder sb, String label, Collection set) { sb.append(label).append(": ").append(set).append("; "); } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java index ebece72f933..d477d01f090 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java @@ -1029,11 +1029,6 @@ public String toDebugType() { return objectTypeClass.getSimpleName(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java index 669b27fc363..d39c5cded6a 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java @@ -8,7 +8,6 @@ package com.evolveum.midpoint.prism.impl.marshaller; import com.evolveum.midpoint.prism.PrismConstants; -import com.evolveum.midpoint.prism.path.UniformItemPathImpl; import com.evolveum.midpoint.prism.path.*; import com.evolveum.midpoint.prism.impl.xml.GlobalDynamicNamespacePrefixMapper; import com.evolveum.midpoint.util.DOMUtil; @@ -218,11 +217,11 @@ private String findNamespace(String prefix, Node domNode, Map na //region Serializing public static String serializeWithDeclarations(@NotNull ItemPath itemPath) { - return new ItemPathHolder(UniformItemPathImpl.fromItemPath(itemPath)).getXPathWithDeclarations(); + return new ItemPathHolder(UniformItemPath.from(itemPath)).getXPathWithDeclarations(); } public static String serializeWithForcedDeclarations(@NotNull ItemPath itemPath) { - return new ItemPathHolder(UniformItemPathImpl.fromItemPath(itemPath), true).getXPathWithDeclarations(); + return new ItemPathHolder(UniformItemPath.from(itemPath), true).getXPathWithDeclarations(); } private ItemPathHolder(@NotNull UniformItemPath itemPath) { @@ -398,7 +397,7 @@ public Map getNamespaceMap() { } public static Element serializeToElement(ItemPath path, QName elementQName, Document document) { - return new ItemPathHolder(UniformItemPathImpl.fromItemPath(path)).toElement(elementQName, document); + return new ItemPathHolder(UniformItemPath.from(path)).toElement(elementQName, document); } public Element toElement(QName elementQName, Document document) { @@ -443,10 +442,10 @@ public UniformItemPath toItemPath() { } else { QName qName = segment.getQName(); boolean variable = segment.isVariable(); - segments.add(UniformItemPathImpl.createSegment(qName, variable)); + segments.add(UniformItemPath.createSegment(qName, variable)); } } - UniformItemPath path = new UniformItemPathImpl(segments); + UniformItemPath path = UniformItemPath.create(segments); path.setNamespaceMap(explicitNamespaceDeclarations); return path; } diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java index 95d443ed592..c23fda880cf 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java @@ -40,11 +40,6 @@ public void checkConsistence(boolean requireDefinitions) { // nothing to do } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java index e2b28435ef5..af50cee7b6f 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java @@ -112,11 +112,6 @@ public void checkConsistence(boolean requireDefinitions) { } } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java index 6296e292341..b43d42d08a4 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java @@ -284,11 +284,6 @@ private void copyTo(ObjectPagingImpl clone) { clone.cookie = this.cookie; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java index 5e38b2823d8..a3c0765f6a2 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java @@ -93,11 +93,6 @@ public ObjectQueryImpl cloneEmpty() { return clone; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java index 90bdd14edaa..80e865fdbee 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java @@ -315,11 +315,6 @@ public int hashCode() { return Objects.hash(fullPath, matchingRule, values, expression, rightHandSidePath); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java index f81f90ea44a..8c1df3958e9 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java @@ -598,11 +598,6 @@ public Collection getCompileTimePackages() { } //endregion - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java index 3e3c95e41de..4344155df43 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java @@ -182,11 +182,6 @@ private Map clonePrefixMap(Map map) { return clone; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java index bfc9b8af9a0..cfcc66215c7 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java @@ -198,11 +198,6 @@ protected void copyCommonAttributesFrom(XNodeImpl xnode) { setMaxOccurs(xnode.getMaxOccurs()); } - @Override - public String debugDump() { - return debugDump(0); - } - public abstract String getDesc(); protected String dumpSuffix() { diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java index 25964e0101c..c2c5128c8e9 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java @@ -40,8 +40,8 @@ public class TestPath extends AbstractPrismTest { */ @Test public void testEmptyPath() { - System.out.println("UniformItemPath.EMPTY_PATH = " + UniformItemPath.EMPTY_PATH); - System.out.println("UniformItemPathImpl.EMPTY_PATH = " + UniformItemPathImpl.EMPTY_PATH); + System.out.println("UniformItemPath.empty() = " + UniformItemPath.empty()); + assertNotNull(UniformItemPath.empty()); } @Test diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java index 94e19f8820a..9d753de2933 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java @@ -7,19 +7,20 @@ package com.evolveum.midpoint.prism.lex; -import com.evolveum.midpoint.prism.impl.lex.LexicalProcessor; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.prism.impl.xnode.RootXNodeImpl; -import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.fail; import java.util.ArrayList; import java.util.List; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.fail; +import org.testng.annotations.Test; + +import com.evolveum.midpoint.prism.impl.lex.LexicalProcessor; +import com.evolveum.midpoint.prism.impl.xnode.RootXNodeImpl; +import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.util.DebugUtil; +import com.evolveum.midpoint.util.exception.SchemaException; /** * @author mederly @@ -68,7 +69,8 @@ public void testParseObjectsIteratively_2_Wrong() throws Exception { System.out.println("Parsed objects (standard way):"); System.out.println(DebugUtil.debugDump(nodesStandard)); - assertFalse("Nodes are not different", nodesStandard.equals(nodes)); + assertThat(nodesStandard).withFailMessage("Nodes are not different") + .isNotEqualTo(nodes); } @Test @@ -98,16 +100,11 @@ public void testParseObjectsIteratively_2_Wrong_2() throws Exception { @Test public void testParseObjectsIteratively_9_listSingle() throws Exception { - final String TEST_NAME = "testParseObjectsIteratively_9_listSingle"; - - standardTest(TEST_NAME, OBJECTS_9_LIST_SINGLE, 1); + standardTest(OBJECTS_9_LIST_SINGLE, 1); } @Test public void testParseObjectsIteratively_10_listOfLists() throws Exception { - final String TEST_NAME = "testParseObjectsIteratively_10_listOfLists"; - - standardTest(TEST_NAME, OBJECTS_10_LIST_OF_LISTS, 3); + standardTest(OBJECTS_10_LIST_OF_LISTS, 3); } - } diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java index d322a9b3e56..48fac86fcc8 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java @@ -86,7 +86,7 @@ protected File getFile(String baseName) { @Test public void testParseUserToPrism() throws Exception { // GIVEN - LexicalProcessor lexicalProcessor = createParser(); + LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); // WHEN (parse to xnode) @@ -182,7 +182,7 @@ public void testParseUserRoundTrip() throws Exception { @Test public void testParseResourceRumToPrism() throws Exception { // GIVEN - LexicalProcessor lexicalProcessor = createParser(); + LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); // WHEN (parse to xnode) @@ -331,7 +331,7 @@ protected void validateResourceSchema(String dataString, PrismContext prismConte @Test(enabled = false) public void testParseEventHandler() throws Exception { // GIVEN - LexicalProcessor lexicalProcessor = createParser(); + LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); // WHEN (parse to xnode) @@ -356,9 +356,7 @@ public void testParseEventHandler() throws Exception { @Test public void testParseObjectsIteratively_1() throws Exception { - final String TEST_NAME = "testParseObjectsIteratively_1"; - - List nodes = standardTest(TEST_NAME, OBJECTS_1, 3); + List nodes = standardTest(OBJECTS_1, 3); final String NS_C = "http://midpoint.evolveum.com/xml/ns/public/common/common-3"; nodes.forEach(n -> assertEquals("Wrong namespace", NS_C, n.getRootElementName().getNamespaceURI())); @@ -367,7 +365,8 @@ public void testParseObjectsIteratively_1() throws Exception { assertEquals("Wrong namespace for node 3", NS_C, getFirstElementNS(nodes, 2)); } - protected List standardTest(String TEST_NAME, String fileName, int expectedCount) throws SchemaException, IOException { + protected List standardTest(String fileName, int expectedCount) + throws SchemaException, IOException { // GIVEN LexicalProcessor lexicalProcessor = createParser(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java index 906b7623f95..d59db482db1 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java @@ -197,11 +197,6 @@ public String toString() { '}'; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java index d82efb8b450..2073d146173 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java @@ -224,11 +224,6 @@ public String toString() { return "ConnectorOperationalStatus(" + connectorName + ": " + connectorClassName + ": " + poolStatusNumActive + "/" + poolConfigMaxSize+")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java index 9f475446d73..43c5ab206ae 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java @@ -1,80 +1,120 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.schema.util; - -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.stream.Stream; - -/** - * @author mederly - */ -public class TaskTypeUtil { - - /** - * Returns a stream of the task and all of its subtasks. - */ - @NotNull - public static Stream getAllTasksStream(TaskType root) { - return Stream.concat(Stream.of(root), - getResolvedSubtasks(root).stream().flatMap(TaskTypeUtil::getAllTasksStream)); - } - - public static List getResolvedSubtasks(TaskType parent) { - List rv = new ArrayList<>(); - for (ObjectReferenceType childRef : parent.getSubtaskRef()) { - //noinspection unchecked - PrismObject child = childRef.getObject(); - if (child != null) { - rv.add(child.asObjectable()); - } else { - throw new IllegalStateException("Unresolved subtaskRef in " + parent + ": " + childRef); - } - } - return rv; - } - - public static void addSubtask(TaskType parent, TaskType child, PrismContext prismContext) { - parent.getSubtaskRef().add(ObjectTypeUtil.createObjectRefWithFullObject(child, prismContext)); - } - - //moved from GUI - public static boolean isCoordinator(TaskType task) { - return getKind(task) == TaskKindType.COORDINATOR; - } - - public static boolean isPartitionedMaster(TaskType task) { - return getKind(task) == TaskKindType.PARTITIONED_MASTER; - } - - @NotNull - public static TaskKindType getKind(TaskType task) { - if (task.getWorkManagement() != null && task.getWorkManagement().getTaskKind() != null) { - return task.getWorkManagement().getTaskKind(); - } else { - return TaskKindType.STANDALONE; - } - } - - public static int getObjectsProcessed(TaskType task) { - OperationStatsType stats = task.getOperationStats(); - if (stats == null) { - return 0; - } - IterativeTaskInformationType iterativeStats = stats.getIterativeTaskInformation(); - if (iterativeStats == null) { - return 0; - } - return iterativeStats.getTotalSuccessCount() + iterativeStats.getTotalFailureCount(); - } -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.schema.util; + +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.schema.statistics.ActionsExecutedInformation; +import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; +import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.stream.Stream; + +/** + * @author mederly + */ +public class TaskTypeUtil { + + /** + * Returns a stream of the task and all of its subtasks. + */ + @NotNull + public static Stream getAllTasksStream(TaskType root) { + return Stream.concat(Stream.of(root), + getResolvedSubtasks(root).stream().flatMap(TaskTypeUtil::getAllTasksStream)); + } + + public static List getResolvedSubtasks(TaskType parent) { + List rv = new ArrayList<>(); + for (ObjectReferenceType childRef : parent.getSubtaskRef()) { + //noinspection unchecked + PrismObject child = childRef.getObject(); + if (child != null) { + rv.add(child.asObjectable()); + } else { + throw new IllegalStateException("Unresolved subtaskRef in " + parent + ": " + childRef); + } + } + return rv; + } + + public static void addSubtask(TaskType parent, TaskType child, PrismContext prismContext) { + parent.getSubtaskRef().add(ObjectTypeUtil.createObjectRefWithFullObject(child, prismContext)); + } + + //moved from GUI + public static boolean isCoordinator(TaskType task) { + return getKind(task) == TaskKindType.COORDINATOR; + } + + public static boolean isPartitionedMaster(TaskType task) { + return getKind(task) == TaskKindType.PARTITIONED_MASTER; + } + + @NotNull + public static TaskKindType getKind(TaskType task) { + if (task.getWorkManagement() != null && task.getWorkManagement().getTaskKind() != null) { + return task.getWorkManagement().getTaskKind(); + } else { + return TaskKindType.STANDALONE; + } + } + + public static int getObjectsProcessed(TaskType task) { + OperationStatsType stats = task.getOperationStats(); + if (stats == null) { + return 0; + } + IterativeTaskInformationType iterativeStats = stats.getIterativeTaskInformation(); + if (iterativeStats == null) { + return 0; + } + return iterativeStats.getTotalSuccessCount() + iterativeStats.getTotalFailureCount(); + } + + public static int getObjectsProcessedFailures(TaskType task, PrismContext prismContext) { + OperationStatsType stats = getAggregatedOperationStats(task, prismContext); + if (stats == null) { + return 0; + } + IterativeTaskInformationType iterativeStats = stats.getIterativeTaskInformation(); + if (iterativeStats == null) { + return 0; + } + return iterativeStats.getTotalFailureCount(); + } + + public static OperationStatsType getAggregatedOperationStats(TaskType task, PrismContext prismContext) { + if (!isPartitionedMaster(task)) { + return task.getOperationStats(); + } + + IterativeTaskInformationType iterativeTaskInformation = new IterativeTaskInformationType(); + SynchronizationInformationType synchronizationInformation = new SynchronizationInformationType(); + ActionsExecutedInformationType actionsExecutedInformation = new ActionsExecutedInformationType(); + + Stream subTasks = TaskTypeUtil.getAllTasksStream(task); + subTasks.forEach(subTask -> { + OperationStatsType operationStatsType = subTask.getOperationStats(); + if (operationStatsType != null) { + IterativeTaskInformation.addTo(iterativeTaskInformation, operationStatsType.getIterativeTaskInformation(), true); + SynchronizationInformation.addTo(synchronizationInformation, operationStatsType.getSynchronizationInformation()); + ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStatsType.getActionsExecutedInformation()); + } + }); + + return new OperationStatsType(prismContext) + .iterativeTaskInformation(iterativeTaskInformation) + .synchronizationInformation(synchronizationInformation) + .actionsExecutedInformation(actionsExecutedInformation); + } +} diff --git a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd index 7534e40b98b..4fa8bbb8464 100755 --- a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd +++ b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd @@ -21479,7 +21479,21 @@ - + + + + + + + + + + + + + + + diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java index 49fc0d62ab0..20351d533c1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java @@ -700,12 +700,13 @@ public void test700Exists() throws Exception { checkQueryRoundtripFile(AccessCertificationCaseType.class, q); } + public static final String TEST_900_910_FILE_NAME = TEST_DIR + "/test900TypeWrong.xml"; + @Test public void test900TypeWrong() throws Exception { - final String TEST_NAME = "test900TypeWrong"; - String fileName = TEST_DIR + "/" + TEST_NAME + ".xml"; try { - toQueryType(FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8)); + toQueryType(FileUtils.readFileToString( + new File(TEST_900_910_FILE_NAME), StandardCharsets.UTF_8)); fail("Unexpected success!"); } catch (SchemaException e) { System.out.println("Got expected exception: " + e.getMessage()); @@ -714,10 +715,8 @@ public void test900TypeWrong() throws Exception { @Test public void test910TypeWrongCompat() throws Exception { - final String TEST_NAME = "test900TypeWrong"; - String fileName = TEST_DIR + "/" + TEST_NAME + ".xml"; - QueryType jaxb = toQueryTypeCompat( - FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8)); + QueryType jaxb = toQueryTypeCompat(FileUtils.readFileToString( + new File(TEST_900_910_FILE_NAME), StandardCharsets.UTF_8)); displayQueryType(jaxb); try { ObjectQuery query = toObjectQuery(ObjectType.class, jaxb); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java index 5e8c981d17b..9d5ef0378b8 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java @@ -25,7 +25,6 @@ /** * @author semancik - * */ public class TestObjectValidator extends AbstractSchemaTest { @@ -41,10 +40,7 @@ public class TestObjectValidator extends AbstractSchemaTest { @Test public void testValidateRoleOneDefault() throws Exception { - final String TEST_NAME = "testValidateRoleOneDefault"; - // GIVEN - ObjectValidator validator = createValidator(); PrismObject object = PrismTestUtil.getPrismContext().parseObject(ROLE_ONE_FILE); @@ -63,8 +59,6 @@ public void testValidateRoleOneDefault() throws Exception { @Test public void testValidateRoleOneDeprecated() throws Exception { - final String TEST_NAME = "testValidateRoleOneDeprecated"; - // GIVEN ObjectValidator validator = createValidator(); @@ -90,8 +84,6 @@ public void testValidateRoleOneDeprecated() throws Exception { */ @Test public void testValidateRoleOneLegacyCompat() throws Exception { - final String TEST_NAME = "testValidateRoleOneLegacyCompat"; - // GIVEN ObjectValidator validator = createValidator(); @@ -120,8 +112,6 @@ public void testValidateRoleOneLegacyCompat() throws Exception { */ @Test public void testValidateRoleOneLegacyStrict() throws Exception { - final String TEST_NAME = "testValidateRoleOneLegacyStrict"; - // GIVEN ObjectValidator validator = createValidator(); @@ -144,11 +134,7 @@ public void testValidateRoleOneLegacyStrict() throws Exception { // We have no planned removal annotations in 4.0. Nothing to test. // @Test // public void testValidateRoleOnePlannedRemoval() throws Exception { -// final String TEST_NAME = "testValidateRoleOnePlannedRemoval"; -// displayTestTile(TEST_NAME); -// // // GIVEN -// // ObjectValidator validator = createValidator(); // validator.setWarnPlannedRemoval(true); // @@ -179,7 +165,7 @@ private void assertWarnings(ValidationResult validationResult, Object... expecte if (expectedItem instanceof ItemPath) { expectedPath = (ItemPath)expectedItem; } else if (expectedItem instanceof QName) { - expectedPath = ItemPath.create((QName)expectedItem); + expectedPath = ItemPath.create(expectedItem); } else { throw new IllegalArgumentException("What? "+expectedItem); } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java index a5165be2a5d..5b4a64d7c04 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java @@ -280,11 +280,6 @@ private void diff(StringBuilder sb, String key, Integer baselineValue, Integer c sb.append("\n"); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java index cec7ccbe9f2..02c4e1a4de8 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java @@ -1,45 +1,46 @@ -/* - * Copyright (c) 2010-2015 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.model.api; - -import com.evolveum.midpoint.schema.constants.SchemaConstants; - -/** - * Model constants referenced from the outside. - * (TODO reconsider with regards to SchemaConstants) - * - * @author mederly - */ -public class ModelPublicConstants { - - private static final String NS_SYNCHRONIZATION_PREFIX = SchemaConstants.NS_MODEL +"/synchronization"; - public static final String NS_SYNCHRONIZATION_TASK_PREFIX = NS_SYNCHRONIZATION_PREFIX + "/task"; - - public static final String DELETE_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete/handler-3"; // TODO why "synchronization"? - public static final String REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/reindex/handler-3"; - public static final String AUDIT_REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/auditReindex/handler-3"; - public static final String CLEANUP_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/cleanup/handler-3"; - public static final String SHADOW_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadow-integrity-check/handler-3"; - public static final String OBJECT_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/object-integrity-check/handler-3"; - public static final String DEPRECATED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/focus-validation-scanner/handler-3"; - public static final String FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/focus-validity-scanner/handler-3"; - public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/partitioned-focus-validity-scanner/handler-3"; - public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_1 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#1"; - public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_2 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#2"; - public static final String TRIGGER_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/trigger/scanner/handler-3"; - public static final String SHADOW_REFRESH_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadowRefresh/handler-3"; - public static final String RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/reconciliation/handler-3"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/partitioned-reconciliation/handler-3"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_1 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#1"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_2 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#2"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_3 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#3"; - public static final String SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/scripting/handler-3"; - public static final String ITERATIVE_SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/iterative-scripting/handler-3"; - public static final String EXECUTE_DELTAS_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/execute-deltas/handler-3"; - public static final String EXECUTE_CHANGES_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/execute/handler-3"; - public static final String DELETE_NOT_UPDATE_SHADOW_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete-not-updated-shadow/handler-3"; -} +/* + * Copyright (c) 2010-2015 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.model.api; + +import com.evolveum.midpoint.schema.constants.SchemaConstants; + +/** + * Model constants referenced from the outside. + * (TODO reconsider with regards to SchemaConstants) + * + * @author mederly + */ +public class ModelPublicConstants { + + private static final String NS_SYNCHRONIZATION_PREFIX = SchemaConstants.NS_MODEL +"/synchronization"; + public static final String NS_SYNCHRONIZATION_TASK_PREFIX = NS_SYNCHRONIZATION_PREFIX + "/task"; + + public static final String DELETE_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete/handler-3"; // TODO why "synchronization"? + public static final String REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/reindex/handler-3"; + public static final String AUDIT_REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/auditReindex/handler-3"; + public static final String CLEANUP_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/cleanup/handler-3"; + public static final String SHADOW_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadow-integrity-check/handler-3"; + public static final String OBJECT_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/object-integrity-check/handler-3"; + public static final String DEPRECATED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/focus-validation-scanner/handler-3"; + public static final String FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/focus-validity-scanner/handler-3"; + public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/partitioned-focus-validity-scanner/handler-3"; + public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_1 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#1"; + public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_2 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#2"; + public static final String TRIGGER_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/trigger/scanner/handler-3"; + public static final String SHADOW_REFRESH_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadowRefresh/handler-3"; + public static final String RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/reconciliation/handler-3"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/partitioned-reconciliation/handler-3"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_1 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#1"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_2 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#2"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_3 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#3"; + public static final String SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/scripting/handler-3"; + public static final String ITERATIVE_SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/iterative-scripting/handler-3"; + public static final String EXECUTE_DELTAS_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/execute-deltas/handler-3"; + public static final String EXECUTE_CHANGES_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/execute/handler-3"; + public static final String DELETE_NOT_UPDATE_SHADOW_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete-not-updated-shadow/handler-3"; + public static final String RECOMPUTE_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/recompute/handler-3"; +} diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java index 6f0fecfea74..9d08dbe77f8 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java @@ -120,11 +120,6 @@ public void setMessage(String message) { this.message = message; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java index 2d2f779bf7e..511bff5f854 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java @@ -96,11 +96,6 @@ public String toString() { + ", rightLinkDelta=" + rightLinkDelta + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java index a864fc82317..3dfeb599ad8 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java @@ -790,10 +790,9 @@ public XMLGregorianCalendar currentDateTime() { } public XMLGregorianCalendar fromNow(String timeSpec) { - return XmlTypeConverter.fromNow(XmlTypeConverter.createDuration(timeSpec)); + return XmlTypeConverter.fromNow(timeSpec); } - public XMLGregorianCalendar addDuration(XMLGregorianCalendar now, Duration duration) { if (now == null) { return null; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java index 0e8139158bf..98ab05fbef4 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java @@ -62,11 +62,6 @@ public String toString() { return "ConstructionPack(" + SchemaDebugUtil.prettyPrint(constructions) + (forceRecon ? ", forceRecon" : "") + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java index 49adbf6a7ba..a3ef1ebdfd0 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java @@ -320,11 +320,6 @@ public List> subList(int fromIndex, int toIndex) { // DUMP - @Override - public String debugDump() { - return debugDump(0); - } - public String dump(boolean showTriples) { return debugDump(0, showTriples); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java index 0be0a7889c9..bdc692dfb22 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java @@ -52,11 +52,6 @@ public List getData() { return data; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { return DebugUtil.debugDump(data, indent); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java index ac1914165e8..2497e61209f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java @@ -148,9 +148,4 @@ public String debugDump(int indent) { return sb.toString(); } - @Override - public String debugDump() { - return debugDump(0); - } - } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java index 6d29ec26e94..8a4858b71c8 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java @@ -79,11 +79,6 @@ public void setSourceDelta(ItemDelta sourceDelta) { this.sourceDelta = sourceDelta; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = debugDumpCommon(indent); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java index 1ff40549e8f..86c6fdfbd3a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java @@ -139,11 +139,6 @@ public void setSourceDelta(ObjectDelta sourceDelta) { this.sourceDelta = sourceDelta; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java index 35ca4cd3f33..6e79eac651e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java @@ -86,11 +86,6 @@ public void setSourceRelPath(ItemPath sourceRelPath) { this.sourceRelPath = sourceRelPath; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = debugDumpCommon(indent); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java index 83a0b495dce..56edcf10e4e 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java @@ -7,32 +7,26 @@ package com.evolveum.midpoint.model.impl; import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.test.TestResource; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.model.impl.util.mock.MockClockworkHook; -import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.internals.InternalsConfig; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; +import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik - * */ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class AbstractInternalModelIntegrationTest extends AbstractModelImplementationIntegrationTest { @@ -66,7 +60,7 @@ public class AbstractInternalModelIntegrationTest extends AbstractModelImplement protected static final String USER_ELAINE_USERNAME = "elaine"; // Largo does not have a full name set, employeeType=PIRATE - protected static final File USER_LARGO_FILE = new File(COMMON_DIR, "user-largo.xml"); + protected static final File USER_LARGO_FILE = new File(COMMON_DIR, "user-largo.xml"); protected static final String USER_LARGO_OID = "c0c010c0-d34d-b33f-f00d-111111111118"; public static final File ROLE_SUPERUSER_FILE = new File(COMMON_DIR, "role-superuser.xml"); @@ -113,8 +107,6 @@ public class AbstractInternalModelIntegrationTest extends AbstractModelImplement protected static final String MOCK_CLOCKWORK_HOOK_URL = MidPointConstants.NS_MIDPOINT_TEST_PREFIX + "/mockClockworkHook"; - protected static final Trace LOGGER = TraceManager.getTrace(AbstractModelIntegrationTest.class); - protected PrismObject userAdministrator; protected UserType userTypeJack; @@ -126,7 +118,7 @@ public class AbstractInternalModelIntegrationTest extends AbstractModelImplement @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); // We want logging config from logback-test.xml and not from system config object (unless suppressed) diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java index 78e2e892d98..e7bca1e3126 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java @@ -70,7 +70,7 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + logger.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); if (!idPath.contains(userName)) { AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } @@ -97,7 +97,7 @@ public void test002testReconcileScriptsWhenReconciling() throws Exception { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + logger.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); if (!idPath.contains(userName)) { AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } @@ -110,9 +110,7 @@ public void test002testReconcileScriptsWhenReconciling() throws Exception { @Test public void test003testReconcileScriptsAddUserAction() throws Exception { - final String TEST_NAME = "test003testReconcileScriptsAddUserAction"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = createOperationResult(); ShadowType shadow = parseObjectType(new File(ACCOUNT_BEFORE_SCRIPT_FILENAME), ShadowType.class); @@ -140,7 +138,7 @@ public void test003testReconcileScriptsAddUserAction() throws Exception { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + logger.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); if (!idPath.contains(userName)) { AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java index 25b0eafa828..a36a2e85bfc 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java @@ -161,7 +161,7 @@ public void test004CorrelationMatchCaseInsensitive() throws Exception { AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex) { - LOGGER.error("exception occured: {}", ex.getMessage(), ex); + logger.error("exception occured: {}", ex.getMessage(), ex); throw ex; } } @@ -185,7 +185,7 @@ public void test005CorrelationMatchCaseInsensitive() throws Exception { AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex) { - LOGGER.error("exception occured: {}", ex.getMessage(), ex); + logger.error("exception occured: {}", ex.getMessage(), ex); throw ex; } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java index 65bcd510f44..117cfbc3db9 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java @@ -76,7 +76,7 @@ public class TestSynchronizationService extends AbstractInternalModelIntegration @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); initDummyResourcePirate(RESOURCE_DUMMY_LIMITED_NAME, diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java index e6a723ec621..3681fe99884 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java @@ -105,14 +105,6 @@ public void invokeOnException(@NotNull ModelContext context, @NotNull Throwable // // } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/model/model-intest/pom.xml b/model/model-intest/pom.xml index 4aaba738eec..77520674d96 100644 --- a/model/model-intest/pom.xml +++ b/model/model-intest/pom.xml @@ -244,6 +244,11 @@ testng test + + org.assertj + assertj-core + test + com.evolveum.midpoint.tools test-ng diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java index 04af15e9c13..893937ae425 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java @@ -6,42 +6,32 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.*; + import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ENABLE_TIMESTAMP; import static com.evolveum.midpoint.schema.util.ObjectTypeUtil.cast; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Date; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.icf.dummy.resource.DummyObjectClass; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; - -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.test.TestResource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; -import com.evolveum.icf.dummy.resource.ConflictException; -import com.evolveum.icf.dummy.resource.DummyAccount; -import com.evolveum.icf.dummy.resource.DummyResource; -import com.evolveum.icf.dummy.resource.SchemaViolationException; -import com.evolveum.midpoint.model.intest.sync.AbstractSynchronizationStoryTest; +import com.evolveum.icf.dummy.resource.*; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.intest.sync.TestValidityRecomputeTask; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; @@ -50,33 +40,20 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; +import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.LockoutStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TimeIntervalStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * * @see TestValidityRecomputeTask */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestActivation extends AbstractInitializedModelIntegrationTest { @@ -169,10 +146,8 @@ public void test050CheckJackEnabled() throws Exception { @Test public void test051ModifyUserJackDisable() throws Exception { - final String TEST_NAME = "test051ModifyUserJackDisable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -200,10 +175,8 @@ public void test051ModifyUserJackDisable() throws Exception { @Test public void test052ModifyUserJackNull() throws Exception { - final String TEST_NAME = "test052ModifyUserJackNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -230,10 +203,8 @@ public void test052ModifyUserJackNull() throws Exception { @Test public void test055ModifyUserJackEnable() throws Exception { - final String TEST_NAME = "test055ModifyUserJackEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -261,10 +232,8 @@ public void test055ModifyUserJackEnable() throws Exception { @Test public void test056RecomputeUserJackEffectiveEnable() throws Exception { - final String TEST_NAME = "test056RecomputeUserJackEffectiveEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); @@ -304,19 +273,14 @@ public void test056RecomputeUserJackEffectiveEnable() throws Exception { assertValidity(userJackAfter, null); assertEffectiveStatus(userJackAfter, ActivationStatusType.ENABLED); - TestUtil.assertModifyTimestamp(userJackAfter, start, end); - - } @Test public void test060ModifyUserJackLifecycleActive() throws Exception { - final String TEST_NAME = "test060ModifyUserJackLifecycleActive"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -344,10 +308,8 @@ public void test060ModifyUserJackLifecycleActive() throws Exception { @Test public void test061ModifyUserJackLifecycleDraft() throws Exception { - final String TEST_NAME = "test061ModifyUserJackLifecycleDraft"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -375,10 +337,8 @@ public void test061ModifyUserJackLifecycleDraft() throws Exception { @Test public void test065ModifyUserJackLifecycleDeprecated() throws Exception { - final String TEST_NAME = "test065ModifyUserJackLifecycleDeprecated"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -406,10 +366,8 @@ public void test065ModifyUserJackLifecycleDeprecated() throws Exception { @Test public void test068ModifyUserJackLifecycleArchived() throws Exception { - final String TEST_NAME = "test068ModifyUserJackLifecycleArchived"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -436,10 +394,8 @@ public void test068ModifyUserJackLifecycleArchived() throws Exception { @Test public void test069ModifyUserJackLifecycleNull() throws Exception { - final String TEST_NAME = "test069ModifyUserJackLifecycleNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -466,10 +422,8 @@ public void test069ModifyUserJackLifecycleNull() throws Exception { @Test public void test100ModifyUserJackAssignAccount() throws Exception { - final String TEST_NAME = "test100ModifyUserJackAssignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -526,7 +480,7 @@ public void test100ModifyUserJackAssignAccount() throws Exception { dummyAuditService.assertExecutionSuccess(); Collection> executionDeltas = dummyAuditService.getExecutionDeltas(); boolean found = false; - for (ObjectDeltaOperation executionDelta: executionDeltas) { + for (ObjectDeltaOperation executionDelta : executionDeltas) { ObjectDelta objectDelta = executionDelta.getObjectDelta(); if (objectDelta.getObjectTypeClass() == ShadowType.class) { PropertyDelta enableTimestampDelta = objectDelta.findPropertyDelta(PATH_ACTIVATION_ENABLE_TIMESTAMP); @@ -540,10 +494,8 @@ public void test100ModifyUserJackAssignAccount() throws Exception { @Test public void test101ModifyUserJackDisable() throws Exception { - final String TEST_NAME = "test101ModifyUserJackDisable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -595,7 +547,6 @@ public void test102ModifyUserJackEnable() throws Exception { assertEnableTimestampFocus(userJack, startTime, endTime); } - /** * Modify account activation. User's activation should be unchanged */ @@ -635,10 +586,8 @@ public void test111ModifyAccountJackDisable() throws Exception { */ @Test public void test112UserJackRecompute() throws Exception { - final String TEST_NAME = "test112UserJackRecompute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -674,10 +623,8 @@ public void test112UserJackRecompute() throws Exception { */ @Test public void test114ModifyUserJackEnable() throws Exception { - final String TEST_NAME = "test114ModifyUserJackEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -711,10 +658,8 @@ public void test114ModifyUserJackEnable() throws Exception { */ @Test public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { - final String TEST_NAME = "test115ModifyUserJackAdministrativeStatusNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -749,10 +694,8 @@ public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { */ @Test public void test118ModifyJackActivationUserAndAccount() throws Exception { - final String TEST_NAME = "test118ModifyJackActivationUserAndAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -844,14 +787,11 @@ public void test120ModifyUserJackAssignAccountDummyRed() throws Exception { */ @Test public void test121ModifyJackUserAndAccountRed() throws Exception { - final String TEST_NAME = "test121ModifyJackUserAndAccountRed"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - ObjectDelta userDelta = createModifyUserReplaceDelta(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountRedOid, getDummyResourceObject(), @@ -923,10 +863,8 @@ public void test130ModifyAccountDefaultAndRed() throws Exception { */ @Test public void test138ModifyJackEnabled() throws Exception { - final String TEST_NAME = "test138ModifyJackEnabled"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -953,10 +891,8 @@ public void test138ModifyJackEnabled() throws Exception { */ @Test public void test139ModifyUserJackUnAssignAccountDummyRed() throws Exception { - final String TEST_NAME = "test139ModifyUserJackUnAssignAccountDummyRed"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1256,10 +1192,8 @@ public void test152ModifyAccountsJackDisable() throws Exception { */ @Test public void test153ModifyAccountsJackEnable() throws Exception { - final String TEST_NAME = "test153ModifyAccountsJackEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1386,7 +1320,7 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { dummyAuditService.assertExecutionSuccess(); Collection> executionDeltas = dummyAuditService.getExecutionDeltas(); boolean found = false; - for (ObjectDeltaOperation executionDelta: executionDeltas) { + for (ObjectDeltaOperation executionDelta : executionDeltas) { ObjectDelta objectDelta = executionDelta.getObjectDelta(); if (objectDelta.getObjectTypeClass() == ShadowType.class) { // Actually, there should be no F_TRIGGER delta! It was there by mistake. @@ -1395,7 +1329,7 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { // } PropertyDelta enableTimestampDelta = objectDelta.findPropertyDelta(PATH_ACTIVATION_ENABLE_TIMESTAMP); display("Audit enableTimestamp delta", enableTimestampDelta); - assertNotNull("EnableTimestamp delta vanished from audit record, delta: "+objectDelta, enableTimestampDelta); + assertNotNull("EnableTimestamp delta vanished from audit record, delta: " + objectDelta, enableTimestampDelta); found = true; } } @@ -1404,10 +1338,8 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { @Test public void test170GetAccountUnlocked() throws Exception { - final String TEST_NAME = "test170GetAccountUnlocked"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1427,10 +1359,8 @@ public void test170GetAccountUnlocked() throws Exception { @Test public void test172GetAccountLocked() throws Exception { - final String TEST_NAME = "test172GetAccountLocked"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1454,10 +1384,8 @@ public void test172GetAccountLocked() throws Exception { @Test public void test174ModifyAccountUnlock() throws Exception { - final String TEST_NAME = "test174ModifyAccountUnlock"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1488,10 +1416,8 @@ public void test174ModifyAccountUnlock() throws Exception { @Test public void test176ModifyUserUnlock() throws Exception { - final String TEST_NAME = "test176ModifyUserUnlock"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1520,13 +1446,10 @@ public void test176ModifyUserUnlock() throws Exception { checkAdminStatusFor15x(userJack, true, true, true); } - @Test public void test199DeleteUserJack() throws Exception { - final String TEST_NAME = "test199DeleteUserJack"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1556,11 +1479,9 @@ public void test199DeleteUserJack() throws Exception { @Test public void test200AddUserLargo() throws Exception { - final String TEST_NAME = "test200AddUserLargo"; - // GIVEN long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userLargo = PrismTestUtil.parseObject(USER_LARGO_FILE); @@ -1581,10 +1502,8 @@ public void test200AddUserLargo() throws Exception { @Test public void test205ModifyUserLargoAssignAccount() throws Exception { - final String TEST_NAME = "test205ModifyUserLargoAssignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1619,11 +1538,9 @@ public void test205ModifyUserLargoAssignAccount() throws Exception { @Test public void test210ModifyLargoValidTo10MinsAgo() throws Exception { - final String TEST_NAME = "test210ModifyLargoValidTo10MinsAgo"; - // GIVEN long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); XMLGregorianCalendar tenMinutesAgo = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis() - 10 * 60 * 1000); @@ -1656,11 +1573,9 @@ public void test210ModifyLargoValidTo10MinsAgo() throws Exception { @Test public void test211ModifyLargoValidToManana() throws Exception { - final String TEST_NAME = "test211ModifyLargoValidToManana"; - // GIVEN long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); manana = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis() + 10 * 24 * 60 * 60 * 1000); @@ -1697,10 +1612,8 @@ public void test211ModifyLargoValidToManana() throws Exception { */ @Test public void test212SeeLargoTomorrow() throws Exception { - final String TEST_NAME = "test212SeeLargoTomorrow"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Let's play with the clock, move the time to tomorrow @@ -1743,7 +1656,7 @@ public void test213HastaLaMananaLargo() throws Exception { OperationResult result = task.getResult(); // Let's play with the clock, move the time forward 20 days - long crrentNow = System.currentTimeMillis() + 20 *24 * 60 * 60 * 1000; + long crrentNow = System.currentTimeMillis() + 20 * 24 * 60 * 60 * 1000; clock.override(crrentNow); // WHEN @@ -1774,11 +1687,9 @@ public void test213HastaLaMananaLargo() throws Exception { @Test public void test215ModifyLargoRemoveValidTo() throws Exception { - final String TEST_NAME = "test215ModifyLargoRemoveValidTo"; - // GIVEN long startMillis = clock.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -1810,11 +1721,9 @@ public void test215ModifyLargoRemoveValidTo() throws Exception { @Test public void test217ModifyLargoRemoveValidFrom() throws Exception { - final String TEST_NAME = "test217ModifyLargoRemoveValidFrom"; - // GIVEN long startMillis = clock.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -1851,10 +1760,8 @@ public void test217ModifyLargoRemoveValidFrom() throws Exception { */ @Test public void test230JackUnassignRepoRecompute() throws Exception { - final String TEST_NAME = "test230JackUnassignRepoRecompute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); addObject(USER_JACK_FILE); @@ -1882,10 +1789,8 @@ public void test230JackUnassignRepoRecompute() throws Exception { */ @Test public void test231JackRecomputeReconcile() throws Exception { - final String TEST_NAME = "test231JackRecomputeReconcile"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2127,7 +2032,6 @@ public void test249DeleteUserRapp() throws Exception { assertNoDummyAccount(USER_RAPP_USERNAME); } - /** * Test reading of validity data through shadow */ @@ -2203,10 +2107,8 @@ public void test310ImportAccountsFromDummyGreen() throws Exception { @Test public void test350AssignMancombBlueAccount() throws Exception { - final String TEST_NAME = "test350AssignMancombBlueAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2229,10 +2131,8 @@ public void test350AssignMancombBlueAccount() throws Exception { @Test public void test352AssignMancombBlackAccount() throws Exception { - final String TEST_NAME = "test352AssignMancombBlackAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2261,10 +2161,8 @@ public void test352AssignMancombBlackAccount() throws Exception { @Test public void test355MancombModifyAdministrativeStatusNull() throws Exception { - final String TEST_NAME = "test355MancombModifyAdministrativeStatusNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2295,13 +2193,11 @@ public void test355MancombModifyAdministrativeStatusNull() throws Exception { @Test public void test400AddHerman() throws Exception { - final String TEST_NAME = "test400AddHerman"; - // WHEN addObject(USER_HERMAN_FILE); // THEN - // Make sure that it is effectivelly enabled + // Make sure that it is effectively enabled PrismObject userHermanAfter = getUser(USER_HERMAN_OID); assertEffectiveActivation(userHermanAfter, ActivationStatusType.ENABLED); } @@ -2311,10 +2207,8 @@ public void test400AddHerman() throws Exception { */ @Test public void test410AssignHermanKhakiAccount() throws Exception { - final String TEST_NAME = "test410AssignHermanKhakiAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2337,85 +2231,82 @@ public void test410AssignHermanKhakiAccount() throws Exception { khakiAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME)); } - @Test public void test500CheckRolePirateInitial() throws Exception { - test5X0CheckInitial("test500CheckRolePirateInitial", RoleType.class, ROLE_PIRATE_OID); + test5X0CheckInitial(RoleType.class, ROLE_PIRATE_OID); } @Test public void test501RolePirateRecompute() throws Exception { - test5X1Recompute("test501RolePirateRecompute", RoleType.class, ROLE_PIRATE_OID); + test5X1Recompute(RoleType.class, ROLE_PIRATE_OID); } @Test public void test502ModifyRolePirateDisable() throws Exception { - test5X2ModifyDisable("test502ModifyRolePirateDisable", RoleType.class, ROLE_PIRATE_OID); + test5X2ModifyDisable(RoleType.class, ROLE_PIRATE_OID); } @Test public void test504ModifyRolePirateEnable() throws Exception { - test5X4ModifyEnable("test504ModifyRolePirateEnable", RoleType.class, ROLE_PIRATE_OID); + test5X4ModifyEnable(RoleType.class, ROLE_PIRATE_OID); } @Test public void test505RolePirateRecompute() throws Exception { - test5X5Recompute("test505RolePirateRecompute", RoleType.class, ROLE_PIRATE_OID); + test5X5Recompute(RoleType.class, ROLE_PIRATE_OID); } - @Test public void test510CheckOrgScummBarInitial() throws Exception { - test5X0CheckInitial("test510CheckOrgScummBarInitial", OrgType.class, ORG_SCUMM_BAR_OID); + test5X0CheckInitial(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test511OrgScummBarRecompute() throws Exception { - test5X1Recompute("test511OrgScummBarRecompute", OrgType.class, ORG_SCUMM_BAR_OID); + test5X1Recompute(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test512ModifyOrgScummBarDisable() throws Exception { - test5X2ModifyDisable("test512ModifyOrgScummBarDisable", OrgType.class, ORG_SCUMM_BAR_OID); + test5X2ModifyDisable(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test514ModifyOrgScummBarEnable() throws Exception { - test5X4ModifyEnable("test514ModifyOrgScummBarEnable", OrgType.class, ORG_SCUMM_BAR_OID); + test5X4ModifyEnable(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test515OrgScummBarRecompute() throws Exception { - test5X5Recompute("test515OrgScummBarRecompute", OrgType.class, ORG_SCUMM_BAR_OID); + test5X5Recompute(OrgType.class, ORG_SCUMM_BAR_OID); } - @Test public void test520CheckSerivceSeaMonkeyInitial() throws Exception { - test5X0CheckInitial("test520CheckSerivceSeaMonkeyInitial", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X0CheckInitial(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test521SerivceSeaMonkeyRecompute() throws Exception { - test5X1Recompute("test521SerivceSeaMonkeyRecompute", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X1Recompute(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test522ModifySerivceSeaMonkeyDisable() throws Exception { - test5X2ModifyDisable("test522ModifySerivceSeaMonkeyDisable", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X2ModifyDisable(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test524ModifySerivceSeaMonkeyEnable() throws Exception { - test5X4ModifyEnable("test524ModifySerivceSeaMonkeyEnable", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X4ModifyEnable(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test525SerivceSeaMonkeyRecompute() throws Exception { - test5X5Recompute("test525SerivceSeaMonkeyRecompute", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X5Recompute(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } - private void test5X0CheckInitial(final String TEST_NAME, Class type, String oid) throws Exception { + private void test5X0CheckInitial(Class type, String oid) throws Exception { // GIVEN, WHEN // this happens during test initialization when the role is added @@ -2432,18 +2323,18 @@ private void test5X0CheckInitial(final String TEST_NAME, C * Make sure that recompute properly updates the effective status. * MID-2877 */ - private void test5X1Recompute(final String TEST_NAME, Class type, String oid) throws Exception { + private void test5X1Recompute(Class type, String oid) throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - // WHEN + when(); modelService.recompute(type, oid, null, task, result); - // THEN + then(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2458,19 +2349,18 @@ private void test5X1Recompute(final String TEST_NAME, Clas /** * MID-2877 */ - private void test5X2ModifyDisable(final String TEST_NAME, Class type, String oid) throws Exception { - - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + private void test5X2ModifyDisable(Class type, String oid) throws Exception { + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - // WHEN + when(); modifyObjectReplaceProperty(type, oid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - // THEN + then(); XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2489,19 +2379,17 @@ private void test5X2ModifyDisable(final String TEST_NAME, /** * MID-2877 */ - private void test5X4ModifyEnable(final String TEST_NAME, Class type, String oid) throws Exception { - - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + private void test5X4ModifyEnable(Class type, String oid) throws Exception { + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); - XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - // WHEN + when(); modifyObjectReplaceProperty(type, oid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - // THEN + then(); XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2520,18 +2408,17 @@ private void test5X4ModifyEnable(final String TEST_NAME, C /** * Make sure that recompute does not destroy anything. */ - public void test5X5Recompute(final String TEST_NAME, Class type, String oid) throws Exception { - - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + public void test5X5Recompute(Class type, String oid) throws Exception { + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - // WHEN + when(); modelService.recompute(type, oid, null, task, result); - // THEN + then(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2550,8 +2437,6 @@ public void test5X5Recompute(final String TEST_NAME, Class // attempt to simulate MID-3348 (unsuccessful for now) @Test public void test600AddUser1() throws Exception { - final String TEST_NAME = "test600AddUser1"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2595,12 +2480,10 @@ private void checkSuspendedAttribute(DummyAccount dummyAccount, Boolean expected @Test public void test610EnableUser1() throws Exception { - final String TEST_NAME = "test610EnableUser1"; - // GIVEN PrismObject user1 = findUserByUsername("user1"); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); Collection> deltas = @@ -2631,10 +2514,8 @@ public void test610EnableUser1() throws Exception { */ @Test public void test700ModifyJackRemoveAdministrativeStatus() throws Exception { - final String TEST_NAME = "test700ModifyJackRemoveAdministrativeStatus"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2682,10 +2563,8 @@ public void test700ModifyJackRemoveAdministrativeStatus() throws Exception { */ @Test public void test702ModifyJackFuneralTimestampBeforeNow() throws Exception { - final String TEST_NAME = "test702ModifyJackFuneralTimestampBeforeNow"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2727,10 +2606,8 @@ public void test702ModifyJackFuneralTimestampBeforeNow() throws Exception { */ @Test public void test704ModifyJackFuneralTimestampAfterNow() throws Exception { - final String TEST_NAME = "test704ModifyJackFuneralTimestampAfterNow"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2768,10 +2645,8 @@ public void test704ModifyJackFuneralTimestampAfterNow() throws Exception { */ @Test public void test750AddAndDeleteUserWithPrecreate() throws Exception { - final String TEST_NAME = "test750AddAndDeleteUserWithPrecreate"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2785,12 +2660,12 @@ public void test750AddAndDeleteUserWithPrecreate() throws Exception { UserType user = new UserType(prismContext) .name("test750") .beginAssignment() - .beginConstruction() - .resourceRef(RESOURCE_DUMMY_PRECREATE.oid, ResourceType.COMPLEX_TYPE) - .end() + .beginConstruction() + .resourceRef(RESOURCE_DUMMY_PRECREATE.oid, ResourceType.COMPLEX_TYPE) + .end() .end() .beginActivation() - .validFrom(yesterday) + .validFrom(yesterday) .end(); String oid = addObject(user.asPrismObject(), task, result); assertSuccess(result); @@ -2813,8 +2688,8 @@ private void assertDummyActivationEnabledState(String userId, Boolean expectedEn private void assertDummyActivationEnabledState(String instance, String userId, Boolean expectedEnabled) throws SchemaViolationException, ConflictException, InterruptedException { DummyAccount account = getDummyAccount(instance, userId); - assertNotNull("No dummy account "+userId, account); - assertEquals("Wrong enabled flag in dummy '"+instance+"' account "+userId, expectedEnabled, account.isEnabled()); + assertNotNull("No dummy account " + userId, account); + assertEquals("Wrong enabled flag in dummy '" + instance + "' account " + userId, expectedEnabled, account.isEnabled()); } private void assertDummyEnabled(String userId) throws SchemaViolationException, ConflictException, InterruptedException { @@ -2835,35 +2710,35 @@ private void assertDummyDisabled(String instance, String userId) throws SchemaVi private void assertValidity(PrismObject focus, TimeIntervalStatusType expectedValidityStatus) { ActivationType activation = focus.asObjectable().getActivation(); - assertNotNull("No activation in "+focus, activation); - assertEquals("Unexpected validity status in "+focus, expectedValidityStatus, activation.getValidityStatus()); + assertNotNull("No activation in " + focus, activation); + assertEquals("Unexpected validity status in " + focus, expectedValidityStatus, activation.getValidityStatus()); } private void assertValidityTimestamp(PrismObject user, long expected) { ActivationType activation = user.asObjectable().getActivation(); - assertNotNull("No activation in "+user, activation); + assertNotNull("No activation in " + user, activation); XMLGregorianCalendar validityChangeTimestamp = activation.getValidityChangeTimestamp(); - assertNotNull("No validityChangeTimestamp in "+user, validityChangeTimestamp); + assertNotNull("No validityChangeTimestamp in " + user, validityChangeTimestamp); assertEquals("wrong validityChangeTimestamp", expected, XmlTypeConverter.toMillis(validityChangeTimestamp)); } private void assertValidityTimestamp(PrismObject user, XMLGregorianCalendar expected) { ActivationType activation = user.asObjectable().getActivation(); - assertNotNull("No activation in "+user, activation); + assertNotNull("No activation in " + user, activation); XMLGregorianCalendar validityChangeTimestamp = activation.getValidityChangeTimestamp(); - assertNotNull("No validityChangeTimestamp in "+user, validityChangeTimestamp); + assertNotNull("No validityChangeTimestamp in " + user, validityChangeTimestamp); assertEquals("wrong validityChangeTimestamp", expected, validityChangeTimestamp); } private void assertValidityTimestamp(PrismObject user, long lowerBound, long upperBound) { ActivationType activation = user.asObjectable().getActivation(); - assertNotNull("No activation in "+user, activation); + assertNotNull("No activation in " + user, activation); XMLGregorianCalendar validityChangeTimestamp = activation.getValidityChangeTimestamp(); - assertNotNull("No validityChangeTimestamp in "+user, validityChangeTimestamp); + assertNotNull("No validityChangeTimestamp in " + user, validityChangeTimestamp); long validityMillis = XmlTypeConverter.toMillis(validityChangeTimestamp); if (validityMillis >= lowerBound && validityMillis <= upperBound) { return; } - AssertJUnit.fail("Expected validityChangeTimestamp to be between "+lowerBound+" and "+upperBound+", but it was "+validityMillis); + AssertJUnit.fail("Expected validityChangeTimestamp to be between " + lowerBound + " and " + upperBound + ", but it was " + validityMillis); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java index 630832a6d11..6ce6c305a6b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java @@ -7,7 +7,6 @@ package com.evolveum.midpoint.model.intest; import com.evolveum.icf.dummy.resource.DummyGroup; -import com.evolveum.midpoint.model.intest.rbac.TestRbac; import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; @@ -74,7 +73,7 @@ public class TestCaseIgnore extends AbstractInitializedModelIntegrationTest { private static final String GROUP_DUMMY_FOOLS_NAME = "FoOlS"; - @Autowired(required = true) + @Autowired protected MatchingRuleRegistry matchingRuleRegistry; private MatchingRule caseIgnoreMatchingRule; @@ -100,17 +99,13 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test000Sanity() throws Exception { - final String TEST_NAME="test000Sanity"; - assertShadows(5); } @Test public void test131ModifyUserJackAssignAccount() throws Exception { - final String TEST_NAME="test131ModifyUserJackAssignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_UPCASE_OID, null, true); @@ -159,11 +154,9 @@ public void test131ModifyUserJackAssignAccount() throws Exception { } @Test - public void test133SeachAccountShadows() throws Exception { - final String TEST_NAME="test133SeachAccountShadows"; - + public void test133SearchAccountShadows() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_UPCASE_OID, @@ -213,10 +206,8 @@ public void test133SeachAccountShadows() throws Exception { @Test public void test139ModifyUserJackUnassignAccount() throws Exception { - final String TEST_NAME = "test139ModifyUserJackUnassignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); @@ -252,9 +243,7 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { @Test public void test150JackAssignRoleX() throws Exception { - final String TEST_NAME = "test150JackAssignRoleX"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -298,9 +287,7 @@ public void test150JackAssignRoleX() throws Exception { @Test public void test152GetJack() throws Exception { - final String TEST_NAME = "test152GetJack"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -339,9 +326,7 @@ public void test152GetJack() throws Exception { @Test public void test159JackUnAssignRoleX() throws Exception { - final String TEST_NAME = "test159JackUnAssignRoleX"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -370,9 +355,7 @@ public void test159JackUnAssignRoleX() throws Exception { @Test public void test160JackAssignRoleBasic() throws Exception { - final String TEST_NAME = "test160JackAssignRoleBasic"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -418,9 +401,7 @@ public void test160JackAssignRoleBasic() throws Exception { @Test public void test161JackAssignRoleJoker() throws Exception { - final String TEST_NAME = "test161JackAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -470,9 +451,7 @@ public void test161JackAssignRoleJoker() throws Exception { @Test public void test165JackUnAssignRoleJoker() throws Exception { - final String TEST_NAME = "test165JackUnAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -518,9 +497,7 @@ public void test165JackUnAssignRoleJoker() throws Exception { @Test public void test169JackUnAssignRoleBasic() throws Exception { - final String TEST_NAME = "test169JackUnAssignRoleBasic"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -552,9 +529,7 @@ public void test169JackUnAssignRoleBasic() throws Exception { @Test public void test170JackAssignRoleJoker() throws Exception { - final String TEST_NAME = "test170JackAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -599,9 +574,7 @@ public void test170JackAssignRoleJoker() throws Exception { @Test public void test179JackUnAssignRoleJoker() throws Exception { - final String TEST_NAME = "test179JackUnAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -641,9 +614,7 @@ public void test179JackUnAssignRoleJoker() throws Exception { */ @Test public void test200GuybrushAssignRoleFools() throws Exception { - final String TEST_NAME = "test200GuybrushAssignRoleFools"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertShadows(5); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java index b5a9d804ce5..0bbc07329ef 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java @@ -6,14 +6,11 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.util.Collection; import java.util.List; -import com.evolveum.midpoint.prism.delta.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -24,6 +21,9 @@ import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.delta.DiffUtil; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; @@ -31,14 +31,7 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; @@ -49,9 +42,8 @@ * fake dummy connector. Test upgrades and downgrades of connector version. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestConnectorDummyFake extends AbstractConfiguredModelIntegrationTest { @@ -85,8 +77,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010ListConnectors() throws Exception { - final String TEST_NAME = "test010ListConnectors"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -100,7 +90,7 @@ public void test010ListConnectors() throws Exception { TestUtil.assertSuccess("getObject result", result); assertEquals("Unexpected number of connectors", 12, connectors.size()); - for(PrismObject connector: connectors) { + for (PrismObject connector : connectors) { display("Connector", connector); ConnectorType connectorType = connector.asObjectable(); if (CONNECTOR_DUMMY_TYPE.equals(connectorType.getConnectorType())) { @@ -122,8 +112,6 @@ public void test010ListConnectors() throws Exception { @Test public void test020ImportFakeResource() throws Exception { - final String TEST_NAME = "test020ImportFakeResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -146,24 +134,19 @@ public void test020ImportFakeResource() throws Exception { @Test public void test021TestFakeResource() throws Exception { - final String TEST_NAME = "test021TestFakeResource"; - // GIVEN Task task = getTestTask(); - OperationResult result = task.getResult(); // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_FAKE_OID, task); // THEN - display("testResource result", testResult); + display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } @Test public void test022ListAccountsFakeResource() throws Exception { - final String TEST_NAME = "test022ListAccountsFakeResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -173,16 +156,14 @@ public void test022ListAccountsFakeResource() throws Exception { // THEN result.computeStatus(); - display("listAccounts result", result); + display("listAccounts result", result); TestUtil.assertSuccess("listAccounts result", result); - assertEquals("Unexpected number of accounts: "+accounts, 1, accounts.size()); + assertEquals("Unexpected number of accounts: " + accounts, 1, accounts.size()); } @Test public void test030ImportDummyResource() throws Exception { - final String TEST_NAME = "test030ImportDummyResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -205,24 +186,19 @@ public void test030ImportDummyResource() throws Exception { @Test public void test031TestDummyResource() throws Exception { - final String TEST_NAME = "test031TestDummyResource"; - // GIVEN Task task = getTestTask(); - OperationResult result = task.getResult(); // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); // THEN - display("testResource result", testResult); + display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } @Test public void test032ListAccountsDummyResource() throws Exception { - final String TEST_NAME = "test032ListAccountsDummyResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -233,7 +209,7 @@ public void test032ListAccountsDummyResource() throws Exception { // THEN assertSuccess(result); - assertEquals("Unexpected number of accounts: "+accounts, 3, accounts.size()); + assertEquals("Unexpected number of accounts: " + accounts, 3, accounts.size()); } /** @@ -242,8 +218,6 @@ public void test032ListAccountsDummyResource() throws Exception { */ @Test public void test100UpgradeModelAddDelete() throws Exception { - final String TEST_NAME = "test100UpgradeModelAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -270,14 +244,11 @@ public void test100UpgradeModelAddDelete() throws Exception { // THEN assertSuccess(result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test150DowngradeModelAddDelete() throws Exception { - final String TEST_NAME = "test150DowngradeModelAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -305,8 +276,6 @@ public void test150DowngradeModelAddDelete() throws Exception { @Test public void test200UpgradeModelReplace() throws Exception { - final String TEST_NAME = "test200UpgradeModelReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -326,14 +295,11 @@ public void test200UpgradeModelReplace() throws Exception { // THEN assertSuccess("executeChanges result", result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test250DowngradeModelReplace() throws Exception { - final String TEST_NAME = "test250DowngradeModelReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -358,8 +324,6 @@ public void test250DowngradeModelReplace() throws Exception { @Test public void test300UpgradeRawAddDelete() throws Exception { - final String TEST_NAME = "test300UpgradeRawAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -384,14 +348,11 @@ public void test300UpgradeRawAddDelete() throws Exception { // THEN assertSuccess(result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test350DowngradeRawAddDelete() throws Exception { - final String TEST_NAME = "test350DowngradeRawAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -416,7 +377,7 @@ public void test350DowngradeRawAddDelete() throws Exception { // THEN result.computeStatus(); - display("executeChanges result", result); + display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); assertDowngrade(dummyResourceModelBefore); @@ -424,8 +385,6 @@ public void test350DowngradeRawAddDelete() throws Exception { @Test public void test400UpgradeRawReplace() throws Exception { - final String TEST_NAME = "test400UpgradeRawReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -447,17 +406,14 @@ public void test400UpgradeRawReplace() throws Exception { // THEN result.computeStatus(); - display("executeChanges result", result); + display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test450DowngradeRawReplace() throws Exception { - final String TEST_NAME = "test450DowngradeRawReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -482,8 +438,8 @@ public void test450DowngradeRawReplace() throws Exception { assertDowngrade(dummyResourceModelBefore); } - private void assertUpgrade(final String TEST_NAME, PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { - Task task = taskManager.createTaskInstance(TestConnectorDummyFake.class.getName() + ".assertUpgrade"); + private void assertUpgrade(PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { + Task task = createPlainTask("assertUpgrade"); OperationResult result = task.getResult(); // Check if the changes went well in the repo @@ -494,7 +450,7 @@ private void assertUpgrade(final String TEST_NAME, PrismObject dum assertEquals("Wrong connectorRef in fake resource (repo)", connectorDummyOid, repoResource.asObjectable().getConnectorRef().getOid()); - display("HEREHERE: "+TEST_NAME); + displayHEREHERE(); // Check if resource view of the model has changed as well resourceDummyFake = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, null, task, result); display("Upgraded fake resource (model)", resourceDummyFake); @@ -511,9 +467,9 @@ private void assertUpgrade(final String TEST_NAME, PrismObject dum dummyResourceModelAfter.asObjectable().setFetchResult(null); ObjectDelta dummyResourceDiff = DiffUtil.diff(dummyResourceModelBefore, dummyResourceModelAfter); display("Dummy resource diff", dummyResourceDiff); - assertTrue("Ha! Someone touched the other resource! Off with his head! diff:"+dummyResourceDiff, dummyResourceDiff.isEmpty()); + assertTrue("Ha! Someone touched the other resource! Off with his head! diff:" + dummyResourceDiff, dummyResourceDiff.isEmpty()); - testResources(3,3); + testResources(3, 3); } private void assertDowngrade(PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { @@ -541,9 +497,9 @@ private void assertDowngrade(PrismObject dummyResourceModelBefore) dummyResourceModelAfter.asObjectable().setFetchResult(null); ObjectDelta dummyResourceDiff = DiffUtil.diff(dummyResourceModelBefore, dummyResourceModelAfter); display("Dummy resource diff", dummyResourceDiff); - assertTrue("Ha! Someone touched the other resource! Off with his head! diff:"+dummyResourceDiff, dummyResourceDiff.isEmpty()); + assertTrue("Ha! Someone touched the other resource! Off with his head! diff:" + dummyResourceDiff, dummyResourceDiff.isEmpty()); - testResources(3,1); + testResources(3, 1); } private void testResources(int numDummyAccounts, int numFakeAccounts) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { @@ -553,11 +509,11 @@ private void testResources(int numDummyAccounts, int numFakeAccounts) throws Obj purgeResourceSchema(RESOURCE_DUMMY_FAKE_OID); OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_FAKE_OID, task); - display("testResource fake result", testResult); + display("testResource fake result", testResult); TestUtil.assertSuccess("testResource fake result", testResult); testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); - display("testResource dummy result", testResult); + display("testResource dummy result", testResult); TestUtil.assertSuccess("testResource dummy result", testResult); assertResourceAccounts(resourceDummy, numDummyAccounts); @@ -573,12 +529,10 @@ private void assertResourceAccounts(PrismObject resource, int numA // THEN result.computeStatus(); - display("listAccounts result "+resource, result); - TestUtil.assertSuccess("listAccounts result "+resource, result); + display("listAccounts result " + resource, result); + TestUtil.assertSuccess("listAccounts result " + resource, result); - assertEquals("Unexpected number of accounts on "+resource+": "+accounts, numAccounts, accounts.size()); + assertEquals("Unexpected number of accounts on " + resource + ": " + accounts, numAccounts, accounts.size()); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java index a328bd9bbec..5605002acb8 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java @@ -61,90 +61,91 @@ private enum ResourceObjectOperation { KEEP, DELETE } private ObjectClassComplexTypeDefinition getAccountObjectClassDefinition() throws SchemaException { ResourceSchema schema = RefinedResourceSchemaImpl.getResourceSchema(getDummyResourceObject(), prismContext); + assertNotNull(schema); return schema.findObjectClassDefinition(dummyResourceCtl.getAccountObjectClassQName()); } @Test public void test100Reconcile_Keep_Keep() throws Exception { - executeTest("test100Reconcile_Keep_Keep", FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test110Recompute_Keep_Keep() throws Exception { - executeTest("test110Recompute_Keep_Keep", FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test120Reconcile_Unlink_Keep() throws Exception { - executeTest("test120Reconcile_Unlink_Keep", FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test130Recompute_Unlink_Keep() throws Exception { - executeTest("test130Recompute_Unlink_Keep", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test140Reconcile_UnlinkTombstone_Keep() throws Exception { - executeTest("test140Reconcile_UnlinkTombstone_Keep", FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test150Recompute_UnlinkTombstone_Keep() throws Exception { - executeTest("test150Recompute_UnlinkTombstone_Keep", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test160Reconcile_Delete_Keep() throws Exception { - executeTest("test160Reconcile_Delete_Keep", FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } @Test public void test170Recompute_Delete_Keep() throws Exception { - executeTest("test170Recompute_Delete_Keep", FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } @Test public void test200Reconcile_Keep_Delete() throws Exception { - executeTest("test200Reconcile_Keep_Delete", FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test210Recompute_Keep_Delete() throws Exception { - executeTest("test210Recompute_Keep_Delete", FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test220Reconcile_Unlink_Delete() throws Exception { - executeTest("test220Reconcile_Unlink_Delete", FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test230Recompute_Unlink_Delete() throws Exception { - executeTest("test230Recompute_Unlink_Delete", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test240Reconcile_UnlinkTombstone_Delete() throws Exception { - executeTest("test240Reconcile_UnlinkTombstone_Delete", FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test250Recompute_UnlinkTombstone_Delete() throws Exception { - executeTest("test250Recompute_UnlinkTombstone_Delete", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test260Reconcile_Delete_Delete() throws Exception { - executeTest("test260Reconcile_Delete_Delete", FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } @Test public void test270Recompute_Delete_Delete() throws Exception { - executeTest("test270Recompute_Delete_Delete", FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } - private void executeTest(final String TEST_NAME, FocusOperation focusOperation, ShadowOperation shadowOperation, + private void executeTest(FocusOperation focusOperation, ShadowOperation shadowOperation, ResourceObjectOperation resourceObjectOperation) throws Exception { // GIVEN @@ -162,7 +163,6 @@ private void executeTest(final String TEST_NAME, FocusOperation focusOperation, display("Shadow", shadowBefore); if (shadowOperation != ShadowOperation.KEEP) { - @SuppressWarnings("unchecked") ObjectDelta removeLinkRefDelta = deltaFor(UserType.class) .item(UserType.F_LINK_REF).replace() .asObjectDelta(USER_JACK_OID); @@ -175,7 +175,6 @@ private void executeTest(final String TEST_NAME, FocusOperation focusOperation, assertNoObject(ShadowType.class, shadowBefore.getOid()); } else { if (shadowOperation == ShadowOperation.UNLINK_AND_TOMBSTONE) { - @SuppressWarnings("unchecked") ObjectDelta markAsDead = deltaFor(ShadowType.class) .item(ShadowType.F_DEAD).replace(Boolean.TRUE) .item(ShadowType.F_EXISTS).replace(Boolean.FALSE) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java index f7a5873256f..af8ee29620d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java @@ -7,7 +7,6 @@ package com.evolveum.midpoint.model.intest; import java.io.File; - import javax.xml.datatype.XMLGregorianCalendar; import org.springframework.test.annotation.DirtiesContext; @@ -15,7 +14,6 @@ import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; -import com.evolveum.midpoint.model.intest.sync.TestValidityRecomputeTask; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismTestUtil; @@ -25,21 +23,16 @@ import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Test for deputy (delegation) mechanism. - * + *

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

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

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

* Create account operation should fail, account should be synchronized back to repo (creating the user!), and * model should clean it up somehow... */ @Test public void test260JupiterConflictNoShadowSyncBack() throws Exception { - final String TEST_NAME = "test260JupiterConflictNoShadowSyncBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -657,7 +605,6 @@ public void test260JupiterConflictNoShadowSyncBack() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, USER_JUPITER_NAME); // jupiter getDummyResource(RESOURCE_DUMMY_FUCHSIA_NAME).addAccount(account); - Collection> deltas = new ArrayList<>(); PrismObject userJupiter = PrismTestUtil.parseObject(USER_JUPITER_FILE); // WHEN @@ -688,23 +635,19 @@ public void test260JupiterConflictNoShadowSyncBack() throws Exception { // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } // remove the assignment, shadow and account to prepare for following tests @Test public void test262JupiterCleanup() throws Exception { - final String TEST_NAME = "test262JupiterCleanup"; - cleanUpJupiter(TEST_NAME); + cleanUpJupiter(); } - protected void cleanUpJupiter(String TEST_NAME) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, SchemaViolationException, ConflictException, InterruptedException { + protected void cleanUpJupiter() + throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException, SchemaViolationException, + ConflictException, InterruptedException { // GIVEN Task task = getTestTask(); @@ -730,13 +673,6 @@ protected void cleanUpJupiter(String TEST_NAME) throws SchemaException, ObjectAl // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } /** @@ -744,8 +680,6 @@ protected void cleanUpJupiter(String TEST_NAME) throws SchemaException, ObjectAl */ @Test public void test264JupiterConflictNoShadowSyncBackSeparate() throws Exception { - final String TEST_NAME = "test264JupiterConflictNoShadowSyncBackSeparate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -787,20 +721,12 @@ public void test264JupiterConflictNoShadowSyncBackSeparate() throws Exception { // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } // remove the assignment, shadow and account to prepare for following tests @Test public void test266JupiterCleanupAgain() throws Exception { - final String TEST_NAME = "test266JupiterCleanupAgain"; - cleanUpJupiter(TEST_NAME); + cleanUpJupiter(); } /** @@ -809,8 +735,6 @@ public void test266JupiterCleanupAgain() throws Exception { */ @Test public void test270JupiterConflictOtherNoShadowSyncBack() throws Exception { - final String TEST_NAME = "test270JupiterConflictOtherNoShadowSyncBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -872,13 +796,6 @@ public void test270JupiterConflictOtherNoShadowSyncBack() throws Exception { // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } private void assertUserJupiter(PrismObject user) { @@ -890,8 +807,6 @@ private void assertUserJupiter(PrismObject user) { */ @Test public void test280RenameBobNoShadow() throws Exception { - final String TEST_NAME = "test280RenameBobNoShadow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -950,8 +865,6 @@ public void test280RenameBobNoShadow() throws Exception { */ @Test public void test282RenamePeterNoShadowSync() throws Exception { - final String TEST_NAME = "test282RenamePeterNoShadowSync"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1026,8 +939,6 @@ public void test282RenamePeterNoShadowSync() throws Exception { // as with jupiter, but ADD instead of ASSIGN account @Test public void test290AlfredConflictNoShadowSyncBackAdd() throws Exception { - final String TEST_NAME = "test290AlfredConflictNoShadowSyncBackAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1039,7 +950,6 @@ public void test290AlfredConflictNoShadowSyncBackAdd() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, "alfred"); getDummyResource(RESOURCE_DUMMY_FUCHSIA_NAME).addAccount(account); - Collection> deltas = new ArrayList<>(); PrismObject userAlfred = PrismTestUtil.parseObject(USER_ALFRED_FILE); PrismObject accountAlfred = PrismTestUtil.parseObject(ACCOUNT_ALFRED_FILE); ObjectReferenceType linkRef = new ObjectReferenceType(); @@ -1073,12 +983,8 @@ public void test290AlfredConflictNoShadowSyncBackAdd() throws Exception { assertDummyAccount(RESOURCE_DUMMY_FUCHSIA_NAME, "Alfred Hitchcock", null, true); } - - @Test public void test300JackAssignAccountDummyVioletConflicting() throws Exception { - final String TEST_NAME = "test300JackAssignAccountDummyVioletConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1143,8 +1049,6 @@ public void test300JackAssignAccountDummyVioletConflicting() throws Exception { @Test public void test350GuybrushAssignAccountDummyViolet() throws Exception { - final String TEST_NAME = "test350GuybrushAssignAccountDummyViolet"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1199,8 +1103,6 @@ public void test350GuybrushAssignAccountDummyViolet() throws Exception { @Test public void test360HermanAssignAccountDummyViolet() throws Exception { - final String TEST_NAME = "test360HermanAssignAccountDummyViolet"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1258,8 +1160,6 @@ public void test360HermanAssignAccountDummyViolet() throws Exception { @Test public void test400RenameAngelicaConflicting() throws Exception { - final String TEST_NAME = "test400RenameAngelicaConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1282,7 +1182,7 @@ public void test400RenameAngelicaConflicting() throws Exception { // THEN assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME, null, true); - assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME+"1", "Angelica", true); + assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME + "1", "Angelica", true); assertNoDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_ANGELICA_NAME); } @@ -1291,8 +1191,6 @@ public void test400RenameAngelicaConflicting() throws Exception { */ @Test public void test500JackAssignAccountDummyMagenta() throws Exception { - final String TEST_NAME = "test500JackAssignAccountDummyMagenta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1359,8 +1257,6 @@ public void test500JackAssignAccountDummyMagenta() throws Exception { */ @Test public void test510DrakeAssignAccountDummyMagenta() throws Exception { - final String TEST_NAME = "test510DrakeAssignAccountDummyMagenta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1438,8 +1334,6 @@ public void test510DrakeAssignAccountDummyMagenta() throws Exception { */ @Test public void test520DrakeModifyLocality() throws Exception { - final String TEST_NAME = "test520DrakeModifyLocality"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1502,8 +1396,6 @@ public void test520DrakeModifyLocality() throws Exception { */ @Test public void test530GuybrushAssignAccountDummyMagenta() throws Exception { - final String TEST_NAME = "test530GuybrushAssignAccountDummyMagenta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1568,8 +1460,6 @@ public void test530GuybrushAssignAccountDummyMagenta() throws Exception { */ @Test public void test532GuybrushModifyDescription() throws Exception { - final String TEST_NAME = "test532GuybrushModifyDescription"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1610,9 +1500,9 @@ public void test532GuybrushModifyDescription() throws Exception { // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); // Renamed - assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME+ "001", "Guybrush Threepwood", true); + assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME + "001", "Guybrush Threepwood", true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME+ "001", + assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME + "001", DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, DESCRIPTION_RUM + " -- Guybrush Threepwood"); PrismAsserts.assertPropertyValue(userGuybrush, UserType.F_ORGANIZATION, @@ -1631,8 +1521,6 @@ public void test532GuybrushModifyDescription() throws Exception { @Test public void test600JackRename() throws Exception { - final String TEST_NAME = "test600JackRename"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1692,8 +1580,6 @@ public void test600JackRename() throws Exception { @Test public void test700DarkVioletSyncTask() throws Exception { - final String TEST_NAME = "test700DarkVioletSyncTask"; - // WHEN importObjectFromFile(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_FILE); @@ -1706,8 +1592,6 @@ public void test700DarkVioletSyncTask() throws Exception { */ @Test public void test710DarkVioletAddLeChuck() throws Exception { - final String TEST_NAME = "test710DarkVioletAddLeChuck"; - // GIVEN dummyAuditService.clear(); @@ -1733,8 +1617,6 @@ public void test710DarkVioletAddLeChuck() throws Exception { */ @Test public void test712DarkVioletAddCharles() throws Exception { - final String TEST_NAME = "test712DarkVioletAddCharles"; - // GIVEN dummyAuditService.clear(); @@ -1753,7 +1635,7 @@ public void test712DarkVioletAddCharles() throws Exception { // THEN then(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); + assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".1"); } /* @@ -1761,8 +1643,6 @@ public void test712DarkVioletAddCharles() throws Exception { */ @Test public void test714DarkVioletAddShinetop() throws Exception { - final String TEST_NAME = "test714DarkVioletAddShinetop"; - // GIVEN dummyAuditService.clear(); @@ -1782,14 +1662,12 @@ public void test714DarkVioletAddShinetop() throws Exception { // THEN then(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); - assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2", "Melee Island"); + assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".1"); + assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".2", "Melee Island"); } @Test public void test716DarkVioletDeleteCharles() throws Exception { - final String TEST_NAME = "test716DarkVioletDeleteCharles"; - // GIVEN dummyAuditService.clear(); @@ -1803,14 +1681,12 @@ public void test716DarkVioletDeleteCharles() throws Exception { // THEN then(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); - assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2", "Melee Island"); + assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME + ".1"); + assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".2", "Melee Island"); } @Test public void test720DarkVioletModifyShinetopLocation() throws Exception { - final String TEST_NAME = "test720DarkVioletModifyShinetopLocation"; - // GIVEN dummyAuditService.clear(); @@ -1827,14 +1703,12 @@ public void test720DarkVioletModifyShinetopLocation() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); - assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2", "Monkey Island"); + assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME + ".1"); + assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".2", "Monkey Island"); } @Test public void test722DarkVioletModifyShinetopFullName() throws Exception { - final String TEST_NAME = "test722DarkVioletModifyShinetopFullName"; - // GIVEN dummyAuditService.clear(); @@ -1851,9 +1725,9 @@ public void test722DarkVioletModifyShinetopFullName() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); + assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME + ".1"); assertUserNick(ACCOUNT_SHINETOP_USERNAME, CHUCKIE_FULLNAME, CHUCKIE_FULLNAME, "Monkey Island"); - assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2"); + assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME + ".2"); } /* @@ -1865,8 +1739,6 @@ public void test722DarkVioletModifyShinetopFullName() throws Exception { */ @Test public void test724DarkVioletAddLe_Chuck() throws Exception { - final String TEST_NAME = "test724DarkVioletAddLe_Chuck"; - // GIVEN dummyAuditService.clear(); @@ -1887,9 +1759,9 @@ public void test724DarkVioletAddLe_Chuck() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertUserNick(ACCOUNT_LE_CHUCK_USERNAME, LE_CHUCK_FULLNAME, LE_CHUCK_FULLNAME+".1", "Melee Island"); + assertUserNick(ACCOUNT_LE_CHUCK_USERNAME, LE_CHUCK_FULLNAME, LE_CHUCK_FULLNAME + ".1", "Melee Island"); assertUserNick(ACCOUNT_SHINETOP_USERNAME, CHUCKIE_FULLNAME, CHUCKIE_FULLNAME, "Monkey Island"); - assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2"); + assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME + ".2"); } /* @@ -1898,11 +1770,7 @@ public void test724DarkVioletAddLe_Chuck() throws Exception { */ @Test public void test730DarkVioletAddBarbossa() throws Exception { - final String TEST_NAME = "test730DarkVioletAddBarbossa"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount(USER_BARBOSSA_USERNAME); @@ -1919,7 +1787,7 @@ public void test730DarkVioletAddBarbossa() throws Exception { // THEN then(); - assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".1"); + assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME + ".1"); } /* @@ -1930,11 +1798,7 @@ public void test730DarkVioletAddBarbossa() throws Exception { */ @Test public void test732DarkVioletAddBarbossa() throws Exception { - final String TEST_NAME = "test732DarkVioletAddBarbossa"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount("YA" + USER_BARBOSSA_USERNAME); @@ -1951,14 +1815,12 @@ public void test732DarkVioletAddBarbossa() throws Exception { // THEN then(); - assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".1"); - assertUserNick("YA" + USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".4"); + assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME + ".1"); + assertUserNick("YA" + USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME + ".4"); } @Test public void test750DarkVioletAddMatusalem() throws Exception { - final String TEST_NAME = "test750DarkVioletAddMatusalem"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1990,11 +1852,7 @@ public void test750DarkVioletAddMatusalem() throws Exception { */ @Test public void test752DarkVioletAddDiplomatico() throws Exception { - final String TEST_NAME = "test752DarkVioletAddDiplomatico"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount(ACCOUNT_DIPLOMATICO_USERNAME); @@ -2016,7 +1874,7 @@ public void test752DarkVioletAddDiplomatico() throws Exception { assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); iterationTokenDiplomatico = lookupIterationTokenByAdditionalName(ACCOUNT_DIPLOMATICO_USERNAME); - assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenDiplomatico); } /* @@ -2024,11 +1882,7 @@ public void test752DarkVioletAddDiplomatico() throws Exception { */ @Test public void test754DarkVioletAddMilionario() throws Exception { - final String TEST_NAME = "test754DarkVioletAddMilionario"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount(ACCOUNT_MILLONARIO_USERNAME); @@ -2047,19 +1901,15 @@ public void test754DarkVioletAddMilionario() throws Exception { // THEN then(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenDiplomatico); iterationTokenMillonario = lookupIterationTokenByAdditionalName(ACCOUNT_MILLONARIO_USERNAME); - assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Peru"); + assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenMillonario, "Peru"); } @Test public void test756DarkVioletDeleteDiplomatico() throws Exception { - final String TEST_NAME = "test756DarkVioletDeleteDiplomatico"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN @@ -2072,17 +1922,13 @@ public void test756DarkVioletDeleteDiplomatico() throws Exception { // THEN then(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); - assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Peru"); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); + assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenMillonario, "Peru"); } @Test public void test760DarkVioletModifyMillonarioLocation() throws Exception { - final String TEST_NAME = "test760DarkVioletModifyMillonarioLocation"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_DARK_VIOLET_NAME).getAccountByUsername(ACCOUNT_MILLONARIO_USERNAME); @@ -2098,8 +1944,8 @@ public void test760DarkVioletModifyMillonarioLocation() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); - assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Northern Peru"); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); + assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenMillonario, "Northern Peru"); } /** @@ -2107,11 +1953,7 @@ public void test760DarkVioletModifyMillonarioLocation() throws Exception { */ @Test public void test762DarkVioletModifyMillonarioFullName() throws Exception { - final String TEST_NAME = "test762DarkVioletModifyMillonarioFullName"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_DARK_VIOLET_NAME).getAccountByUsername(ACCOUNT_MILLONARIO_USERNAME); @@ -2127,9 +1969,9 @@ public void test762DarkVioletModifyMillonarioFullName() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RON_FULLNAME, RON_FULLNAME, "Northern Peru"); - assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario); + assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME + iterationTokenMillonario); } /** @@ -2137,11 +1979,7 @@ public void test762DarkVioletModifyMillonarioFullName() throws Exception { */ @Test public void test764DarkVioletModifyMatusalemFullName() throws Exception { - final String TEST_NAME = "test764DarkVioletModifyMatusalemFullName"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_DARK_VIOLET_NAME).getAccountByUsername(ACCOUNT_MATUSALEM_USERNAME); @@ -2156,22 +1994,19 @@ public void test764DarkVioletModifyMatusalemFullName() throws Exception { // THEN then(); displayAllUsers(); - assertNoUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); + assertNoUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME); String iterationTokenMatusalem = lookupIterationTokenByAdditionalName(ACCOUNT_MATUSALEM_USERNAME); - assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RON_FULLNAME, RON_FULLNAME+iterationTokenMatusalem); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RON_FULLNAME, RON_FULLNAME + iterationTokenMatusalem); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RON_FULLNAME, RON_FULLNAME, "Northern Peru"); - assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario); + assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME + iterationTokenMillonario); } - /** * MID-2887 */ @Test - public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { - final String TEST_NAME = "test800UniqeEmailAddUserAlfredoFettucini"; - + public void test800UniqueEmailAddUserAlfredoFettucini() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2179,8 +2014,9 @@ public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_ITERATION_UNIQUE_EMAIL_OID); - PrismObject user = createUser(USER_ALFREDO_FETTUCINI_USERNAME, USER_ALFREDO_FETTUCINI_GIVEN_NAME, USER_ALFREDO_FETTUCINI_FAMILY_NAME, - USER_FETTUCINI_NICKNAME, true); + PrismObject user = createUser( + USER_ALFREDO_FETTUCINI_USERNAME, USER_ALFREDO_FETTUCINI_GIVEN_NAME, + USER_ALFREDO_FETTUCINI_FAMILY_NAME, USER_FETTUCINI_NICKNAME, true); // WHEN when(); @@ -2197,18 +2033,16 @@ public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { USER_ALFREDO_FETTUCINI_GIVEN_NAME + " " + USER_ALFREDO_FETTUCINI_FAMILY_NAME, USER_ALFREDO_FETTUCINI_GIVEN_NAME, USER_ALFREDO_FETTUCINI_FAMILY_NAME); - PrismAsserts.assertEqualsPolyString("Wrong "+user+" nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); + PrismAsserts.assertEqualsPolyString("Wrong " + user + " nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); - assertEquals("Wrong "+user+" emailAddress", USER_FETTUCINI_NICKNAME + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); + assertEquals("Wrong " + user + " emailAddress", USER_FETTUCINI_NICKNAME + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); } /** * MID-2887 */ @Test - public void test802UniqeEmailAddUserBillFettucini() throws Exception { - final String TEST_NAME = "test802UniqeEmailAddUserBillFettucini"; - + public void test802UniqueEmailAddUserBillFettucini() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2233,9 +2067,9 @@ public void test802UniqeEmailAddUserBillFettucini() throws Exception { USER_BILL_FETTUCINI_GIVEN_NAME + " " + USER_BILL_FETTUCINI_FAMILY_NAME, USER_BILL_FETTUCINI_GIVEN_NAME, USER_BILL_FETTUCINI_FAMILY_NAME); - PrismAsserts.assertEqualsPolyString("Wrong "+user+" nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); + PrismAsserts.assertEqualsPolyString("Wrong " + user + " nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); - assertEquals("Wrong "+user+" emailAddress", USER_FETTUCINI_NICKNAME + ".1" + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); + assertEquals("Wrong " + user + " emailAddress", USER_FETTUCINI_NICKNAME + ".1" + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); } /** @@ -2243,8 +2077,6 @@ public void test802UniqeEmailAddUserBillFettucini() throws Exception { */ @Test public void test820SubtypeSetByInbound() throws Exception { - final String TEST_NAME = "test820SubtypeSetByInbound"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2304,22 +2136,24 @@ private void assertUserNick(String accountName, String accountFullName, String e private void assertUserNick(String accountName, String accountFullName, String expectedUserName, String expectedLocality) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(expectedUserName); - assertNotNull("No user for "+accountName+" ("+expectedUserName+")", user); - display("Created user for "+accountName, user); - assertEquals("Wrong nickname in user created for "+accountName, accountFullName, user.asObjectable().getNickName().getOrig()); - assertEquals("Wrong additionalName in user created for "+accountName, accountName, user.asObjectable().getAdditionalName().getOrig()); + assertNotNull("No user for " + accountName + " (" + expectedUserName + ")", user); + display("Created user for " + accountName, user); + assertEquals("Wrong nickname in user created for " + accountName, accountFullName, user.asObjectable().getNickName().getOrig()); + assertEquals("Wrong additionalName in user created for " + accountName, accountName, user.asObjectable().getAdditionalName().getOrig()); PolyStringType locality = user.asObjectable().getLocality(); if (locality == null) { - assertEquals("Wrong locality in user created for "+accountName, expectedLocality, null); + assertNull("Wrong locality in user created for " + accountName, expectedLocality); } else { - assertEquals("Wrong locality in user created for "+accountName, expectedLocality, locality.getOrig()); + assertEquals("Wrong locality in user created for " + accountName, expectedLocality, locality.getOrig()); } } - private void assertNoUserNick(String accountName, String accountFullName, String expectedUserName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void assertNoUserNick(String accountName, String expectedUserName) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(expectedUserName); - display("User for "+accountName, user); - assertNull("User for "+accountName+" ("+expectedUserName+") exists but it should be gone", user); + display("User for " + accountName, user); + assertNull("User for " + accountName + " (" + expectedUserName + ") exists but it should be gone", user); } private String lookupIterationTokenByAdditionalName(String additionalName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -2332,7 +2166,7 @@ private String lookupIterationTokenByAdditionalName(String additionalName) throw if (objects.isEmpty()) { return null; } - assert objects.size() == 1 : "Too many objects found for additional name "+additionalName+": "+objects; + assert objects.size() == 1 : "Too many objects found for additional name " + additionalName + ": " + objects; PrismObject user = objects.iterator().next(); return user.asObjectable().getIterationToken(); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java index b08bf160ffe..d83bb2953da 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java @@ -25,11 +25,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author Radovan Semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLifecycle extends AbstractInitializedModelIntegrationTest { @@ -51,16 +47,12 @@ public class TestLifecycle extends AbstractInitializedModelIntegrationTest { //no subtype, forced in draft state public static final File ROLE_CROUPIER_FILE = new File(TEST_DIR, "role-croupier.xml"); - protected static final String ROLE_CROUPIER_OID = "a7b8de9a-20a1-84f6-b452-01254a1256e3"; public static final File ROLE_PIT_BOSS_FILE = new File(TEST_DIR, "role-pit-boss.xml"); - protected static final String ROLE_PIT_BOSS_OID = "c4525ef8-31d4-95e6-d542-745e263f596c"; public static final String SUBTYPE_EMPLOYEE = "employee"; private static final Object USER_JACK_TELEPHONE_NUMBER = "12345654321"; - private String accontJackOid; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -87,8 +79,6 @@ protected File getSystemConfigurationFile() { */ @Test public void test050SetupJack() throws Exception { - final String TEST_NAME = "test050SetupJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -118,9 +108,6 @@ public void test050SetupJack() throws Exception { @Test public void test052PrincipalJackDraft() throws Exception { - final String TEST_NAME = "test052AutzJackDraft"; - // GIVEN - // WHEN when(); MidPointPrincipal principal = focusProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); @@ -140,8 +127,6 @@ public void test052PrincipalJackDraft() throws Exception { */ @Test public void test060TransitionJackToProposed() throws Exception { - final String TEST_NAME = "test060TransitionJackToProposed"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -162,14 +147,11 @@ public void test060TransitionJackToProposed() throws Exception { // Although we are in the proposed lifecycle and assignments would not be active by default // the proposed lifecycle is forcing activation to enabled. Therefore also assignments are // considered active. - accontJackOid = getSingleLinkOid(userAfter); + getSingleLinkOid(userAfter); } @Test public void test062PrincipalJackProposed() throws Exception { - final String TEST_NAME = "test062PrincipalJackProposed"; - // GIVEN - // WHEN when(); MidPointPrincipal principal = focusProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); @@ -194,8 +176,6 @@ public void test062PrincipalJackProposed() throws Exception { */ @Test public void test090TransitionJackToDefaultActive() throws Exception { - final String TEST_NAME = "test090TransitionJackToDefaultActive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -219,9 +199,6 @@ public void test090TransitionJackToDefaultActive() throws Exception { @Test public void test092PrincipalJackDefaultActive() throws Exception { - final String TEST_NAME = "test092PrincipalJackDefaultActive"; - // GIVEN - // WHEN when(); MidPointPrincipal principal = focusProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); @@ -231,23 +208,21 @@ public void test092PrincipalJackDefaultActive() throws Exception { assertNotAuthorized(principal, AUTZ_COMMAND_URL); assertAuthorized(principal, AUTZ_GAMBLE_URL); assertAuthorized(principal, AUTZ_APPARATE_URL); - // Forced assignment not specified for active lifecycle state + // Forced assignment not specified for active lifecycle state assertNotAuthorized(principal, AUTZ_PIT_BOSS_URL); assertNotAuthorized(principal, AUTZ_CROUPIER_URL); } private void assertTelephoneNumber(PrismObject user, Object expectedTelephoneNumber) { - assertEquals("Wrong telephoe number in "+user, expectedTelephoneNumber, user.asObjectable().getTelephoneNumber()); + assertEquals("Wrong telephoe number in " + user, expectedTelephoneNumber, user.asObjectable().getTelephoneNumber()); } protected void assertLifecycleState(PrismObject object, String expectedLifecycleState) { - assertEquals("Wrong lifecycle state in "+object, expectedLifecycleState, object.asObjectable().getLifecycleState()); + assertEquals("Wrong lifecycle state in " + object, expectedLifecycleState, object.asObjectable().getLifecycleState()); } @Test public void test100AssignJackCaretaker() throws Exception { - final String TEST_NAME = "test100AssignJackCaretaker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -270,8 +245,6 @@ public void test100AssignJackCaretaker() throws Exception { @Test public void test102UnassignJackHeadmaster() throws Exception { - final String TEST_NAME = "test102UnassignJackHeadmaster"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -298,8 +271,6 @@ public void test102UnassignJackHeadmaster() throws Exception { */ @Test public void test110UnassignJackCaretaker() throws Exception { - final String TEST_NAME = "test110UnassignJackCaretaker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -325,8 +296,6 @@ public void test110UnassignJackCaretaker() throws Exception { */ @Test public void test112UnassignJackCaretaker() throws Exception { - final String TEST_NAME = "test110UnassignJackCaretaker"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java index 233651495f0..269485b6e2c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java @@ -26,10 +26,6 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author semancik - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMerge extends AbstractInitializedModelIntegrationTest { @@ -69,8 +65,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); @@ -96,9 +90,7 @@ public void test000Sanity() throws Exception { */ @Test public void test100MergeJackGuybrushPreviewDelta() throws Exception { - final String TEST_NAME = "test100MergeJackGuybrushPreviewDelta"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJackBefore = getUser(USER_JACK_OID); @@ -158,9 +150,7 @@ public void test100MergeJackGuybrushPreviewDelta() throws Exception { */ @Test public void test102MergeJackGuybrushPreviewObject() throws Exception { - final String TEST_NAME = "test102MergeJackGuybrushPreviewObject"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -208,9 +198,7 @@ public void test102MergeJackGuybrushPreviewObject() throws Exception { */ @Test public void test110MergeGuybrushJackPreviewDelta() throws Exception { - final String TEST_NAME = "test110MergeGuybrushJackPreviewDelta"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); @@ -267,9 +255,7 @@ public void test110MergeGuybrushJackPreviewDelta() throws Exception { */ @Test public void test112MergeGuybrushJackPreviewObject() throws Exception { - final String TEST_NAME = "test112MergeGuybrushJackPreviewObject"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -314,9 +300,7 @@ public void test112MergeGuybrushJackPreviewObject() throws Exception { */ @Test public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { - final String TEST_NAME = "test200MergeJackGuybrushExpressionPreviewDelta"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJackBefore = getUser(USER_JACK_OID); @@ -366,9 +350,7 @@ public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { */ @Test public void test202MergeJackGuybrushExpressionPreviewObject() throws Exception { - final String TEST_NAME = "test202MergeJackGuybrushExpressionPreviewObject"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -416,9 +398,7 @@ public void test202MergeJackGuybrushExpressionPreviewObject() throws Exception { */ @Test public void test300MergeJackGuybrushPreviewDeltaDefaultSpecific() throws Exception { - final String TEST_NAME = "test300MergeJackGuybrushPreviewDeltaDefaultSpecific"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJackBefore = getUser(USER_JACK_OID); @@ -478,9 +458,7 @@ public void test300MergeJackGuybrushPreviewDeltaDefaultSpecific() throws Excepti */ @Test public void test500MergeJackGuybrush() throws Exception { - final String TEST_NAME = "test500MergeJackGuybrush"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java index 42d5fbf3cb2..cf628993b63 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java @@ -6,12 +6,12 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.*; + import java.io.File; import java.util.ArrayList; import java.util.Collection; -import com.evolveum.midpoint.test.IntegrationTestTools; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; @@ -28,18 +28,17 @@ import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; - -import static org.testng.AssertJUnit.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * This is testing the DEPRECATED functions of model API. It should be removed once the functions are phased out. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelCrudService extends AbstractInitializedModelIntegrationTest { @@ -54,15 +53,13 @@ public class TestModelCrudService extends AbstractInitializedModelIntegrationTes private static String accountOid; - @Autowired(required = true) + @Autowired protected ModelCrudService modelCrudService; @Test public void test050AddResource() throws Exception { - final String TEST_NAME = "test050AddResource"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); @@ -85,16 +82,14 @@ public void test050AddResource() throws Exception { @Test public void test100ModifyUserAddAccount() throws Exception { - final String TEST_NAME = "test100ModifyUserAddAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference() @@ -102,7 +97,7 @@ public void test100ModifyUserAddAccount() throws Exception { modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN // Check accountRef @@ -140,14 +135,14 @@ public void test119ModifyUserDeleteAccount() throws Exception { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.setOid(accountOid); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN // Check accountRef @@ -158,8 +153,8 @@ public void test119ModifyUserDeleteAccount() throws Exception { // Check is shadow is gone try { - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - AssertJUnit.fail("Shadow "+accountOid+" still exists"); + repositoryService.getObject(ShadowType.class, accountOid, null, result); + AssertJUnit.fail("Shadow " + accountOid + " still exists"); } catch (ObjectNotFoundException e) { // This is OK } @@ -208,12 +203,12 @@ public void test121ModifyUserAddAccountRef() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountOid); modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN // Check accountRef @@ -233,8 +228,6 @@ public void test121ModifyUserAddAccountRef() throws Exception { assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - - @Test public void test128ModifyUserDeleteAccountRef() throws Exception { @@ -245,14 +238,14 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountOid); modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN PrismObject userJack = getUser(USER_JACK_OID); @@ -308,7 +301,7 @@ public void test150AddUserBlackbeardWithAccount() throws Exception { addAccountLinkRef(user, new File(TEST_CONTRACT_DIR, "account-blackbeard-dummy.xml")); // WHEN - modelCrudService.addObject(user , null, task, result); + modelCrudService.addObject(user, null, task, result); // THEN // Check accountRef @@ -331,7 +324,6 @@ public void test150AddUserBlackbeardWithAccount() throws Exception { assertDefaultDummyAccount("blackbeard", "Edward Teach", true); } - @Test public void test210AddUserMorganWithAssignment() throws Exception { @@ -343,7 +335,7 @@ public void test210AddUserMorganWithAssignment() throws Exception { PrismObject user = PrismTestUtil.parseObject(new File(TEST_CONTRACT_DIR, "user-morgan-assignment-dummy.xml")); // WHEN - modelCrudService.addObject(user , null, task, result); + modelCrudService.addObject(user, null, task, result); // THEN // Check accountRef diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java index 65a6d18359a..2e624b724f1 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java @@ -6,36 +6,17 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; - import javax.xml.bind.JAXBElement; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.icf.dummy.resource.BreakMode; -import com.evolveum.midpoint.common.refinery.*; -import com.evolveum.midpoint.notifications.api.transports.Message; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemName; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.*; -import com.evolveum.midpoint.schema.processor.*; -import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import com.evolveum.prism.xml.ns._public.types_3.RawType; - import org.apache.commons.lang.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -43,17 +24,28 @@ import org.testng.AssertJUnit; import org.testng.annotations.Test; +import com.evolveum.icf.dummy.resource.BreakMode; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.audit.api.AuditEventStage; import com.evolveum.midpoint.common.StaticExpressionUtil; +import com.evolveum.midpoint.common.refinery.*; import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.context.ModelContext; +import com.evolveum.midpoint.notifications.api.transports.Message; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.path.ItemName; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; +import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.ObjectDeltaOperation; +import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.internals.InternalCounters; import com.evolveum.midpoint.schema.internals.InternalMonitor; +import com.evolveum.midpoint.schema.processor.*; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; @@ -69,26 +61,13 @@ import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.PolicyViolationException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAttributeDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; +import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; +import com.evolveum.prism.xml.ns._public.types_3.RawType; + +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelServiceContract extends AbstractInitializedModelIntegrationTest { @@ -106,8 +85,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); InternalMonitor.reset(); -// InternalMonitor.setTraceShadowFetchOperation(true); -// InternalMonitor.setTraceResourceSchemaOperations(true); InternalMonitor.setTrace(InternalCounters.PRISM_OBJECT_CLONE_COUNT, true); // setGlobalTracingOverride(addNotificationsLogging(createModelLoggingTracingProfile())); @@ -115,8 +92,6 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test050GetUserJack() throws Exception { - final String TEST_NAME = "test050GetUserJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -136,8 +111,6 @@ public void test050GetUserJack() throws Exception { @Test public void test051GetUserBarbossa() throws Exception { - final String TEST_NAME = "test051GetUserBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -159,8 +132,6 @@ public void test051GetUserBarbossa() throws Exception { @Test public void test099ModifyUserAddAccountFailing() throws Exception { - final String TEST_NAME = "test099ModifyUserAddAccountFailing"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -204,17 +175,6 @@ public void test099ModifyUserAddAccountFailing() throws Exception { UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); -// // Check audit -// display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(2); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(3); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertTarget(USER_JACK_OID); -// dummyAuditService.assertExecutionSuccess(); - notificationManager.setDisabled(true); getDummyResource().resetBreakMode(); @@ -235,8 +195,6 @@ public void test099ModifyUserAddAccountFailing() throws Exception { @Test public void test100ModifyUserAddAccount() throws Exception { - final String TEST_NAME = "test100ModifyUserAddAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -310,22 +268,12 @@ public void test100ModifyUserAddAccount() throws Exception { Message message = messages.get(0); // number of messages was already checked assertEquals("Invalid list of recipients", Arrays.asList("recipient@evolveum.com"), message.getTo()); assertTrue("No account name in account password notification", message.getBody().contains("Password for account jack on Dummy Resource is:")); -// -// messages = dummyTransport.getMessages("dummy:newAccountsViaExpression"); -// assertNotNull("No messages recorded in dummy transport (expressions)", messages); -// assertEquals("Invalid number of messages recorded in dummy transport (expressions)", 1, messages.size()); -// message = messages.get(0); -// assertEquals("Invalid list of recipients (expressions)", Arrays.asList("test1", "test2"), message.getTo()); -// assertEquals("Invalid message subject", "Changed account for jack", message.getSubject()); -// assertEquals("Invalid message body", "Body: Changed account for jack", message.getBody()); assertSteadyResources(); } @Test public void test101GetAccount() throws Exception { - final String TEST_NAME = "test101GetAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -340,7 +288,7 @@ public void test101GetAccount() throws Exception { rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); // WHEN - PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, null , task, result); + PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); // THEN display("Account", account); @@ -364,10 +312,10 @@ public void test101GetAccount() throws Exception { "cold"); ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(account); - assertNotNull("No attribute container from "+account, attributesContainer); + assertNotNull("No attribute container from " + account, attributesContainer); Collection> identifiers = attributesContainer.getPrimaryIdentifiers(); - assertNotNull("No identifiers (null) in attributes container in "+accountJackOid, identifiers); - assertFalse("No identifiers (empty) in attributes container in "+accountJackOid, identifiers.isEmpty()); + assertNotNull("No identifiers (null) in attributes container in " + accountJackOid, identifiers); + assertFalse("No identifiers (empty) in attributes container in " + accountJackOid, identifiers.isEmpty()); ResourceAttribute fullNameAttr = attributesContainer.findAttribute(dummyResourceCtl.getAttributeFullnameQName()); PrismAsserts.assertPropertyValue(fullNameAttr, ACCOUNT_JACK_DUMMY_FULLNAME); @@ -388,14 +336,14 @@ public void test101GetAccount() throws Exception { public void test102GetAccountNoFetch() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test102GetAccountNoFetch"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); // WHEN - PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options , task, result); + PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options, task, result); display("Account", account); display("Account def", account.getDefinition()); @@ -414,14 +362,14 @@ public void test102GetAccountNoFetch() throws Exception { public void test103GetAccountRaw() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test103GetAccountRaw"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); // WHEN - PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options , task, result); + PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options, task, result); display("Account", account); display("Account def", account.getDefinition()); @@ -440,7 +388,7 @@ public void test103GetAccountRaw() throws Exception { public void test105SearchAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test105SearchAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); // get weapon attribute definition @@ -471,7 +419,7 @@ public void test105SearchAccount() throws Exception { public void test106SearchAccountWithoutResourceSchema() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test106SearchAccountWithoutResourceSchema"); + Task task = getTestTask(); OperationResult result = task.getResult(); // create weapon attribute definition - NOT SUPPORTED, use only when you know what you're doing! @@ -497,7 +445,7 @@ public void test106SearchAccountWithoutResourceSchema() throws Exception { public void test108ModifyUserAddAccountAgain() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test108ModifyUserAddAccountAgain"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -542,8 +490,6 @@ public void test108ModifyUserAddAccountAgain() throws Exception { @Test public void test109ModifyUserAddAccountAgain() throws Exception { - final String TEST_NAME = "test109ModifyUserAddAccountAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -592,8 +538,6 @@ public void test109ModifyUserAddAccountAgain() throws Exception { @Test public void test110GetUserResolveAccount() throws Exception { - final String TEST_NAME = "test110GetUserResolveAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -604,7 +548,7 @@ public void test110GetUserResolveAccount() throws Exception { .build(); // WHEN - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options, task, result); // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); @@ -628,11 +572,8 @@ public void test110GetUserResolveAccount() throws Exception { assertSteadyResources(); } - @Test public void test111GetUserResolveAccountResource() throws Exception { - final String TEST_NAME = "test111GetUserResolveAccountResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -644,7 +585,7 @@ public void test111GetUserResolveAccountResource() throws Exception { .build(); // WHEN - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options, task, result); // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); @@ -673,8 +614,6 @@ public void test111GetUserResolveAccountResource() throws Exception { @Test public void test112GetUserResolveAccountNoFetch() throws Exception { - final String TEST_NAME = "test112GetUserResolveAccountNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -684,10 +623,10 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { getOpts.setResolve(true); getOpts.setNoFetch(true); Collection> options = - SelectorOptions.createCollection(prismContext.toUniformPath(UserType.F_LINK_REF), getOpts); + SelectorOptions.createCollection(prismContext.toUniformPath(UserType.F_LINK_REF), getOpts); // WHEN - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options, task, result); // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); @@ -715,8 +654,6 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { @Test public void test119ModifyUserDeleteAccount() throws Exception { - final String TEST_NAME = "test119ModifyUserDeleteAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -727,7 +664,8 @@ public void test119ModifyUserDeleteAccount() throws Exception { ObjectDelta userDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); + ReferenceDelta accountDelta = prismContext.deltaFactory().reference() + .createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); @@ -742,15 +680,16 @@ public void test119ModifyUserDeleteAccount() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); // Check accountRef - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + PrismObject userJack = + modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertUserJack(userJack); UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of linkRefs", 0, userJackType.getLinkRef().size()); // Check is shadow is gone try { - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); - AssertJUnit.fail("Shadow "+accountJackOid+" still exists"); + repositoryService.getObject(ShadowType.class, accountJackOid, null, result); + AssertJUnit.fail("Shadow " + accountJackOid + " still exists"); } catch (ObjectNotFoundException e) { // This is OK } @@ -760,7 +699,7 @@ public void test119ModifyUserDeleteAccount() throws Exception { assertDummyScriptsDelete(); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -787,10 +726,8 @@ public void test119ModifyUserDeleteAccount() throws Exception { @Test public void test120AddAccount() throws Exception { - final String TEST_NAME = "test120AddAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -801,7 +738,8 @@ public void test120AddAccount() throws Exception { // WHEN when(); - Collection> executeChanges = executeChanges(accountDelta, null, task, result); + Collection> executeChanges = + executeChanges(accountDelta, null, task, result); // THEN then(); @@ -812,19 +750,22 @@ public void test120AddAccount() throws Exception { accountJackOid = ObjectDeltaOperation.findProjectionDeltaOidInCollection(executeChanges); assertNotNull("No account OID in executed deltas", accountJackOid); // Check accountRef (should be none) - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + PrismObject userJack = + modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertUserJack(userJack); UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, + PrismObject accountShadow = repositoryService.getObject( + ShadowType.class, accountJackOid, SelectorOptions.createCollection(GetOperationOptions.createRaw()), result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); + PrismObject accountModel = modelService.getObject( + ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); @@ -863,8 +804,6 @@ public void test120AddAccount() throws Exception { */ @Test public void test121ModifyUserAddAccountRef() throws Exception { - final String TEST_NAME = "test121ModifyUserAddAccountRef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -872,7 +811,9 @@ public void test121ModifyUserAddAccountRef() throws Exception { ObjectDelta userDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountJackOid); + ReferenceDelta accountDelta = + prismContext.deltaFactory().reference().createModificationAdd( + UserType.F_LINK_REF, getUserDefinition(), accountJackOid); userDelta.addModification(accountDelta); // WHEN @@ -894,7 +835,8 @@ public void test121ModifyUserAddAccountRef() throws Exception { assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); + PrismObject accountModel = modelService.getObject( + ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); // Check account in dummy resource @@ -924,13 +866,10 @@ public void test121ModifyUserAddAccountRef() throws Exception { assertSteadyResources(); } - - @Test public void test128ModifyUserDeleteAccountRef() throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test128ModifyUserDeleteAccountRef"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -995,9 +934,8 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { @Test public void test129DeleteAccount() throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test129DeleteAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -1050,48 +988,46 @@ public void test129DeleteAccount() throws Exception { assertSteadyResources(); } - @Test public void test130PreviewModifyUserJackAssignAccount() { - // GIVEN - try{ - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test130PreviewModifyUserJackAssignAccount"); - OperationResult result = task.getResult(); - preTestCleanup(AssignmentPolicyEnforcementType.FULL); + try { + Task task = getTestTask(); + OperationResult result = task.getResult(); + preTestCleanup(AssignmentPolicyEnforcementType.FULL); - Collection> deltas = new ArrayList<>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); - deltas.add(accountAssignmentUserDelta); + Collection> deltas = new ArrayList<>(); + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); + deltas.add(accountAssignmentUserDelta); - // WHEN - ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); + // WHEN + modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - // THEN - result.computeStatus(); - TestUtil.assertSuccess("previewChanges result", result); - assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); + // THEN + result.computeStatus(); + TestUtil.assertSuccess("previewChanges result", result); + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - PrismObject userJack = getUser(USER_JACK_OID); - display("User after change execution", userJack); - assertUserJack(userJack); - // Check accountRef - assertUserNoAccountRefs(userJack); + PrismObject userJack = getUser(USER_JACK_OID); + display("User after change execution", userJack); + assertUserJack(userJack); + // Check accountRef + assertUserNoAccountRefs(userJack); - // TODO: assert context - // TODO: assert context - // TODO: assert context + // TODO: assert context + // TODO: assert context + // TODO: assert context - // We (temporarily?) turned off resource ref resolution during preview operation. - // It complicated things regarding objects immutability a bit. Let the clients resolve these references themselves. + // We (temporarily?) turned off resource ref resolution during preview operation. + // It complicated things regarding objects immutability a bit. Let the clients resolve these references themselves. - //assertResolvedResourceRefs(modelContext); + //assertResolvedResourceRefs(modelContext); - // Check account in dummy resource - assertNoDummyAccount("jack"); + // Check account in dummy resource + assertNoDummyAccount("jack"); - dummyAuditService.assertNoRecord(); - }catch(Exception ex){ + dummyAuditService.assertNoRecord(); + } catch (Exception ex) { logger.info("Exception {}", ex.getMessage(), ex); } @@ -1100,8 +1036,6 @@ public void test130PreviewModifyUserJackAssignAccount() { @Test public void test131ModifyUserJackAssignAccount() throws Exception { - final String TEST_NAME="test131ModifyUserJackAssignAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1181,8 +1115,6 @@ public void test131ModifyUserJackAssignAccount() throws Exception { */ @Test public void test132ModifyAccountJackDummy() throws Exception { - final String TEST_NAME = "test132ModifyAccountJackDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1272,8 +1204,6 @@ public void test132ModifyAccountJackDummy() throws Exception { */ @Test public void test135ModifyUserJackAssignAccountAgain() throws Exception { - final String TEST_NAME="test135ModifyUserJackAssignAccountAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1295,7 +1225,6 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { accountJackOid = getSingleLinkOid(userJack); - // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, SelectorOptions.createCollection(GetOperationOptions.createRaw()), result); @@ -1335,8 +1264,6 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { @Test public void test136JackRecomputeNoChange() throws Exception { - final String TEST_NAME="test136JackRecomputeNoChange"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1397,8 +1324,6 @@ public void test136JackRecomputeNoChange() throws Exception { @Test public void test139ModifyUserJackUnassignAccount() throws Exception { - final String TEST_NAME = "test139ModifyUserJackUnassignAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1459,8 +1384,6 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { */ @Test public void test141ModifyUserJackAssignAccountPositiveEnforcement() throws Exception { - final String TEST_NAME = "test141ModifyUserJackAssignAccountPositiveEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1543,8 +1466,6 @@ public void test141ModifyUserJackAssignAccountPositiveEnforcement() throws Excep */ @Test public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exception { - final String TEST_NAME = "test148ModifyUserJackUnassignAccountPositiveEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1638,8 +1559,6 @@ public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exc */ @Test public void test149ModifyUserJackDeleteAccount() throws Exception { - final String TEST_NAME = "test149ModifyUserJackDeleteAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1710,8 +1629,6 @@ public void test149ModifyUserJackDeleteAccount() throws Exception { */ @Test public void test151ModifyUserJackAssignAccountRelativeEnforcement() throws Exception { - final String TEST_NAME = "test151ModifyUserJackAssignAccountRelativeEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1787,11 +1704,8 @@ public void test151ModifyUserJackAssignAccountRelativeEnforcement() throws Excep */ @Test public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exception { - final String TEST_NAME = "test158ModifyUserJackUnassignAccountRelativeEnforcement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); @@ -1851,8 +1765,6 @@ public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exc */ @Test public void test161ModifyUserJackAssignAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test161ModifyUserJackAssignAccountNoneEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1913,8 +1825,6 @@ public void test161ModifyUserJackAssignAccountNoneEnforcement() throws Exception @Test public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test163ModifyUserJackAddAccountNoneEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1926,9 +1836,10 @@ public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { .createEmptyModifyDelta(UserType.class, USER_JACK_OID); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); - ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); + ReferenceDelta accountDelta = prismContext.deltaFactory().reference() + .createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); dummyAuditService.clear(); dummyTransport.clearMessages(); @@ -1993,11 +1904,8 @@ public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { @Test public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test164ModifyUserJackUnassignAccountNoneEnforcement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.NONE); @@ -2060,8 +1968,6 @@ public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Excepti @Test public void test169ModifyUserJackDeleteAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test169ModifyUserJackDeleteAccountNoneEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2127,8 +2033,6 @@ public void test169ModifyUserJackDeleteAccountNoneEnforcement() throws Exception @Test public void test180ModifyUserAddAccountFullEnforcement() throws Exception { - final String TEST_NAME = "test180ModifyUserAddAccountFullEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2142,7 +2046,7 @@ public void test180ModifyUserAddAccountFullEnforcement() throws Exception { accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); try { @@ -2188,8 +2092,6 @@ public void test180ModifyUserAddAccountFullEnforcement() throws Exception { @Test public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exception { - final String TEST_NAME = "test182ModifyUserAddAndAssignAccountPositiveEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2202,7 +2104,7 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -2266,7 +2168,7 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc public void test189ModifyUserJackUnassignAndDeleteAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test149ModifyUserJackUnassignAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -2316,13 +2218,11 @@ public void test189ModifyUserJackUnassignAndDeleteAccount() throws Exception { /** * We try to both assign an account and modify that account in one operation. - * Some changes should be reflected to account (e.g. weapon) as the mapping is weak, other should be - * overridded (e.g. fullname) as the mapping is strong. + * Some changes should be reflected to account (e.g. weapon) as the mapping is weak, + * other should be overridden (e.g. fullname) as the mapping is strong. */ @Test public void test190ModifyUserJackAssignAccountAndModify() throws Exception { - final String TEST_NAME = "test190ModifyUserJackAssignAccountAndModify"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2402,20 +2302,15 @@ public void test190ModifyUserJackAssignAccountAndModify() throws Exception { /** * We try to modify an assignment of the account and see whether changes will be recorded in the account itself. - * */ @Test public void test191ModifyUserJackModifyAssignment() throws Exception { - final String TEST_NAME = "test191ModifyUserJackModifyAssignment"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); Collection> deltas = new ArrayList<>(); - //PrismPropertyDefinition definition = getAssignmentDefinition().findPropertyDefinition(new QName(SchemaConstantsGenerated.NS_COMMON, "accountConstruction")); - PrismObject dummyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(dummyResource, prismContext); @@ -2498,7 +2393,6 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { DummyAccount dummyAccount = getDummyAccount(null, USER_JACK_USERNAME); display(dummyAccount.debugDump()); assertDummyAccountAttribute(null, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "q"); - //assertEquals("Missing or incorrect attribute value", "soda", dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, String.class)); assertDummyScriptsModify(userJack, true); @@ -2520,8 +2414,6 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { @Test public void test192ModifyUserJack() throws Exception { - final String TEST_NAME = "test192ModifyUserJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2592,8 +2484,6 @@ public void test192ModifyUserJack() throws Exception { @Test public void test193ModifyUserJackLocationEmpty() throws Exception { - final String TEST_NAME = "test193ModifyUserJackLocationEmpty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2658,8 +2548,6 @@ public void test193ModifyUserJackLocationEmpty() throws Exception { @Test public void test194ModifyUserJackLocationNull() throws Exception { - final String TEST_NAME = "test194ModifyUserJackLocationNull"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2667,7 +2555,7 @@ public void test194ModifyUserJackLocationNull() throws Exception { try { // WHEN - modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, (PolyString)null); + modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, (PolyString) null); AssertJUnit.fail("Unexpected success"); } catch (IllegalStateException e) { @@ -2691,8 +2579,6 @@ public void test194ModifyUserJackLocationNull() throws Exception { @Test public void test195ModifyUserJackLocationSea() throws Exception { - final String TEST_NAME = "test195ModifyUserJackLocationSea"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2760,13 +2646,13 @@ public void test195ModifyUserJackLocationSea() throws Exception { public void test198ModifyUserJackRaw() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test196ModifyUserJackRaw"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Marvelous Captain Jack Sparrow")); - Collection> deltas = (Collection)MiscUtil.createCollection(objectDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(objectDelta); // WHEN modelService.executeChanges(deltas, ModelExecuteOptions.createRaw(), task, result); @@ -2813,7 +2699,7 @@ public void test198ModifyUserJackRaw() throws Exception { public void test199DeleteUserJack() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test199DeleteUserJack"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); @@ -2830,7 +2716,7 @@ public void test199DeleteUserJack() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); try { - PrismObject userJack = getUser(USER_JACK_OID); + getUser(USER_JACK_OID); AssertJUnit.fail("Jack is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK @@ -2844,7 +2730,7 @@ public void test199DeleteUserJack() throws Exception { assertDummyScriptsDelete(); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2873,8 +2759,6 @@ public void test199DeleteUserJack() throws Exception { @Test public void test200AddUserBlackbeardWithAccount() throws Exception { - final String TEST_NAME = "test200AddUserBlackbeardWithAccount"; - // GIVEN Task task = getTestTask(); // Use custom channel to trigger a special outbound mapping @@ -2883,7 +2767,7 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); PrismObject user = PrismTestUtil.parseObject(new File(TEST_DIR, "user-blackbeard-account-dummy.xml")); - addAccountLinkRef(user,new File(TEST_DIR, "account-blackbeard-dummy.xml")); + addAccountLinkRef(user, new File(TEST_DIR, "account-blackbeard-dummy.xml")); ObjectDelta userDelta = DeltaFactory.Object.createAddDelta(user); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); @@ -2921,7 +2805,7 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { // Check account in dummy resource assertDefaultDummyAccount("blackbeard", "Edward Teach", true); DummyAccount dummyAccount = getDummyAccount(null, "blackbeard"); - assertEquals("Wrong loot", (Integer)10000, dummyAccount.getAttributeValue("loot", Integer.class)); + assertEquals("Wrong loot", (Integer) 10000, dummyAccount.getAttributeValue("loot", Integer.class)); assertDummyScriptsAdd(userBlackbeard, accountModel, getDummyResourceType()); @@ -2937,7 +2821,7 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { // this one was redundant // dummyAuditService.assertExecutionDeltas(1, 1); // dummyAuditService.assertHasDelta(1, ChangeType.MODIFY, UserType.class); - // raw operation, no target + // raw operation, no target // dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); @@ -2958,8 +2842,6 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { @Test public void test210AddUserMorganWithAssignment() throws Exception { - final String TEST_NAME = "test210AddUserMorganWithAssignment"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3010,7 +2892,7 @@ public void test210AddUserMorganWithAssignment() throws Exception { assertDummyScriptsAdd(userMorgan, accountModel, getDummyResourceType()); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -3039,8 +2921,6 @@ public void test210AddUserMorganWithAssignment() throws Exception { @Test public void test212RenameUserMorgan() throws Exception { - final String TEST_NAME = "test212RenameUserMorgan"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3079,7 +2959,7 @@ public void test212RenameUserMorgan() throws Exception { assertDummyScriptsModify(userMorgan); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -3088,7 +2968,7 @@ public void test212RenameUserMorgan() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); ObjectDeltaOperation auditShadowDelta = dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); - assertEquals("Unexpected number of modifications in shadow audit delta: "+auditShadowDelta.debugDump(), 8, auditShadowDelta.getObjectDelta().getModifications().size()); + assertEquals("Unexpected number of modifications in shadow audit delta: " + auditShadowDelta.debugDump(), 8, auditShadowDelta.getObjectDelta().getModifications().size()); dummyAuditService.assertOldValue(ChangeType.MODIFY, UserType.class, UserType.F_NAME, PrismTestUtil.createPolyString("morgan")); @@ -3124,8 +3004,6 @@ public void test212RenameUserMorgan() throws Exception { */ @Test public void test240AddUserCharlesRaw() throws Exception { - final String TEST_NAME = "test240AddUserCharlesRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3156,7 +3034,7 @@ public void test240AddUserCharlesRaw() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.ADD, UserType.class); - // raw operation, no target + // raw operation, no target // dummyAuditService.assertTarget(userAfter.getOid()); dummyAuditService.assertExecutionSuccess(); @@ -3168,8 +3046,6 @@ public void test240AddUserCharlesRaw() throws Exception { */ @Test public void test241DeleteUserCharlesRaw() throws Exception { - final String TEST_NAME = "test241DeleteUserCharlesRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3198,7 +3074,7 @@ public void test241DeleteUserCharlesRaw() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.DELETE, UserType.class); - // raw operation, no target + // raw operation, no target // dummyAuditService.assertTarget(userCharlesOid); dummyAuditService.assertExecutionSuccess(); @@ -3207,8 +3083,6 @@ public void test241DeleteUserCharlesRaw() throws Exception { @Test public void test300AddUserJackWithAssignmentBlue() throws Exception { - final String TEST_NAME="test300AddUserJackWithAssignmentBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3276,8 +3150,6 @@ public void test300AddUserJackWithAssignmentBlue() throws Exception { */ @Test public void test302ModifyAccountJackDummyBlue() throws Exception { - final String TEST_NAME = "test302ModifyAccountJackDummyBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3315,7 +3187,7 @@ accountJackBlueOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttr // Check account // All the changes should be reflected to the account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); + modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertAccountShadowRepo(accountShadow, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); // Check account in dummy resource @@ -3387,7 +3259,7 @@ private void assertDummyScriptsAdd(PrismObject user, PrismObject user, PrismObject> accountSource = () -> { try { return PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); } catch (SchemaException | IOException e) { - throw new IllegalStateException(e.getMessage(),e); + throw new IllegalStateException(e.getMessage(), e); } }; ObjectChecker> checker = modelContext -> assertAddAccount(modelContext, false); - modifyUserAddAccountImplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountExplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSame(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSameReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqualReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqualReverse(TEST_NAME, accountSource, checker); + modifyUserAddAccountImplicit(accountSource, checker); + modifyUserAddAccountExplicit(accountSource, checker); + modifyUserAddAccountImplicitExplicitSame(accountSource, checker); + modifyUserAddAccountImplicitExplicitSameReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqual(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqualReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitNotEqual(accountSource); + modifyUserAddAccountImplicitExplicitNotEqualReverse(accountSource); } @Test public void test101ModifyUserAddAccountNoAttributesBundle() throws Exception { - final String TEST_NAME = "test101ModifyUserAddAccountNoAttributesBundle"; - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); ObjectSource> accountSource = new ObjectSource>() { @@ -117,8 +115,8 @@ public PrismObject get() { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.removeContainer(ShadowType.F_ATTRIBUTES); return account; - } catch (SchemaException|IOException e) { - throw new IllegalStateException(e.getMessage(),e); + } catch (SchemaException | IOException e) { + throw new IllegalStateException(e.getMessage(), e); } } }; @@ -130,22 +128,20 @@ public void check(ModelContext modelContext) { } }; - modifyUserAddAccountImplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountExplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSame(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSameReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqualReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqualReverse(TEST_NAME, accountSource, checker); + modifyUserAddAccountImplicit(accountSource, checker); + modifyUserAddAccountExplicit(accountSource, checker); + modifyUserAddAccountImplicitExplicitSame(accountSource, checker); + modifyUserAddAccountImplicitExplicitSameReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqual(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqualReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitNotEqual(accountSource); + modifyUserAddAccountImplicitExplicitNotEqualReverse(accountSource); } - private void modifyUserAddAccountImplicit(String bundleName, ObjectSource> accountSource, + private void modifyUserAddAccountImplicit(ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "Implicit"; - // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicit"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -161,12 +157,10 @@ private void modifyUserAddAccountImplicit(String bundleName, ObjectSource> accountSource, + private void modifyUserAddAccountExplicit(ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "Explicit"; - // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountExplicit"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -179,12 +173,11 @@ private void modifyUserAddAccountExplicit(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitSame"; - + private void modifyUserAddAccountImplicitExplicitSame( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitSame"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -201,12 +194,11 @@ private void modifyUserAddAccountImplicitExplicitSame(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitSameReverse"; - + private void modifyUserAddAccountImplicitExplicitSameReverse( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitSameReverse"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -223,12 +215,11 @@ private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitEqual"; - + private void modifyUserAddAccountImplicitExplicitEqual( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitEqual"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -245,12 +236,11 @@ private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitEqualReverse"; - + private void modifyUserAddAccountImplicitExplicitEqualReverse( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitEqualReverse"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -267,12 +257,10 @@ private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitNotEqual"; - + private void modifyUserAddAccountImplicitExplicitNotEqual( + ObjectSource> accountSource) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitNotEqual"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -291,12 +279,10 @@ private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, doPreviewFail(deltas, task, result); } - private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitNotEqualReverse"; - + private void modifyUserAddAccountImplicitExplicitNotEqualReverse( + ObjectSource> accountSource) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitNotEqualReverse"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -317,8 +303,8 @@ private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleNa private void doPreview(Collection> deltas, ObjectChecker> checker, Task task, OperationResult result) - throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, - ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, + ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { display("Input deltas: ", deltas); // WHEN @@ -331,15 +317,16 @@ private void doPreview(Collection> deltas, assertSuccess(result); } - private void doPreviewFail(Collection> deltas, Task task, OperationResult result) - throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, - ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { + private void doPreviewFail( + Collection> deltas, Task task, OperationResult result) + throws PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, + ObjectAlreadyExistsException, CommunicationException, ConfigurationException, + SecurityViolationException { display("Input deltas: ", deltas); try { // WHEN - ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); AssertJUnit.fail("Expected exception, but it haven't come"); } catch (SchemaException e) { // This is expected @@ -355,7 +342,7 @@ private void assertAddAccount(ModelContext modelContext, boolean expec ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); assertSideEffectiveDeltasOnly(focusContext.getSecondaryDelta(), "focus secondary delta", ActivationStatusType.ENABLED); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -393,8 +380,6 @@ private void assertAddAccount(ModelContext modelContext, boolean expec @Test public void test130GetCompiledGuiProfile() throws Exception { - final String TEST_NAME = "test130GetCompiledGuiProfile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -406,11 +391,11 @@ public void test130GetCompiledGuiProfile() throws Exception { assertSuccess(result); assertCompiledGuiProfile(compiledGuiProfile) - .assertAdditionalMenuLinks(0) - .assertUserDashboardLinks(1) - .assertObjectForms(1) - .assertUserDashboardWidgets(0) - .assertObjectCollectionViews(3); + .assertAdditionalMenuLinks(0) + .assertUserDashboardLinks(1) + .assertObjectForms(1) + .assertUserDashboardWidgets(0) + .assertObjectCollectionViews(3); RichHyperlinkType link = compiledGuiProfile.getUserDashboardLink().get(0); assertEquals("Bad link label", "Foo", link.getLabel()); @@ -421,8 +406,6 @@ public void test130GetCompiledGuiProfile() throws Exception { @Test public void test150GetGuybrushRefinedObjectClassDef() throws Exception { - final String TEST_NAME = "test150GetGuybrushRefinedObjectClassDef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -445,8 +428,6 @@ public void test150GetGuybrushRefinedObjectClassDef() throws Exception { @Test public void test200ModifyUserGuybrushDeleteAccount() throws Exception { - final String TEST_NAME = "test200ModifyUserGuybrushDeleteAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -477,7 +458,7 @@ public void test200ModifyUserGuybrushDeleteAccount() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -494,8 +475,6 @@ public void test200ModifyUserGuybrushDeleteAccount() throws Exception { @Test public void test210GuybrushAddAccount() throws Exception { - final String TEST_NAME = "test210GuybrushAddAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -544,8 +523,6 @@ public void test210GuybrushAddAccount() throws Exception { @Test public void test212ModifyUserAddAccountRef() throws Exception { - final String TEST_NAME = "test212ModifyUserAddAccountRef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -573,9 +550,8 @@ public void test212ModifyUserAddAccountRef() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -589,7 +565,7 @@ public void test212ModifyUserAddAccountRef() throws Exception { assertNull("Unexpected account primary delta", accountPrimaryDelta); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertEquals("Unexpected size of account secondary delta: "+accountSecondaryDelta, 2, accountSecondaryDelta.getModifications().size()); + assertEquals("Unexpected size of account secondary delta: " + accountSecondaryDelta, 2, accountSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyAdd(accountSecondaryDelta, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME), "rum"); PrismAsserts.assertPropertyAdd(accountSecondaryDelta, @@ -601,8 +577,6 @@ public void test212ModifyUserAddAccountRef() throws Exception { */ @Test public void test220PreviewJackAssignRolePirate() throws Exception { - final String TEST_NAME = "test220PreviewJackAssignRolePirate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -628,8 +602,6 @@ public void test220PreviewJackAssignRolePirate() throws Exception { */ @Test public void test221PreviewJackAssignRolePirateReconcile() throws Exception { - final String TEST_NAME = "test221PreviewJackAssignRolePirateReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -637,7 +609,7 @@ public void test221PreviewJackAssignRolePirateReconcile() throws Exception { assertUserBefore(USER_JACK_OID) .links() - .assertNone(); + .assertNone(); ObjectDelta delta = createAssignmentAssignmentHolderDelta(UserType.class, USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); @@ -654,7 +626,7 @@ public void test221PreviewJackAssignRolePirateReconcile() throws Exception { assertPreviewJackAssignRolePirate(modelContext); } - private void assertPreviewJackAssignRolePirate(ModelContext modelContext) throws Exception { + private void assertPreviewJackAssignRolePirate(ModelContext modelContext) { display("Preview context", modelContext); assertNotNull("Null model context", modelContext); @@ -731,17 +703,14 @@ private void assertPreviewJackAssignRolePirate(ModelContext modelConte */ @Test public void test230GuybrushAssignAccountDummy() throws Exception { - final String TEST_NAME = "test230GuybrushAssignAccountDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - ObjectDelta delta = createAssignmentAssignmentHolderDelta(UserType.class, USER_GUYBRUSH_OID, + createAssignmentAssignmentHolderDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - - ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); + ModelExecuteOptions.createReconcile(); // WHEN when(); @@ -755,7 +724,7 @@ public void test230GuybrushAssignAccountDummy() throws Exception { accountGuybrushOid = assertUserAfter(USER_GUYBRUSH_OID) .singleLink() - .getOid(); + .getOid(); DummyAccount dummyAccount = assertDummyAccount(null, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Dummy account after", dummyAccount); @@ -768,8 +737,6 @@ public void test230GuybrushAssignAccountDummy() throws Exception { */ @Test public void test231PreviewGuybrushModifyAccountFullName() throws Exception { - final String TEST_NAME = "test231PreviewGuybrushModifyAccountFullName"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -820,8 +787,6 @@ public void test231PreviewGuybrushModifyAccountFullName() throws Exception { */ @Test public void test232PreviewGuybrushModifyAccountShip() throws Exception { - final String TEST_NAME = "test232PreviewGuybrushModifyAccountShip"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -871,8 +836,6 @@ public void test232PreviewGuybrushModifyAccountShip() throws Exception { */ @Test public void test233PreviewGuybrushAddRolePirate() throws Exception { - final String TEST_NAME = "test233PreviewGuybrushAddRolePirate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -937,8 +900,6 @@ public void test233PreviewGuybrushAddRolePirate() throws Exception { */ @Test public void test234PreviewGuybrushAddRolePirateRecon() throws Exception { - final String TEST_NAME = "test234PreviewGuybrushAddRolePirateRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1005,8 +966,6 @@ public void test234PreviewGuybrushAddRolePirateRecon() throws Exception { */ @Test public void test236PreviewGuybrushAddRoleSailor() throws Exception { - final String TEST_NAME = "test236PreviewGuybrushAddRoleSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1058,8 +1017,6 @@ public void test236PreviewGuybrushAddRoleSailor() throws Exception { */ @Test public void test238PreviewGuybrushAddRoleSailorOwner() throws Exception { - final String TEST_NAME = "test238PreviewGuybrushAddRoleSailorOwner"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1095,8 +1052,6 @@ public void test238PreviewGuybrushAddRoleSailorOwner() throws Exception { @Test public void test239GuybrushUnAssignAccountDummy() throws Exception { - final String TEST_NAME = "test239GuybrushUnAssignAccountDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1120,8 +1075,6 @@ public void test239GuybrushUnAssignAccountDummy() throws Exception { */ @Test public void test240GuybrushAssignAccountDummyRelative() throws Exception { - final String TEST_NAME = "test240GuybrushAssignAccountDummyRelative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1148,8 +1101,6 @@ public void test240GuybrushAssignAccountDummyRelative() throws Exception { */ @Test public void test242PreviewGuybrushAddRolePirateRelative() throws Exception { - final String TEST_NAME = "test242PreviewGuybrushAddRolePirateRelative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1215,8 +1166,6 @@ public void test242PreviewGuybrushAddRolePirateRelative() throws Exception { */ @Test public void test244PreviewGuybrushAddRolePirateRelativeRecon() throws Exception { - final String TEST_NAME = "test244PreviewGuybrushAddRolePirateRelativeRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1279,8 +1228,6 @@ public void test244PreviewGuybrushAddRolePirateRelativeRecon() throws Exception @Test public void test249GuybrushUnAssignAccountDummyRelative() throws Exception { - final String TEST_NAME = "test249GuybrushUnAssignAccountDummyRelative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1298,7 +1245,6 @@ public void test249GuybrushUnAssignAccountDummyRelative() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_RELATIVE_NAME, USER_GUYBRUSH_USERNAME); } - private void assertAccountDefaultDummyAttributeModify(ObjectDelta accountDelta, String attrName, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { @@ -1317,14 +1263,13 @@ private void assertAccountItemModify(ObjectDelta accountDelta, ItemPath itemPath, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { PropertyDelta attrDelta = accountDelta.findPropertyDelta(itemPath); - assertNotNull("No delta for "+itemPath+" in "+accountDelta, attrDelta); + assertNotNull("No delta for " + itemPath + " in " + accountDelta, attrDelta); PrismAsserts.assertPropertyDelta(attrDelta, expectedOldValues, expectedAddValues, expectedDeleteValues, expectedReplaceValues); } // MAPPING TESTS // following tests mostly check correct functions of mappings - // the test3xx is testing mappings with default dummy resource. It has NORMAL mappings. /** @@ -1332,8 +1277,6 @@ private void assertAccountItemModify(ObjectDelta accountDelta, */ @Test public void test300ModifyElaineAccountDummyReplace() throws Exception { - final String TEST_NAME = "test300ModifyElaineAccountDummyReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1357,9 +1300,8 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContolle ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -1379,7 +1321,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContolle "Elaine Threepwood"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } /** @@ -1387,8 +1329,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContolle */ @Test public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { - final String TEST_NAME = "test301ModifyElaineAccountDummyDeleteAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1414,9 +1354,8 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -1437,7 +1376,7 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Marley"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } /** @@ -1447,8 +1386,6 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { */ @Test public void test400ModifyElaineAccountDummyRedReplace() throws Exception { - final String TEST_NAME = "test400ModifyElaineAccountDummyRedReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1465,7 +1402,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, getDummyResourceObject(RESOURCE_DUMMY_RED_N ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); // THEN - then(); + then(); display("Preview context", modelContext); assertPartialError(result); } @@ -1477,8 +1414,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, getDummyResourceObject(RESOURCE_DUMMY_RED_N */ @Test public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { - final String TEST_NAME = "test401ModifyElaineAccountDummyRedDeleteAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1498,8 +1433,8 @@ public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { display("Preview context", modelContext); // THEN - then(); - assertPartialError(result); + then(); + assertPartialError(result); } // the test5xx is testing mappings with blue dummy resource. It has WEAK mappings. @@ -1509,8 +1444,6 @@ public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { */ @Test public void test500ModifyElaineAccountDummyBlueReplace() throws Exception { - final String TEST_NAME = "test500ModifyElaineAccountDummyBlueReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1534,7 +1467,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); @@ -1556,7 +1489,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE "Elaine Threepwood"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } /** @@ -1564,8 +1497,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE */ @Test public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { - final String TEST_NAME = "test501ModifyElaineAccountDummyBlueDeleteAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1593,7 +1524,7 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); @@ -1618,17 +1549,14 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { "Elaine Marley"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } - /** * Changing USER fullName (replace delta), no account changes. */ @Test public void test600ModifyElaineUserDummyReplace() throws Exception { - final String TEST_NAME = "test600ModifyElaineUserDummyReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1655,7 +1583,7 @@ public void test600ModifyElaineUserDummyReplace() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); + assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertModifications(userPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(userPrimaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); @@ -1719,8 +1647,6 @@ public void test600ModifyElaineUserDummyReplace() throws Exception { */ @Test public void test610ModifyElaineUserAccountDummyReplace() throws Exception { - final String TEST_NAME = "test610ModifyElaineUserAccountDummyReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1758,7 +1684,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); + assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertModifications(userPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(userPrimaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); @@ -1783,7 +1709,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE "Elaine LeChuck"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); // RED dummy resource: strong mappings accContext = modelContext.findProjectionContext( @@ -1822,8 +1748,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE @Test public void test620AddUserCapsize() throws Exception { - final String TEST_NAME = "test620AddUserCapsize"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1912,8 +1836,6 @@ public void test620AddUserCapsize() throws Exception { // testing multiple resources with dependencies (dummy -> dummy lemon) @Test public void test630AddUserRogers() throws Exception { - final String TEST_NAME = "test630AddUserRogers"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1938,7 +1860,7 @@ public void test630AddUserRogers() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); + assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertIsAdd(userPrimaryDelta); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); @@ -2009,8 +1931,6 @@ public void test630AddUserRogers() throws Exception { */ @Test public void test700DisableElaineAccountTwoResources() throws Exception { - final String TEST_NAME = "test700DisableElaineAccountTwoResources"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2035,7 +1955,7 @@ public void test700DisableElaineAccountTwoResources() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); @@ -2085,8 +2005,6 @@ public void test700DisableElaineAccountTwoResources() throws Exception { */ @Test public void test710PreviewGuybrushHavingRoleSailorOwner() throws Exception { - final String TEST_NAME = "test710PreviewGuybrushHavingRoleSailorOwner"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2121,5 +2039,4 @@ public void test710PreviewGuybrushHavingRoleSailorOwner() throws Exception { assertEquals("Wrong # of zero-set roles in evaluated assignment", 1, evaluatedAssignment.getRoles().getZeroSet().size()); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java index b8156f99141..74213b57f22 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java @@ -13,7 +13,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; @@ -26,10 +25,6 @@ import static org.testng.AssertJUnit.*; -/** - * @author mederly - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRaceConditions extends AbstractInitializedModelIntegrationTest { @@ -50,8 +45,6 @@ protected ConflictResolutionActionType getDefaultConflictResolutionAction() { @Test public void test100AssignRoles() throws Exception { - final String TEST_NAME="test100AssignRoles"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -91,10 +84,8 @@ public void test100AssignRoles() throws Exception { */ @Test public void test110UnassignRoles() throws Exception { - final String TEST_NAME = "test110UnassignRoles"; - // GIVEN - Task task = taskManager.createTaskInstance(TestRaceConditions.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJack = getUser(USER_JACK_OID); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java index 1724860ba06..f194690b17e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java @@ -8,8 +8,6 @@ import static org.testng.AssertJUnit.assertNotNull; -import javax.xml.bind.JAXBException; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -25,30 +23,22 @@ * Test if a resource without a schema can pass basic operations such as getObject and testResource. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSchemalessResource extends AbstractInitializedModelIntegrationTest { - private static String accountOid; - - public TestSchemalessResource() throws JAXBException { - super(); - } - /** * Just test if this does not die on an exception. */ @Test public void test001GetObject() throws Exception { - final String TEST_NAME = "test001GetObject"; - Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_OID, null, task, result); + PrismObject resource = modelService.getObject( + ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_OID, null, task, result); // THEN assertNotNull("Null resource returned", resource); @@ -56,8 +46,6 @@ public void test001GetObject() throws Exception { @Test public void test002TestConnection() throws Exception { - final String TEST_NAME = "test002TestConnection"; - Task task = getTestTask(); // WHEN @@ -72,7 +60,5 @@ public void test002TestConnection() throws Exception { assertSuccess(connectorResult); assertTestResourceFailure(testResult, ConnectorTestOperation.RESOURCE_SCHEMA); assertFailure(testResult); - } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java index a4db2de84f1..b3b5f34a650 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java @@ -10,31 +10,24 @@ import java.io.File; -import com.evolveum.midpoint.model.intest.util.StaticHookRecorder; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import com.evolveum.icf.dummy.resource.DummyResource; +import com.evolveum.midpoint.model.intest.util.StaticHookRecorder; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ChangeType; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { @@ -43,13 +36,10 @@ public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { protected static final File RESOURCE_DUMMY_HOOK_FILE = new File(TEST_DIR, "resource-dummy-hook.xml"); protected static final String RESOURCE_DUMMY_HOOK_OID = "10000000-0000-0000-0000-000004444001"; protected static final String RESOURCE_DUMMY_HOOK_NAME = "hook"; - protected static final String RESOURCE_DUMMY_HOOK_NAMESPACE = MidPointConstants.NS_RI; private static final File ORG_TOP_FILE = new File(TEST_DIR, "org-top.xml"); - private static final String ORG_TOP_OID = "80808080-8888-6666-0000-100000000001"; private static final File GENERIC_BLACK_PEARL_FILE = new File(TEST_DIR, "generic-blackpearl.xml"); - private static final String GENERIC_BLACK_PEARL_OID = "54195419-5419-5419-5419-000000000001"; private static final File SYSTEM_CONFIGURATION_HOOKS_FILE = new File(TEST_DIR, "system-configuration-hooks.xml"); @@ -59,14 +49,15 @@ public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { protected PrismObject resourceDummyHook; @Override - public void initSystem(Task initTask, OperationResult initResult) - throws Exception { + public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - dummyResourceCtlHook = DummyResourceContoller.create(RESOURCE_DUMMY_HOOK_NAME, resourceDummyHook); + dummyResourceCtlHook = DummyResourceContoller.create( + RESOURCE_DUMMY_HOOK_NAME, resourceDummyHook); dummyResourceCtlHook.extendSchemaPirate(); dummyResourceHook = dummyResourceCtlHook.getDummyResource(); - resourceDummyHook = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_HOOK_FILE, RESOURCE_DUMMY_HOOK_OID, initTask, initResult); + resourceDummyHook = importAndGetObjectFromFile(ResourceType.class, + RESOURCE_DUMMY_HOOK_FILE, RESOURCE_DUMMY_HOOK_OID, initTask, initResult); resourceDummyHookType = resourceDummyHook.asObjectable(); dummyResourceCtlHook.setResource(resourceDummyHook); @@ -79,14 +70,10 @@ protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_HOOKS_FILE; } - - @Test public void test100JackAssignHookAccount() throws Exception { - final String TEST_NAME = "test100JackAssignHookAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestScriptHooks.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); dummyAuditService.clear(); @@ -136,10 +123,8 @@ public void test100JackAssignHookAccount() throws Exception { @Test public void test110JackAddOrganization() throws Exception { - final String TEST_NAME = "test110JackAddOrganization"; - // GIVEN - Task task = taskManager.createTaskInstance(TestScriptHooks.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); dummyAuditService.clear(); @@ -180,18 +165,5 @@ public void test110JackAddOrganization() throws Exception { StaticHookRecorder.assertInvocationCount("foo", 10); StaticHookRecorder.assertInvocationCount("bar", 10); StaticHookRecorder.assertInvocationCount("bar-user", 1); - - - // TODO -// // Check audit -// display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(4); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(1,1); -// dummyAuditService.asserHasDelta(1,ChangeType.ADD, OrgType.class); -// dummyAuditService.assertExecutionDeltas(3,1); -// dummyAuditService.asserHasDelta(3,ChangeType.MODIFY, UserType.class); -// dummyAuditService.assertExecutionSuccess(); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java index b4fa08c557f..7eda05a597a 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java @@ -6,19 +6,13 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.Collection; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; import org.apache.commons.lang.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -29,23 +23,21 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestTolerantAttributes extends AbstractInitializedModelIntegrationTest { - public static final File TEST_DIR = new File("src/test/resources/tolerant"); private static final String ACCOUNT_JACK_DUMMY_BLACK_FILENAME = "src/test/resources/common/account-jack-dummy-black.xml"; @@ -57,7 +49,7 @@ public class TestTolerantAttributes extends AbstractInitializedModelIntegrationT public void test100ModifyUserAddAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test100ModifyUserAddAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -70,7 +62,7 @@ public void test100ModifyUserAddAccount() throws Exception { ReferenceDelta accountDelta = prismContext.deltaFactory().reference() .createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); @@ -111,7 +103,7 @@ public void test100ModifyUserAddAccount() throws Exception { // Check account in dummy resource assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - } + } /** * We are trying to add value to the resource (through a mapping). This value matches @@ -120,8 +112,6 @@ public void test100ModifyUserAddAccount() throws Exception { */ @Test public void test101ModifyAddAttributesIntolerantPattern() throws Exception { - final String TEST_NAME = "test101ModifyAddAttributesIntolerantPattern"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -133,7 +123,7 @@ public void test101ModifyAddAttributesIntolerantPattern() throws Exception { UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "This value will be not added"); userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); // WHEN when(); @@ -165,150 +155,148 @@ UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DE } @Test - public void test102modifyAddAttributeTolerantPattern() throws Exception{ + public void test102modifyAddAttributeTolerantPattern() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test102modifyAddAttributeTolerantPattern"); - OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationAddProperty(UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "res-thiIsOk"); - userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - - modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - - result.computeStatus(); - TestUtil.assertSuccess(result); - - // Check value in "quote attribute" - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - assertUserJack(userJack); - UserType userJackType = userJack.asObjectable(); - assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); - accountOid = accountRefType.getOid(); - assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); - assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); - assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - - // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account in dummy resource - assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - - // Check value of quote attribute - assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "quote", "res-thiIsOk"); + Task task = getTestTask(); + OperationResult result = task.getResult(); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); + + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(UserType.class, USER_JACK_OID); + PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationAddProperty(UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "res-thiIsOk"); + userDelta.addModification(propertyDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); + + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); + + result.computeStatus(); + TestUtil.assertSuccess(result); + + // Check value in "quote attribute" + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + assertUserJack(userJack); + UserType userJackType = userJack.asObjectable(); + assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); + ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); + accountOid = accountRefType.getOid(); + assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); + assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); + assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); + + // Check shadow + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account in dummy resource + assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); + + // Check value of quote attribute + assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "quote", "res-thiIsOk"); } @Test - public void test103modifyReplaceAttributeIntolerant() throws Exception{ + public void test103modifyReplaceAttributeIntolerant() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test103modifyReplaceAttributeIntolerant"); - OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); + Task task = getTestTask(); + OperationResult result = task.getResult(); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "gossip-thiIsNotOk"); - userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(UserType.class, USER_JACK_OID); + PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "gossip-thiIsNotOk"); + userDelta.addModification(propertyDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); - modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - result.computeStatus(); - TestUtil.assertSuccess(result); + result.computeStatus(); + TestUtil.assertSuccess(result); - // Check value in "quote attribute" - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + // Check value in "quote attribute" + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); // assertUserJack(userJack); - UserType userJackType = userJack.asObjectable(); - assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); - accountOid = accountRefType.getOid(); - assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); - assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); - assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - - // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account in dummy resource - assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - - // Check value of drink attribute - assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", null); + UserType userJackType = userJack.asObjectable(); + assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); + ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); + accountOid = accountRefType.getOid(); + assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); + assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); + assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); + + // Check shadow + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account in dummy resource + assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); + + // Check value of drink attribute + assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", null); } @Test - public void test104modifyReplaceAttributeTolerantPattern() throws Exception{ + public void test104modifyReplaceAttributeTolerantPattern() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test104modifyReplaceAttributeTolerantPattern"); - OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); + Task task = getTestTask(); + OperationResult result = task.getResult(); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - ItemPath drinkItemPath = ItemPath.create(new QName(getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME).getNamespace(), "drink")); - PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "thiIsOk"); - userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(UserType.class, USER_JACK_OID); + ItemPath drinkItemPath = ItemPath.create(new QName(getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME).getNamespace(), "drink")); + PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "thiIsOk"); + userDelta.addModification(propertyDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); - modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - result.computeStatus(); - TestUtil.assertSuccess(result); + result.computeStatus(); + TestUtil.assertSuccess(result); - // Check value in "quote attribute" - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + // Check value in "quote attribute" + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); // assertUserJack(userJack); - UserType userJackType = userJack.asObjectable(); - assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); - accountOid = accountRefType.getOid(); - assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); - assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); - assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - - // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account in dummy resource - assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - - // Check value of drink attribute - assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", "thiIsOk"); + UserType userJackType = userJack.asObjectable(); + assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); + ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); + accountOid = accountRefType.getOid(); + assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); + assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); + assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); + + // Check shadow + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account in dummy resource + assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); + + // Check value of drink attribute + assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", "thiIsOk"); } @Test public void test105ModifyAddNonTolerantAttribute() throws Exception { - final String TEST_NAME = "test105ModifyAddNonTolerantAttribute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test105modifyAddNonTolerantAttribute"); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -319,7 +307,7 @@ public void test105ModifyAddNonTolerantAttribute() throws Exception { assertNotNull("null definition for drink attribute ", accountDefinition.findPropertyDefinition(drinkItemPath)); PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationAddProperty(drinkItemPath, accountDefinition.findPropertyDefinition(drinkItemPath), "This should be ignored"); userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); // WHEN when(); @@ -329,6 +317,4 @@ public void test105ModifyAddNonTolerantAttribute() throws Exception { then(); assertPartialError(result); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java index fcdffed8f4c..f8ccdb4bb36 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java @@ -6,24 +6,15 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.ItemFactory; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.test.TestResource; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - import org.apache.commons.lang3.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -35,8 +26,14 @@ import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.common.expression.evaluator.GenerateExpressionEvaluator; import com.evolveum.midpoint.model.impl.trigger.RecomputeTriggerHandler; +import com.evolveum.midpoint.prism.ItemFactory; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismValue; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; @@ -48,21 +45,17 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { @@ -78,6 +71,7 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { protected static final String USER_TEMPLATE_USELESS_OID = "29b2936a-d1f6-4942-8e44-9ba44fc27423"; protected static final TestResource USER_TEMPLATE_MID_5892 = new TestResource(TEST_DIR, "user-template-mid-5892.xml", "064993c0-34b4-4440-9331-e909fc923504"); + private static final TestResource USER_TEMPLATE_MID_6045 = new TestResource(TEST_DIR, "user-template-mid-6045.xml", "f3dbd582-11dc-473f-8b51-a30be5cbd5ce"); private static final String ACCOUNT_STAN_USERNAME = "stan"; private static final String ACCOUNT_STAN_FULLNAME = "Stan the Salesman"; @@ -85,6 +79,7 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { private static final String SUBTYPE_MAROONED = "marooned"; private static final String SUBTYPE_USELESS = "useless"; private static final String SUBTYPE_MID_5892 = "mid-5892"; + private static final String SUBTYPE_MID_6045 = "mid-6045"; private static final int NUMBER_OF_IMPORTED_ROLES = 5; @@ -96,6 +91,8 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { private static final String CANNIBAL_PINEAPPLENOSE_USERNAME = "pineapplenose"; private static final String CANNIBAL_POTATOLEG_USERNAME = "potatoleg"; + private static final long DAY_MILLIS = 24 * 60 * 60 * 1000L; + private static String jackEmployeeNumber; private XMLGregorianCalendar funeralTimestamp; @@ -114,11 +111,13 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(USER_TEMPLATE_MAROONED_FILE, initResult); repoAddObjectFromFile(USER_TEMPLATE_USELESS_FILE, initResult); repoAdd(USER_TEMPLATE_MID_5892, initResult); + repoAdd(USER_TEMPLATE_MID_6045, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_COMPLEX_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_MAROONED, USER_TEMPLATE_MAROONED_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_USELESS, USER_TEMPLATE_USELESS_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_MID_5892, USER_TEMPLATE_MID_5892.oid, initResult); + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_MID_6045, USER_TEMPLATE_MID_6045.oid, initResult); } protected int getNumberOfRoles() { @@ -145,25 +144,26 @@ public void test000Sanity() throws Exception { assertNotNull("no system config", systemConfiguration); List defaultObjectPolicyConfiguration = systemConfiguration.asObjectable().getDefaultObjectPolicyConfiguration(); assertNotNull("No object policy", defaultObjectPolicyConfiguration); - assertEquals("Wrong object policy size", 6, defaultObjectPolicyConfiguration.size()); // last two are conflict resolution rules + assertEquals("Wrong object policy size", 7, defaultObjectPolicyConfiguration.size()); // last two are conflict resolution rules assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, null, USER_TEMPLATE_COMPLEX_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_MAROONED, USER_TEMPLATE_MAROONED_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_USELESS, USER_TEMPLATE_USELESS_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_MID_5892, USER_TEMPLATE_MID_5892.oid); + assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_MID_6045, USER_TEMPLATE_MID_6045.oid); assertRoles(getNumberOfRoles()); } private void assertObjectTemplate(List defaultObjectPolicyConfigurations, QName objectType, String subtype, String userTemplateOid) { - for (ObjectPolicyConfigurationType objectPolicyConfiguration: defaultObjectPolicyConfigurations) { + for (ObjectPolicyConfigurationType objectPolicyConfiguration : defaultObjectPolicyConfigurations) { if (MiscUtil.equals(objectPolicyConfiguration.getType(), objectType) && MiscUtil.equals(objectPolicyConfiguration.getSubtype(), subtype) && MiscUtil.equals(objectPolicyConfiguration.getObjectTemplateRef().getOid(), userTemplateOid)) { return; } } - AssertJUnit.fail("Object template for "+objectType+":"+subtype+"="+userTemplateOid+" not found"); + AssertJUnit.fail("Object template for " + objectType + ":" + subtype + "=" + userTemplateOid + " not found"); } @Test @@ -254,7 +254,7 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { /** * Switch employeeType from PIRATE to BUCCANEER. This makes one condition to go false and the other to go - * true. For the same role assignement value. So nothing should be changed. + * true. For the same role assignment value. So nothing should be changed. */ @Test public void test102ModifyUserEmployeeTypeBuccaneer() throws Exception { @@ -618,7 +618,7 @@ public void test149UnAssignDummy() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @@ -653,7 +653,6 @@ public void test150ModifyJackOrganizationalUnitRum() throws Exception { assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @Test @@ -687,7 +686,6 @@ public void test151ModifyJackOrganizationalUnitOffense() throws Exception { assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @Test @@ -724,7 +722,6 @@ public void test152ModifyJackOrganizationalUnitAddRum() throws Exception { assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @Test @@ -756,8 +753,7 @@ public void test153ModifyJackOrganizationalUnitDeleteOffense() throws Exception assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } /** @@ -795,8 +791,7 @@ public void test155ModifyJackOrganizationalUnitFD001() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } /** @@ -834,7 +829,7 @@ public void test156ReconcileJack() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } /** @@ -876,8 +871,7 @@ public void test157ModifyJackOrganizationalUnitFD0023() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } @Test @@ -917,8 +911,7 @@ public void test159ModifyJackDeleteOrganizationalUnitFD002() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } @Test @@ -951,8 +944,10 @@ public void test160ModifyUserGivenNameAgain() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); - ObjectDeltaOperation objectDeltaOperation = dummyAuditService.getExecutionDelta(0, ChangeType.MODIFY, UserType.class); - assertEquals("unexpected number of modifications in audited delta", 10, objectDeltaOperation.getObjectDelta().getModifications().size()); // givenName + badLuck + modifyTimestamp + ObjectDeltaOperation objectDeltaOperation = + dummyAuditService.getExecutionDelta(0, ChangeType.MODIFY, UserType.class); + assertEquals("unexpected number of modifications in audited delta", + 10, objectDeltaOperation.getObjectDelta().getModifications().size()); // givenName + badLuck + modifyTimestamp PropertyDelta badLuckDelta = objectDeltaOperation.getObjectDelta().findPropertyDelta( ItemPath.create(UserType.F_EXTENSION, PIRACY_BAD_LUCK)); assertNotNull("badLuck delta was not found", badLuckDelta); @@ -960,8 +955,8 @@ public void test160ModifyUserGivenNameAgain() throws Exception { List oldValues = (List) badLuckDelta.getEstimatedOldValues(); assertNotNull("badLuck delta has null estimatedOldValues field", oldValues); ItemFactory factory = prismContext.itemFactory(); - PrismAsserts.assertEqualsCollectionUnordered("badLuck delta has wrong estimatedOldValues", oldValues, - factory.createPropertyValue(123L), factory.createPropertyValue(456L)); + PrismAsserts.assertEqualsCollectionUnordered("badLuck delta has wrong estimatedOldValues", + oldValues, factory.createPropertyValue(123L), factory.createPropertyValue(456L)); } @Test @@ -970,14 +965,16 @@ public void test162ModifyUserGivenNameAgainPhantomChange() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_JACK_OID, null, task, result); display("User before", userBefore); dummyAuditService.clear(); Collection> deltas = new ArrayList<>(); - ObjectDelta userDelta = prismContext.deltaFactory().object().createModificationReplaceProperty(UserType.class, - USER_JACK_OID, UserType.F_GIVEN_NAME, new PolyString("JACKIE")); // this is a phantom change + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationReplaceProperty( + UserType.class, USER_JACK_OID, UserType.F_GIVEN_NAME, new PolyString("JACKIE")); // this is a phantom change deltas.add(userDelta); // WHEN @@ -1030,17 +1027,21 @@ public void test165ModifyUserGivenNameAgainAgain() throws Exception { PrismAsserts.assertNoItem(userJack, ItemPath.create(UserType.F_EXTENSION, PIRACY_BAD_LUCK)); } - private PrismObject assertOnDemandOrgExists(String orgName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private PrismObject assertOnDemandOrgExists(String orgName) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject org = findObjectByName(OrgType.class, orgName); - assertNotNull("The org "+orgName+" is missing!", org); - display("Org "+orgName, org); + assertNotNull("The org " + orgName + " is missing!", org); + display("Org " + orgName, org); PrismAsserts.assertPropertyValue(org, OrgType.F_NAME, PrismTestUtil.createPolyString(orgName)); return org; } - private void assertOnDemandOrgAssigned(String orgName, PrismObject user) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void assertOnDemandOrgAssigned(String orgName, PrismObject user) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject org = assertOnDemandOrgExists(orgName); - PrismAsserts.assertPropertyValue(org, OrgType.F_DESCRIPTION, "Created on demand from user "+user.asObjectable().getName()); + PrismAsserts.assertPropertyValue(org, OrgType.F_DESCRIPTION, "Created on demand from user " + user.asObjectable().getName()); assertAssignedOrg(user, org.getOid()); assertHasOrg(user, org.getOid()); } @@ -1125,7 +1126,8 @@ public void test174ModifyUserGuybrushHonorificPrefixNone() throws Exception { then(); assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); assertAssignedNoRole(userAfter); @@ -1191,7 +1193,6 @@ public void test184ModifyUserGuybrushEmployeeTypeNone() throws Exception { assertEquals("Wrong costCenter", "S321", userAfter.asObjectable().getCostCenter()); - assertAssignedNoRole(userAfter); } @@ -1252,8 +1253,6 @@ public void test189ModifyUserGuybrushSubtypeNone() throws Exception { assertAssignedNoRole(userAfter); } - - /** * Assignment mapping with domain. Control: nothing should happen. * MID-3692 @@ -1341,8 +1340,7 @@ public void test192ModifyUserGuybrushOrganizationAddMixed() throws Exception { createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), createPolyString("plutocratic"), - createPolyString("AUTO-didactic") - ); + createPolyString("AUTO-didactic")); // THEN then(); @@ -1358,8 +1356,7 @@ public void test192ModifyUserGuybrushOrganizationAddMixed() throws Exception { createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), createPolyString("plutocratic"), - createPolyString("AUTO-didactic") - ); + createPolyString("AUTO-didactic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); @@ -1387,8 +1384,7 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti when(); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("meritocratic"), - createPolyString("piratocratic") - ); + createPolyString("piratocratic")); // THEN then(); @@ -1406,8 +1402,7 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti createPolyString("plutocratic"), createPolyString("AUTO-didactic"), createPolyString("meritocratic"), - createPolyString("piratocratic") - ); + createPolyString("piratocratic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); @@ -1437,23 +1432,22 @@ public void test194ModifyUserGuybrushOrganizationDeleteMixed() throws Exception createPolyString("AUTO-matic"), createPolyString("plutocratic"), createPolyString("meritocratic"), - createPolyString("AUTO-didactic") - ); + createPolyString("AUTO-didactic")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), - createPolyString("piratocratic") - ); + createPolyString("piratocratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignments(userAfter, 2); @@ -1479,21 +1473,20 @@ public void test195ModifyUserGuybrushOrganizationDeleteOutOfDomain() throws Exce when(); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("piratocratic"), - createPolyString("DEMO-cratic") - ); + createPolyString("DEMO-cratic")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), - createPolyString("AUTO-cratic") - ); + createPolyString("AUTO-cratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignments(userAfter, 2); @@ -1525,13 +1518,13 @@ public void test196GuybrushAssignCaptain() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), - createPolyString("AUTO-cratic") - ); + createPolyString("AUTO-cratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); @@ -1553,20 +1546,20 @@ public void test197ModifyGuybrushEmployeeTypePirate() throws Exception { // WHEN when(); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "PIRATE"); + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "PIRATE"); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), - createPolyString("AUTO-cratic") - ); + createPolyString("AUTO-cratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); @@ -1595,23 +1588,22 @@ public void test198AModifyUserGuybrushOrganizationAddInDomain() throws Exception when(); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("AUTO-cratic"), createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); @@ -1642,21 +1634,20 @@ public void test198BModifyUserGuybrushOrganizationDeleteMixed() throws Exception when(); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("AUTO-cratic"), - createPolyString("Whateveric") - ); + createPolyString("Whateveric")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); @@ -1683,20 +1674,20 @@ public void test199AGuyBrushModifyEmployeeTypeWannabe() throws Exception { // WHEN when(); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "wannabe"); + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "wannabe"); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); @@ -1729,13 +1720,13 @@ public void test199BGuyBrushUnassignCaptain() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); @@ -1766,7 +1757,8 @@ public void test199CModifyUserGuybrushOrganizationCleanup() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertNoItem(userAfter, UserType.F_ORGANIZATION); @@ -1791,7 +1783,8 @@ public void test200AddUserRapp() throws Exception { modelService.executeChanges(deltas, null, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); PrismAsserts.assertNoItem(userAfter, UserType.F_DESCRIPTION); @@ -1827,7 +1820,8 @@ public void test201AddUserLargo() throws Exception { modelService.executeChanges(deltas, null, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_LARGO_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_LARGO_OID, null, task, result); display("Largo after", userAfter); assertUser(userAfter, USER_LARGO_OID, "largo", "Largo LaGrande", "Largo", "LaGrande"); @@ -1870,7 +1864,8 @@ public void test202AddUserMonkey() throws Exception { modelService.executeChanges(deltas, null, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_THREE_HEADED_MONKEY_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_THREE_HEADED_MONKEY_OID, null, task, result); display("User after", userAfter); // assertUser(userAfter, USER_THREE_HEADED_MONKEY_OID, "monkey", " Monkey", null, "Monkey"); assertUser(userAfter, USER_THREE_HEADED_MONKEY_OID, "monkey", "Three-Headed Monkey", null, "Monkey"); @@ -1987,7 +1982,6 @@ public void test229UnassignRoleSailorFromUserRapp() throws Exception { assertEquals("Wrong costCenter", "G001", userAfterType.getCostCenter()); } - /** * Role Captains has focus mapping for the same costCenter as is given * by the user template. @@ -2034,7 +2028,8 @@ public void test232ModifyUserRappCostCenter() throws Exception { modifyUserReplace(USER_RAPP_OID, UserType.F_COST_CENTER, task, result, "CC-RAPP"); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2067,7 +2062,8 @@ public void test239UnassignRoleCaptainFromUserRapp() throws Exception { unassignRole(USER_RAPP_OID, ROLE_CAPTAIN_OID, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); @@ -2092,20 +2088,23 @@ public void test240ModifyUserRappLocalityScabb() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); assertEquals("Wrong timezone", "High Seas/null", userBefore.asObjectable().getTimezone()); - assertEquals("Wrong locale", null, userBefore.asObjectable().getLocale()); + assertNull("Wrong locale", userBefore.asObjectable().getLocale()); // WHEN - modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Scabb Island")); + modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, + task, result, PrismTestUtil.createPolyString("Scabb Island")); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2123,7 +2122,6 @@ public void test240ModifyUserRappLocalityScabb() throws Exception { assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - /** * Role Rastaman has focus mapping for the same timezone as is given * by the user template. This mapping is normal strength. Even though @@ -2144,7 +2142,8 @@ public void test242AssignRoleRastamanToUserRapp() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2175,17 +2174,20 @@ public void test244ModifyUserRappLocalityCoffin() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); // WHEN - modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Coffin")); + modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, + task, result, PrismTestUtil.createPolyString("Coffin")); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2213,11 +2215,12 @@ public void test245ModifyUserRappLocalityUnderReconcile() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_RAPP_OID, UserType.F_LOCALITY, - PrismTestUtil.createPolyString("Six feet under")); + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_RAPP_OID, + UserType.F_LOCALITY, PrismTestUtil.createPolyString("Six feet under")); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); @@ -2228,7 +2231,8 @@ public void test245ModifyUserRappLocalityUnderReconcile() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2258,7 +2262,8 @@ public void test246ModifyUserRappTimezoneMonkey() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); // WHEN @@ -2268,7 +2273,8 @@ public void test246ModifyUserRappTimezoneMonkey() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2298,7 +2304,8 @@ public void test247ModifyUserRappLocaleMI() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); // WHEN @@ -2308,7 +2315,8 @@ public void test247ModifyUserRappLocaleMI() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2342,7 +2350,8 @@ public void test249UnassignRoleRastamanFromUserRapp() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); PrismAsserts.assertNoItem(userAfter, UserType.F_DESCRIPTION); @@ -2354,10 +2363,8 @@ public void test249UnassignRoleRastamanFromUserRapp() throws Exception { assertLinks(userAfter, 1); // Role is unassigned. The mapping was authoritative, so it removed the value - assertEquals("Wrong timezone", null, userAfterType.getTimezone()); - + assertNull("Wrong timezone", userAfterType.getTimezone()); assertEquals("Wrong locale", "MI", userAfterType.getLocale()); - assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); @@ -2459,6 +2466,7 @@ public void test800NullTimeFrom() throws Exception { waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName(USER_JACK_ADDITIONAL_NAME) .extension() @@ -2466,6 +2474,7 @@ public void test800NullTimeFrom() throws Exception { .assertNoItem(PIRACY_LOOT) .end() .assertNoTrigger(); + // @formatter:on } /** @@ -2484,6 +2493,7 @@ public void test802FuneralTimestamp() throws Exception { waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName(USER_JACK_ADDITIONAL_NAME) .extension() @@ -2494,6 +2504,7 @@ public void test802FuneralTimestamp() throws Exception { .single() .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) .assertTimestampFuture(funeralTimestamp, "P1M", 10*1000L); + // @formatter:on } /** @@ -2501,21 +2512,21 @@ public void test802FuneralTimestamp() throws Exception { */ @Test public void test804PreKaboom() throws Exception { - final String TEST_NAME = "test804PreKaboom"; - // GIVEN - clockForward("P2D"); // total override is realTime + 2D + clockForward("P2D"); // total override is realTime + 2D // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName(USER_JACK_ADDITIONAL_NAME) .triggers() .single() .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture("P30D", 5*24*60*60*1000L); + .assertTimestampFuture("P30D", 5 * DAY_MILLIS); + // @formatter:on } /** @@ -2523,15 +2534,14 @@ public void test804PreKaboom() throws Exception { */ @Test public void test808Kaboom() throws Exception { - final String TEST_NAME = "test808Kaboom"; - // GIVEN - clockForward("P1M"); // total override is realTime + 2D + 1M + clockForward("P1M"); // total override is realTime + 2D + 1M // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2542,7 +2552,8 @@ public void test808Kaboom() throws Exception { // Trigger for "tales bomb" mapping (see below) - it was computed as funeralTimestamp + 3M // (i.e. should be approximately equal to clock + 2M - 2D, because clock = realTime + 2D + 1M) .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture("P2M", 5*24*60*60*1000L); + .assertTimestampFuture("P2M", 5 * DAY_MILLIS); + // @formatter:on } /** @@ -2553,15 +2564,14 @@ public void test808Kaboom() throws Exception { */ @Test public void test810PreTalesBomb() throws Exception { - final String TEST_NAME = "test810PreTalesBomb"; - // GIVEN - clockForward("P1D"); // total override is realTime + 2D + 1M + 1D + clockForward("P1D"); // total override is realTime + 2D + 1M + 1D // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2581,7 +2591,8 @@ public void test810PreTalesBomb() throws Exception { // // So setting the tolerance to 7 days should be good enough. .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture("P2M", 7*24*60*60*1000L); + .assertTimestampFuture("P2M", 7 * DAY_MILLIS); + // @formatter:on } /** @@ -2590,8 +2601,6 @@ public void test810PreTalesBomb() throws Exception { */ @Test public void test812TalesBoom() throws Exception { - final String TEST_NAME = "test812TalesBoom"; - // GIVEN clockForward("P3M"); @@ -2599,6 +2608,7 @@ public void test812TalesBoom() throws Exception { waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2606,6 +2616,7 @@ public void test812TalesBoom() throws Exception { .end() .triggers() .assertNone(); + // @formatter:on } /** @@ -2614,14 +2625,13 @@ public void test812TalesBoom() throws Exception { */ @Test public void test813TalesBoomRecompute() throws Exception { - final String TEST_NAME = "test813TalesBoomRecompute"; - // GIVEN // WHEN recomputeUser(USER_JACK_OID); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2641,7 +2651,7 @@ public void test813TalesBoomRecompute() throws Exception { .end() .triggers() .assertNone(); - + // @formatter:on } /** @@ -2658,11 +2668,11 @@ public void test820TalesUnBoom() throws Exception { // The tales mapping is normal. Therefore primary delta will override it. assertUserBefore(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertNoItem(PIRACY_TALES) .end() - .triggers() + .triggers() .assertNone(); // WHEN @@ -2671,11 +2681,11 @@ public void test820TalesUnBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .end() - .triggers() + .triggers() .assertNone(); // WHEN @@ -2683,11 +2693,11 @@ public void test820TalesUnBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .end() - .triggers() + .triggers() .assertNone(); } @@ -2707,16 +2717,15 @@ public void test830PreLootBoom() throws Exception { // The tales mapping is normal. Therefore primary delta will override it. assertUserBefore(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 2*24*60*60*1000L); - + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", 2 * DAY_MILLIS); // WHEN // No delta here. The normal tales mapping will fire again. @@ -2724,30 +2733,30 @@ public void test830PreLootBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 2*24*60*60*1000L); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", 2 * DAY_MILLIS); // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 2*24*60*60*1000L); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", 2 * DAY_MILLIS); } @@ -2758,8 +2767,6 @@ public void test830PreLootBoom() throws Exception { */ @Test public void test832LootBoomConditionFalse() throws Exception { - final String TEST_NAME = "test832LootBoomConditionFalse"; - // GIVEN clockForward("P9M"); @@ -2768,23 +2775,23 @@ public void test832LootBoomConditionFalse() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -2803,23 +2810,23 @@ public void test835LootBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); } @@ -2839,14 +2846,14 @@ public void test840ResetFuneralTimestamp() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() // We have Kaboom. And no funeral timestamp. Tales mapping should be applied. .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // All conditions are satisfied. And no funeral timestamp. Loot mapping should be applied. .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); } @@ -2865,23 +2872,23 @@ public void test843UnLoot() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -2900,23 +2907,23 @@ public void test845ReLoot() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); } @@ -2937,14 +2944,14 @@ public void test850AddCannibalLemonhead() throws Exception { assertSuccess(result); assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -2965,18 +2972,18 @@ public void test852AddCanibalRedSkull() throws Exception { assertSuccess(result); assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from time bomb. There is no condition and the reference time is set. - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1M", 24*60*60*1000L); + // Trigger from time bomb. There is no condition and the reference time is set. + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1M", DAY_MILLIS); } /** @@ -2997,19 +3004,19 @@ public void test854AddCanibalShaprtooth() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Time is not up for tales bomb to explode. .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from tales bomb. We have Kaboomed, the time constraint has activated - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P3M", 24*60*60*1000L); + // Trigger from tales bomb. We have Kaboomed, the time constraint has activated + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P3M", DAY_MILLIS); } /** @@ -3030,15 +3037,15 @@ public void test856AddCanibalOrangeskin() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. .assertNone(); } @@ -3061,15 +3068,15 @@ public void test858AddCanibalCherrybrain() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. But description does not match and condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); @@ -3090,22 +3097,22 @@ public void test859AddCanibalPineapplenose() throws Exception { // WHEN String userOid = addObject( createCannibal(CANNIBAL_PINEAPPLENOSE_USERNAME, "-P1Y1D", false) - .asObjectable().givenName("Lootjack").asPrismObject(), + .asObjectable().givenName("Lootjack").asPrismObject(), task, result); // THEN assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. But description does not match and condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); @@ -3128,14 +3135,14 @@ public void test860AddCannibalRottenLemonhead() throws Exception { assertSuccess(result); assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -3155,19 +3162,21 @@ public void test862AddCanibalRottenRedSkull() throws Exception { // THEN assertSuccess(result); + // @formatter:on assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from time bomb. There is no condition and the reference time is set. - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1M", 1*24*60*60*1000L); + // Trigger from time bomb. There is no condition and the reference time is set. + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1M", DAY_MILLIS); + // @formatter:off } /** @@ -3176,7 +3185,7 @@ public void test862AddCanibalRottenRedSkull() throws Exception { * MID-4630 */ @Test - public void test864AddCanibalRottenShaprtooth() throws Exception { + public void test864AddCannibalRottenSharptooth() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = getTestOperationResult(); @@ -3187,6 +3196,7 @@ public void test864AddCanibalRottenShaprtooth() throws Exception { // THEN assertSuccess(result); + // @formatter:off assertUserAfter(userOid) // Time bomb exploded .assertAdditionalName("Kaboom!") @@ -3203,14 +3213,15 @@ public void test864AddCanibalRottenShaprtooth() throws Exception { .find() // Trigger from tales bomb. We have Kaboomed, the time constraint has activated .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P3M", 1*24*60*60*1000L) + .assertTimestampFuture(funeralTimestamp, "P3M", DAY_MILLIS) .end() .by() .originDescription("loot bomb") .find() // Trigger from loot bomb. We have Kaboomed and we have the right description, the time constraint has activated .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 1*24*60*60*1000L); + .assertTimestampFuture(funeralTimestamp, "P1Y", DAY_MILLIS); + // @formatter:on } /** @@ -3231,19 +3242,19 @@ public void test866AddCanibalRottenOrangeskin() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from loot bomb. We have Kaboomed and we have the right description, the time constraint has activated - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 1*24*60*60*1000L); + // Trigger from loot bomb. We have Kaboomed and we have the right description, the time constraint has activated + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", DAY_MILLIS); } /** @@ -3265,15 +3276,15 @@ public void test868AddCanibalRottenCherrybrain() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. But description does not match and condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. We are already after timeFrom. .assertNone(); } @@ -3292,22 +3303,22 @@ public void test869AddCanibalRottenPineapplenose() throws Exception { // WHEN String userOid = addObject( createCannibal(CANNIBAL_PINEAPPLENOSE_USERNAME, "-P1Y1D", true) - .asObjectable().givenName("Lootjack").asPrismObject(), + .asObjectable().givenName("Lootjack").asPrismObject(), task, result); // THEN assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. Description matches and condition is true. .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); @@ -3327,12 +3338,13 @@ public void test870AddCanibalRottenPotatoleg() throws Exception { // WHEN String userOid = addObject( createCannibal(CANNIBAL_POTATOLEG_USERNAME, null, true) - .asObjectable().givenName("Lootjack").asPrismObject(), + .asObjectable().givenName("Lootjack").asPrismObject(), task, result); // THEN assertSuccess(result); + // @formatter:off assertUserAfter(userOid) // No funeralTime, no explosion .assertNoAdditionalName() @@ -3340,12 +3352,13 @@ public void test870AddCanibalRottenPotatoleg() throws Exception { // No kaboom, no explosion .assertNoItem(PIRACY_TALES) // No funeral time, description matches and condition is true. - .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) + .assertPropertyValuesEqual(PIRACY_LOOT, 1_000_000) .end() .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); + // @formatter:on } private PrismObject createCannibal(String name, String funeralDateOffset, boolean rotten) throws SchemaException { @@ -3389,7 +3402,7 @@ public void test900DeleteUser() throws Exception { try { PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); display("User after", userJack); - assert false : "User was not deleted: "+userJack; + assert false : "User was not deleted: " + userJack; } catch (ObjectNotFoundException e) { // This is expected } @@ -3454,7 +3467,7 @@ public void test952ModifyJackOrganizationalUnitFD004() throws Exception { assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); PrismObject org = findObjectByName(OrgType.class, "FD004"); - assertNull("Found org "+org+" but not expecting it", org); + assertNull("Found org " + org + " but not expecting it", org); } /** @@ -3476,10 +3489,10 @@ public void test960ReconcileUserJackWithTemplate() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - display("User after", userJack); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + display("User after", userJack); - PrismAsserts.assertPropertyValue(userJack, UserType.F_DESCRIPTION, "Where's the rum?"); + PrismAsserts.assertPropertyValue(userJack, UserType.F_DESCRIPTION, "Where's the rum?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertOnDemandOrgAssigned("FD004", userJack); @@ -3529,7 +3542,7 @@ public void test980DeleteUserGivenName() throws Exception { .givenName("jim") .subtype(SUBTYPE_MID_5892) .beginAssignment() - .targetRef(SystemObjectsType.ROLE_SUPERUSER.value(), RoleType.COMPLEX_TYPE) + .targetRef(SystemObjectsType.ROLE_SUPERUSER.value(), RoleType.COMPLEX_TYPE) .end(); repositoryService.addObject(user.asPrismObject(), null, result); @@ -3544,15 +3557,49 @@ public void test980DeleteUserGivenName() throws Exception { then(); assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, user.getOid(), null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, user.getOid(), null, task, result); display("User after", userAfter); - AssignmentType assignment = assertAssignedRole(userAfter, SystemObjectsType.ROLE_SUPERUSER.value()); + assertAssignedRole(userAfter, SystemObjectsType.ROLE_SUPERUSER.value()); } -// @Override -// protected TracingProfileType getTestMethodTracingProfile() { -// return createModelLoggingTracingProfile() -// .fileNamePattern(TEST_METHOD_TRACING_FILENAME_PATTERN); -// } + /** + * MID-6045 + */ + @Test + public void test990SpecialTimedMapping() throws Exception { + Task task = getTestTask(); + OperationResult result = task.getResult(); + + clock.resetOverride(); + + XMLGregorianCalendar firstTriggerTime = XmlTypeConverter.fromNow("PT1M"); + + UserType user = new UserType(prismContext) + .name("test990SpecialTimedMapping") + .givenName("jim") + .subtype(SUBTYPE_MID_6045) + .beginTrigger() + .timestamp(firstTriggerTime) + .handlerUri(RecomputeTriggerHandler.HANDLER_URI) + .end() + .beginAssignment() + .targetRef(SystemObjectsType.ROLE_SUPERUSER.value(), RoleType.COMPLEX_TYPE) + .end(); + repositoryService.addObject(user.asPrismObject(), null, result); + + when(); + recomputeUser(user.getOid(), task, result); + + then(); + assertSuccess(result); + + assertUser(user.getOid(), "user after") + .display() + .triggers() + .assertTriggers(3) // for some reason two new triggers are created + .end() + .assertAssignments(1); + } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java index 012a91338dc..33e10fa5971 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java @@ -6,6 +6,15 @@ */ package com.evolveum.midpoint.model.intest; +import java.io.File; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.polystring.PolyString; @@ -15,24 +24,15 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.File; +import com.evolveum.midpoint.util.exception.CommonException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * User template with "mapping range" features. - * - * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUserTemplateWithRanges extends AbstractInitializedModelIntegrationTest { @@ -81,10 +81,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100RecomputeElaine() throws Exception { - final String TEST_NAME = "test100RecomputeElaine"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -106,10 +104,8 @@ public void test100RecomputeElaine() throws Exception { */ @Test public void test110ChangeManagerAndRecomputeElaine() throws Exception { - final String TEST_NAME = "test110ChangeManagerAndRecomputeElaine"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -133,10 +129,8 @@ public void test110ChangeManagerAndRecomputeElaine() throws Exception { */ @Test public void test120RestoreManagerAndRecomputeElaineAgain() throws Exception { - final String TEST_NAME = "test120RestoreManagerAndRecomputeElaineAgain"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assignOrg(USER_ELAINE_OID, ORG_GOVERNOR_OFFICE_OID, null); @@ -164,10 +158,8 @@ public void test120RestoreManagerAndRecomputeElaineAgain() throws Exception { */ @Test public void test140ChangeManagerAndRecomputeElaineAgain() throws Exception { - final String TEST_NAME = "test140ChangeManagerAndRecomputeElaineAgain"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -197,8 +189,6 @@ public void test140ChangeManagerAndRecomputeElaineAgain() throws Exception { */ @Test public void test200SimpleOrgUnitAddition() throws Exception { - final String TEST_NAME = "test200SimpleOrgUnitAddition"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -206,8 +196,8 @@ public void test200SimpleOrgUnitAddition() throws Exception { // WHEN executeChanges( deltaFor(UserType.class) - .item(UserType.F_ORGANIZATIONAL_UNIT).add( - PolyString.fromOrig("U1"), + .item(UserType.F_ORGANIZATIONAL_UNIT) + .add(PolyString.fromOrig("U1"), PolyString.fromOrig("U2"), PolyString.fromOrig("U3"), PolyString.fromOrig("U4")) @@ -239,8 +229,6 @@ public void test200SimpleOrgUnitAddition() throws Exception { */ @Test public void test210RemoveUnit1() throws Exception { - final String TEST_NAME = "test210RemoveUnit1"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -278,8 +266,6 @@ public void test210RemoveUnit1() throws Exception { */ @Test public void test220RemoveUnit2AndNumber() throws Exception { - final String TEST_NAME = "test220RemoveUnit2AndNumber"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -317,8 +303,6 @@ public void test220RemoveUnit2AndNumber() throws Exception { */ @Test public void test230RestoreNumber() throws Exception { - final String TEST_NAME = "test230RestoreNumber"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -352,8 +336,6 @@ public void test230RestoreNumber() throws Exception { @Test public void test300GuybrushBloodyNose() throws Exception { - final String TEST_NAME = "test300GuybrushBloodyNose"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -370,6 +352,7 @@ public void test300GuybrushBloodyNose() throws Exception { then(); assertSuccess(result); + // @formatter:off assertUserAfter(USER_GUYBRUSH_OID) .assertTitle(ROLE_BLOODY_NOSE_NAME) .assignments() @@ -378,13 +361,11 @@ public void test300GuybrushBloodyNose() throws Exception { .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) .activation() .assertNoValidTo(); - + // @formatter:on } @Test public void test309GuybrushNotBloody() throws Exception { - final String TEST_NAME = "test309GuybrushNotBloody"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -402,16 +383,12 @@ public void test309GuybrushNotBloody() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertNoTitle() - .assignments() - .assertNone(); - + .assertNoTitle() + .assignments().assertNone(); } @Test public void test310GuybrushBloodyNoseFuneral() throws Exception { - final String TEST_NAME = "test310GuybrushBloodyNoseFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -432,20 +409,18 @@ public void test310GuybrushBloodyNoseFuneral() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertTitle(ROLE_BLOODY_NOSE_NAME) - .assignments() + .assertTitle(ROLE_BLOODY_NOSE_NAME) + .assignments() .single() - .assertTargetOid(ROLE_BLOODY_NOSE_OID) - .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) - .activation() - .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); + .assertTargetOid(ROLE_BLOODY_NOSE_OID) + .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) + .activation() + .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); } @Test public void test319GuybrushNoBloodyNoseFuneral() throws Exception { - final String TEST_NAME = "test319GuybrushNoBloodyNoseFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -463,16 +438,14 @@ public void test319GuybrushNoBloodyNoseFuneral() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertNoTitle() - .assignments() + .assertNoTitle() + .assignments() .assertNone(); } @Test public void test320GuybrushBloodyNose() throws Exception { - final String TEST_NAME = "test320GuybrushBloodyNose"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -493,20 +466,18 @@ public void test320GuybrushBloodyNose() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertTitle(ROLE_BLOODY_NOSE_NAME) - .assignments() + .assertTitle(ROLE_BLOODY_NOSE_NAME) + .assignments() .single() - .assertTargetOid(ROLE_BLOODY_NOSE_OID) - .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) - .activation() - .assertNoValidTo(); + .assertTargetOid(ROLE_BLOODY_NOSE_OID) + .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) + .activation() + .assertNoValidTo(); } @Test public void test322GuybrushSetFuneral() throws Exception { - final String TEST_NAME = "test322GuybrushSetFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -521,20 +492,18 @@ public void test322GuybrushSetFuneral() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertTitle(ROLE_BLOODY_NOSE_NAME) - .assignments() + .assertTitle(ROLE_BLOODY_NOSE_NAME) + .assignments() .single() - .assertTargetOid(ROLE_BLOODY_NOSE_OID) - .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) - .activation() - .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); + .assertTargetOid(ROLE_BLOODY_NOSE_OID) + .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) + .activation() + .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); } @Test public void test324GuybrushSetFuneral22222() throws Exception { - final String TEST_NAME = "test324GuybrushSetFuneral22222"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -548,6 +517,7 @@ public void test324GuybrushSetFuneral22222() throws Exception { then(); assertSuccess(result); + // @formatter:off assertUserAfter(USER_GUYBRUSH_OID) .assertTitle(ROLE_BLOODY_NOSE_NAME) .assignments() @@ -556,6 +526,7 @@ public void test324GuybrushSetFuneral22222() throws Exception { .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) .activation() .assertValidTo(GUYBRUSH_FUNERAL_DATE_22222_CAL); + // @formatter:on } /** @@ -563,8 +534,6 @@ public void test324GuybrushSetFuneral22222() throws Exception { */ @Test public void test326GuybrushNoFuneral() throws Exception { - final String TEST_NAME = "test326GuybrushNoFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -578,6 +547,7 @@ public void test326GuybrushNoFuneral() throws Exception { then(); assertSuccess(result); + // @formatter:off assertUserAfter(USER_GUYBRUSH_OID) .assertTitle(ROLE_BLOODY_NOSE_NAME) .assignments() @@ -586,12 +556,11 @@ public void test326GuybrushNoFuneral() throws Exception { .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) .activation() .assertNoValidTo(); + // @formatter:on } @Test public void test329GuybrushNoBloodyNose() throws Exception { - final String TEST_NAME = "test329GuybrushNoBloodyNose"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -609,10 +578,8 @@ public void test329GuybrushNoBloodyNose() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertNoTitle() - .assignments() - .assertNone(); - + .assertNoTitle() + .assignments().assertNone(); } private void changeManagerRaw(String id, Task task, OperationResult result) throws CommonException { @@ -630,5 +597,4 @@ private void changeEmployeeIdRaw(String id, Task initTask, OperationResult initR .asObjectDelta(USER_ELAINE_OID), ModelExecuteOptions.createRaw(), initTask, initResult); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java index 6d7b95dad37..0274be4004e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java @@ -35,10 +35,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author Radovan Semancik - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestArchetypes extends AbstractArchetypesTest { @@ -125,11 +121,6 @@ protected File getSystemConfigurationFile() { */ @Test public void test020SanityJack() throws Exception { - final String TEST_NAME = "test020SanityJack"; - - Task task = getTestTask(); - OperationResult result = task.getResult(); - PrismObject user = assertUserBefore(USER_JACK_OID) .assertFullName(USER_JACK_FULL_NAME) .getObject(); @@ -139,8 +130,6 @@ public void test020SanityJack() throws Exception { @Test public void test050AddArchetypeTest() throws Exception { - final String TEST_NAME = "test050AddArchetypeTest"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -158,8 +147,6 @@ public void test050AddArchetypeTest() throws Exception { @Test public void test060AddArchetypesAndRoles() throws Exception { - final String TEST_NAME = "test060AddArchetypesAndRoles"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -197,8 +184,6 @@ public void test060AddArchetypesAndRoles() throws Exception { @Test public void test070AssignGuybrushUserAdministrator() throws Exception { - final String TEST_NAME = "test070AssignGuybrushUserAdministrator"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -216,8 +201,6 @@ public void test070AssignGuybrushUserAdministrator() throws Exception { @Test public void test100AssignJackArchetypeEmployee() throws Exception { - final String TEST_NAME = "test100AssignJackArchetypeEmployee"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -259,8 +242,6 @@ private String costCenterEmployee() { @Test public void test102SearchEmployeeArchetypeRef() throws Exception { - final String TEST_NAME = "test102SearchEmployeeArchetypeRef"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -296,8 +277,6 @@ public void test102SearchEmployeeArchetypeRef() throws Exception { @Test public void test104GetGuybryshCompiledGuiProfile() throws Exception { - final String TEST_NAME = "test104GetGuybryshCompiledGuiProfile"; - // GIVEN login(USER_GUYBRUSH_USERNAME); @@ -361,8 +340,6 @@ public void test104GetGuybryshCompiledGuiProfile() throws Exception { @Test public void test109UnassignJackArchetypeEmployee() throws Exception { - final String TEST_NAME = "test109UnassignJackArchetypeEmployee"; - loginAdministrator(); Task task = getTestTask(); @@ -395,8 +372,6 @@ public void test109UnassignJackArchetypeEmployee() throws Exception { @Test public void test110AssignJackRoleEmployeeBase() throws Exception { - final String TEST_NAME = "test110AssignJackRoleEmployeeBase"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -450,8 +425,6 @@ public void test110AssignJackRoleEmployeeBase() throws Exception { @Test public void test115UnassignJackRoleEmployeeBase() throws Exception { - final String TEST_NAME = "test115UnassignJackRoleEmployeeBase"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -493,8 +466,6 @@ public void test115UnassignJackRoleEmployeeBase() throws Exception { @Test public void test120AssignJackArchetypeTest() throws Exception { - final String TEST_NAME = "test120AssignJackArchetypeTest"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -528,8 +499,6 @@ public void test120AssignJackArchetypeTest() throws Exception { @Test public void test129UnassignJackArchetypeTest() throws Exception { - final String TEST_NAME = "test129UnassignJackArchetypeTest"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -559,8 +528,6 @@ public void test129UnassignJackArchetypeTest() throws Exception { */ @Test public void test130AssignJackArchetypeContractor() throws Exception { - final String TEST_NAME = "test130AssignJackArchetypeContractor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -591,8 +558,6 @@ public void test130AssignJackArchetypeContractor() throws Exception { */ @Test public void test132JackContractorRecompute() throws Exception { - final String TEST_NAME = "test132JackContractorRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -624,8 +589,6 @@ public void test132JackContractorRecompute() throws Exception { */ @Test public void test135UnassignJackArchetypeContractor() throws Exception { - final String TEST_NAME = "test135UnassignJackArchetypeContractor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -658,8 +621,6 @@ public void test135UnassignJackArchetypeContractor() throws Exception { */ @Test public void test137JackEmpnoAndRecompute() throws Exception { - final String TEST_NAME = "test137JackEmpnoAndRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -694,8 +655,6 @@ public void test137JackEmpnoAndRecompute() throws Exception { */ @Test public void test140AddMeathookContractor() throws Exception { - final String TEST_NAME = "test140AddMeathookContractor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -728,8 +687,6 @@ public void test140AddMeathookContractor() throws Exception { */ @Test public void test150AddWannabe() throws Exception { - final String TEST_NAME = "test150AddWannabe"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -763,8 +720,6 @@ public void test150AddWannabe() throws Exception { */ @Test public void test160AddSelfMadeMan() throws Exception { - final String TEST_NAME = "test160AddSelfMadeMan"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -796,8 +751,6 @@ public void test160AddSelfMadeMan() throws Exception { */ @Test public void test162AddFraudster() throws Exception { - final String TEST_NAME = "test162AddFraudster"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -825,8 +778,6 @@ public void test162AddFraudster() throws Exception { @Test public void test200AssignJackBarbossaArchetypeEmployee() throws Exception { - final String TEST_NAME = "test200AssignJackBarbossaArchetypeEmployee"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -850,8 +801,6 @@ public void test200AssignJackBarbossaArchetypeEmployee() throws Exception { @Test public void test202GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exception { - final String TEST_NAME = "test202GetGuybryshCompiledGuiProfileActiveEmployeesView"; - // GIVEN login(USER_GUYBRUSH_USERNAME); @@ -886,8 +835,6 @@ public void test202GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exc @Test public void test203DisableBarbossa() throws Exception { - final String TEST_NAME = "test203DisableBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -910,8 +857,6 @@ public void test203DisableBarbossa() throws Exception { @Test public void test205GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exception { - final String TEST_NAME = "test205GetGuybryshCompiledGuiProfileActiveEmployeesView"; - // GIVEN login(USER_GUYBRUSH_USERNAME); @@ -946,8 +891,6 @@ public void test205GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exc @Test public void test300jackAssignArchetypeRaw() throws Exception { - final String TEST_NAME = "test300jackAssignArchetypeRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java index 3c87a3e8a2f..efb8a608309 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java @@ -75,7 +75,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java index 9f3e449ff30..a57f3468828 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java @@ -72,24 +72,18 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); TestUtil.assertSuccess(testResultGrouper); } - private Task createTestTask(String TEST_NAME) { - return taskManager.createTaskInstance(TestAsyncUpdateUcf.class.getName() + "." + TEST_NAME); - } - /** * Shadow ADD delta for banderson. */ @Test public void test100AddAnderson() throws Exception { - final String TEST_NAME = "test100AddAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -127,8 +121,7 @@ public void test100AddAnderson() throws Exception { */ @Test public void test110AddAlumniAndStaff() throws Exception { - final String TEST_NAME = "test110AddAlumni"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -173,8 +166,7 @@ public void test110AddAlumniAndStaff() throws Exception { */ @Test public void test120AddWhite() throws Exception { - final String TEST_NAME = "test120AddWhite"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -212,8 +204,7 @@ public void test120AddWhite() throws Exception { */ @Test public void test200AddAlumniForAnderson() throws Exception { - final String TEST_NAME = "test200AddAlumniForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -251,8 +242,7 @@ public void test200AddAlumniForAnderson() throws Exception { */ @Test public void test210AddStaffForAnderson() throws Exception { - final String TEST_NAME = "test210AddStaffForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -290,8 +280,7 @@ public void test210AddStaffForAnderson() throws Exception { */ @Test public void test220AddAlumniForLewis() throws Exception { - final String TEST_NAME = "test220AddAlumniForLewis"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -329,8 +318,7 @@ public void test220AddAlumniForLewis() throws Exception { */ @Test public void test230MentionLewis() throws Exception { - final String TEST_NAME = "test230MentionLewis"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -368,8 +356,7 @@ public void test230MentionLewis() throws Exception { */ @Test public void test300DeleteAnderson() throws Exception { - final String TEST_NAME = "test300DeleteAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -399,8 +386,7 @@ public void test300DeleteAnderson() throws Exception { */ @Test public void test310DeleteStaff() throws Exception { - final String TEST_NAME = "test310DeleteStaff"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java index 48d0fd78edf..f3bea3ea64c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java @@ -86,8 +86,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); TestUtil.assertSuccess(testResultGrouper); @@ -98,8 +97,7 @@ public void test000Sanity() throws Exception { */ @Test public void test100AddAnderson() throws Exception { - final String TEST_NAME = "test100AddAnderson"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -135,8 +133,7 @@ public void test100AddAnderson() throws Exception { */ @Test public void test105AddLewis() throws Exception { - final String TEST_NAME = "test105AddLewis"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -175,8 +172,7 @@ public void test105AddLewis() throws Exception { */ @Test public void test110AddAlumni() throws Exception { - final String TEST_NAME = "test110AddAlumni"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -212,8 +208,7 @@ public void test110AddAlumni() throws Exception { */ @Test public void test120AddStaff() throws Exception { - final String TEST_NAME = "test120AddStaff"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -249,8 +244,7 @@ public void test120AddStaff() throws Exception { */ @Test public void test200AddGroupsForAnderson() throws Exception { - final String TEST_NAME = "test200AddGroupsForAnderson"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -286,8 +280,7 @@ public void test200AddGroupsForAnderson() throws Exception { */ @Test public void test210AddGroupsForLewis() throws Exception { - final String TEST_NAME = "test210AddGroupsForLewis"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java index d32f6ea192b..79096ca8c82 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java @@ -21,7 +21,6 @@ import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.UniformItemPath; -import com.evolveum.midpoint.prism.path.UniformItemPathImpl; import com.evolveum.midpoint.schema.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -1696,7 +1695,6 @@ public void testEmptyPath() { * UniformItemPath.EMPTY_PATH = * UniformItemPathImpl.EMPTY_PATH = */ - System.out.println("UniformItemPath.EMPTY_PATH = " + UniformItemPath.EMPTY_PATH); - System.out.println("UniformItemPathImpl.EMPTY_PATH = " + UniformItemPathImpl.EMPTY_PATH); + System.out.println("UniformItemPath.EMPTY_PATH = " + UniformItemPath.empty()); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java index a168e1316c3..7a98c07e36c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java @@ -6,53 +6,53 @@ */ package com.evolveum.midpoint.model.intest.gensync; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.util.Collection; -import javax.xml.datatype.XMLGregorianCalendar; +import org.apache.commons.lang.StringUtils; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; import com.evolveum.icf.dummy.resource.DummyGroup; import com.evolveum.midpoint.audit.api.AuditEventStage; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.Containerable; +import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.StringUtils; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.MiscUtil; - /** * Generic synchronization test. We create role and assign a resource to it. * Entitlement (group) should be created. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRoleEntitlement extends AbstractGenericSyncTest { @@ -60,8 +60,6 @@ public class TestRoleEntitlement extends AbstractGenericSyncTest { @Test public void test050GetRolePirate() throws Exception { - final String TEST_NAME = "test050GetRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -78,16 +76,14 @@ public void test050GetRolePirate() throws Exception { protected void assertRolePirate(PrismObject role) { assertObjectSanity(role); - assertEquals("Wrong "+role+" OID (prism)", ROLE_PIRATE_OID, role.getOid()); + assertEquals("Wrong " + role + " OID (prism)", ROLE_PIRATE_OID, role.getOid()); RoleType roleType = role.asObjectable(); - assertEquals("Wrong "+role+" OID (jaxb)", ROLE_PIRATE_OID, roleType.getOid()); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", "Pirate", roleType.getName()); + assertEquals("Wrong " + role + " OID (jaxb)", ROLE_PIRATE_OID, roleType.getOid()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", "Pirate", roleType.getName()); } @Test public void test100ModifyRoleAddEntitlement() throws Exception { - final String TEST_NAME = "test100ModifyRoleAddEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -107,14 +103,12 @@ public void test100ModifyRoleAddEntitlement() throws Exception { prepareNotifications(); dummyTransport.clearMessages(); notificationManager.setDisabled(false); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); // WHEN modelService.executeChanges(deltas, null, task, result); // THEN assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); // Check accountRef PrismObject rolePirate = modelService.getObject(RoleType.class, ROLE_PIRATE_OID, null, task, result); @@ -152,8 +146,6 @@ public void test100ModifyRoleAddEntitlement() throws Exception { @Test public void test101GetGroup() throws Exception { - final String TEST_NAME = "test101GetGroup"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -165,7 +157,7 @@ public void test101GetGroup() throws Exception { dummyGroup.replaceAttributeValue(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION, "Bloodthirsty Pirates"); // WHEN - PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, null , task, result); + PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, null, task, result); // THEN display("Group shadow (model)", shadow); @@ -181,8 +173,6 @@ public void test101GetGroup() throws Exception { @Test public void test102GetGroupNoFetch() throws Exception { - final String TEST_NAME = "test102GetGroupNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -191,7 +181,7 @@ public void test102GetGroupNoFetch() throws Exception { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); // WHEN - PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options , task, result); + PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options, task, result); display("Account", shadow); display("Account def", shadow.getDefinition()); @@ -206,8 +196,6 @@ public void test102GetGroupNoFetch() throws Exception { @Test public void test103GetGroupRaw() throws Exception { - final String TEST_NAME = "test103GetGroupRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -215,7 +203,7 @@ public void test103GetGroupRaw() throws Exception { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); // WHEN - PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options , task, result); + PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options, task, result); display("Account", shadow); display("Account def", shadow.getDefinition()); @@ -230,8 +218,6 @@ public void test103GetGroupRaw() throws Exception { @Test public void test108ModifyRoleAddEntitlementAgain() throws Exception { - final String TEST_NAME = "test108ModifyRoleAddEntitlementAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -245,7 +231,7 @@ public void test108ModifyRoleAddEntitlementAgain() throws Exception { linkRefVal.setObject(group); ReferenceDelta groupDelta = prismContext.deltaFactory().reference().createModificationAdd(RoleType.F_LINK_REF, getRoleDefinition(), linkRefVal); roleDelta.addModification(groupDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(roleDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(roleDelta); dummyAuditService.clear(); @@ -276,8 +262,6 @@ public void test108ModifyRoleAddEntitlementAgain() throws Exception { @Test public void test110GetRoleResolveEntitlement() throws Exception { - final String TEST_NAME = "test110GetRoleResolveEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -304,8 +288,6 @@ public void test110GetRoleResolveEntitlement() throws Exception { @Test public void test111GetRoleResolveEntitlement() throws Exception { - final String TEST_NAME = "test111GetRoleResolveEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -336,8 +318,6 @@ public void test111GetRoleResolveEntitlement() throws Exception { @Test public void test112GetRoleResolveEntitlementNoFetch() throws Exception { - final String TEST_NAME = "test112GetRoleResolveEntitlementNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -345,8 +325,8 @@ public void test112GetRoleResolveEntitlementNoFetch() throws Exception { Collection> options = schemaHelper.getOperationOptionsBuilder() .item(UserType.F_LINK_REF) - .resolve() - .noFetch() + .resolve() + .noFetch() .build(); // WHEN @@ -364,11 +344,8 @@ public void test112GetRoleResolveEntitlementNoFetch() throws Exception { TestUtil.assertSuccess("getObject result", result); } - @Test public void test119ModifyRoleDeleteEntitlement() throws Exception { - final String TEST_NAME = "test119ModifyRoleDeleteEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -381,7 +358,7 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { .createEmptyModifyDelta(RoleType.class, ROLE_PIRATE_OID); ReferenceDelta linkDelta = prismContext.deltaFactory().reference().createModificationDelete(RoleType.F_LINK_REF, getUserDefinition(), group); roleDelta.addModification(linkDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(roleDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(roleDelta); prepareNotifications(); @@ -400,7 +377,7 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { // Check is shadow is gone try { - PrismObject shadow = repositoryService.getObject(ShadowType.class, groupOid, null, result); + repositoryService.getObject(ShadowType.class, groupOid, null, result); AssertJUnit.fail("Shadow " + groupOid + " still exists"); } catch (ObjectNotFoundException e) { // This is OK @@ -409,7 +386,7 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { // Check if dummy resource account is gone assertNoDummyGroup(GROUP_PIRATE_DUMMY_NAME); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -424,8 +401,6 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { @Test public void test120AddEntitlement() throws Exception { - final String TEST_NAME = "test120AddEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -434,8 +409,6 @@ public void test120AddEntitlement() throws Exception { PrismObject group = PrismTestUtil.parseObject(GROUP_PIRATE_DUMMY_FILE); ObjectDelta groupDelta = DeltaFactory.Object.createAddDelta(group); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); Collection> executedChanges = executeChanges(groupDelta, null, task, result); @@ -443,7 +416,6 @@ public void test120AddEntitlement() throws Exception { // THEN then(); assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); groupOid = ObjectDeltaOperation.findAddDeltaOid(executedChanges, group); assertNotNull("No account OID in resulting delta", groupOid); @@ -478,8 +450,6 @@ public void test120AddEntitlement() throws Exception { @Test public void test121ModifyRoleLinkEntitlement() throws Exception { - final String TEST_NAME = "test121ModifyRoleLinkEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -527,11 +497,8 @@ public void test121ModifyRoleLinkEntitlement() throws Exception { dummyAuditService.assertExecutionSuccess(); } - @Test public void test128ModifyRoleUnlinkEntitlement() throws Exception { - final String TEST_NAME = "test128ModifyRoleUnlinkEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -582,8 +549,6 @@ public void test128ModifyRoleUnlinkEntitlement() throws Exception { @Test public void test129DeleteEntitlement() throws Exception { - final String TEST_NAME = "test129DeleteEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -623,8 +588,6 @@ public void test129DeleteEntitlement() throws Exception { @Test public void test131ModifyRoleAssignEntitlement() throws Exception { - final String TEST_NAME = "test131ModifyRoleAssignEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -684,8 +647,6 @@ public void test131ModifyRoleAssignEntitlement() throws Exception { */ @Test public void test132ModifyEntitlement() throws Exception { - final String TEST_NAME = "test132ModifyEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -710,7 +671,7 @@ public void test132ModifyEntitlement() throws Exception { display("Role after change execution", role); assertEquals("Wrong role description", ROLE_PIRATE_DESCRIPTION, role.asObjectable().getDescription()); // reflected by inbound - PrismAsserts.assertPropertyValue(role,ROLE_EXTENSION_COST_CENTER_PATH, "MELEE123"); + PrismAsserts.assertPropertyValue(role, ROLE_EXTENSION_COST_CENTER_PATH, "MELEE123"); assertLinks(role, 1); groupOid = getSingleLinkOid(role); @@ -748,8 +709,6 @@ public void test132ModifyEntitlement() throws Exception { @Test public void test139ModifyRoleUnassignEntitlement() throws Exception { - final String TEST_NAME = "test139ModifyRoleUnassignEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -797,8 +756,6 @@ public void test139ModifyRoleUnassignEntitlement() throws Exception { */ @Test public void test151ModifyRoleAssignEntitlementRelativeEnforcement() throws Exception { - final String TEST_NAME = "test151ModifyRoleAssignEntitlementRelativeEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -808,15 +765,12 @@ public void test151ModifyRoleAssignEntitlementRelativeEnforcement() throws Excep ShadowKindType.ENTITLEMENT, "group", true); Collection> deltas = MiscSchemaUtil.createCollection(assignmentDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -857,11 +811,8 @@ public void test151ModifyRoleAssignEntitlementRelativeEnforcement() throws Excep */ @Test public void test158ModifyRoleUnassignEntitlementRelativeEnforcement() throws Exception { - final String TEST_NAME = "test158ModifyRoleUnassignEntitlementRelativeEnforcement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestRoleEntitlement.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); prepareTest(AssignmentPolicyEnforcementType.RELATIVE); @@ -907,8 +858,6 @@ public void test158ModifyRoleUnassignEntitlementRelativeEnforcement() throws Exc */ @Test public void test160ModifyRolePropertyAndAssignEntitlement() throws Exception { - final String TEST_NAME = "test160ModifyRolePropertyAndAssignEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -919,15 +868,12 @@ public void test160ModifyRolePropertyAndAssignEntitlement() throws Exception { roleDelta.addModificationReplaceProperty(RoleType.F_DESCRIPTION, "Band of Bloodthirsty Bashers"); Collection> deltas = MiscSchemaUtil.createCollection(roleDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -968,8 +914,6 @@ public void test160ModifyRolePropertyAndAssignEntitlement() throws Exception { */ @Test public void test161ModifyRole() throws Exception { - final String TEST_NAME = "test161ModifyRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -979,15 +923,12 @@ public void test161ModifyRole() throws Exception { ROLE_PIRATE_OID, RoleType.F_DESCRIPTION, ROLE_PIRATE_DESCRIPTION); Collection> deltas = MiscSchemaUtil.createCollection(roleDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -997,13 +938,11 @@ public void test161ModifyRole() throws Exception { // Check shadow PrismObject shadow = repositoryService.getObject(ShadowType.class, groupOid, null, result); assertDummyGroupShadowRepo(shadow, groupOid, GROUP_PIRATE_DUMMY_NAME); -// assertEnableTimestampShadow(shadow, startTime, endTime); // Check group PrismObject shadowModel = modelService.getObject(ShadowType.class, groupOid, null, task, result); display("Entitlement shadow after", shadowModel); assertDummyGroupShadowModel(shadowModel, groupOid, GROUP_PIRATE_DUMMY_NAME); -// assertEnableTimestampShadow(shadowModel, startTime, endTime); // Check group in dummy resource assertDummyGroup(GROUP_PIRATE_DUMMY_NAME, ROLE_PIRATE_DESCRIPTION); @@ -1024,8 +963,6 @@ public void test161ModifyRole() throws Exception { @Test public void test180RenameRole() throws Exception { - final String TEST_NAME = "test180RenameRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1035,15 +972,12 @@ public void test180RenameRole() throws Exception { ROLE_PIRATE_OID, RoleType.F_NAME, PrismTestUtil.createPolyString("Privateers")); Collection> deltas = MiscSchemaUtil.createCollection(roleDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -1069,7 +1003,7 @@ public void test180RenameRole() throws Exception { // Just to be on a safe side, this is uppercase assertNoDummyGroup(ROLE_PIRATE_NAME); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -1086,8 +1020,6 @@ public void test180RenameRole() throws Exception { */ @Test public void test199DeleteRole() throws Exception { - final String TEST_NAME = "test199DeleteRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1105,7 +1037,7 @@ public void test199DeleteRole() throws Exception { TestUtil.assertSuccess("executeChanges result", result); try { - PrismObject role = getRole(ROLE_PIRATE_OID); + getRole(ROLE_PIRATE_OID); AssertJUnit.fail("Privateers are still alive!"); } catch (ObjectNotFoundException ex) { // This is OK @@ -1121,7 +1053,7 @@ public void test199DeleteRole() throws Exception { assertNoDummyGroup(GROUP_PIRATE_DUMMY_NAME); assertNoDummyGroup(ROLE_PIRATE_NAME); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -1140,8 +1072,6 @@ public void test199DeleteRole() throws Exception { */ @Test public void test200AddRoleSwashbuckler() throws Exception { - final String TEST_NAME = "test200AddRoleSwashbuckler"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1150,8 +1080,6 @@ public void test200AddRoleSwashbuckler() throws Exception { PrismObject role = parseObject(ROLE_SWASHBUCKLER_FILE); ObjectDelta roleDelta = DeltaFactory.Object.createAddDelta(role); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); executeChanges(roleDelta, null, task, result); @@ -1159,7 +1087,6 @@ public void test200AddRoleSwashbuckler() throws Exception { // THEN then(); assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertNotNull("No account OID in resulting delta", groupOid); // Check linkRef (should be none) @@ -1190,11 +1117,11 @@ public void test200AddRoleSwashbuckler() throws Exception { dummyAuditService.assertRecords(3); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); - dummyAuditService.assertExecutionDeltas(0,3); + dummyAuditService.assertExecutionDeltas(0, 3); dummyAuditService.assertHasDelta(0, ChangeType.ADD, RoleType.class); dummyAuditService.assertHasDelta(0, ChangeType.ADD, ShadowType.class); dummyAuditService.assertHasDelta(0, ChangeType.MODIFY, RoleType.class); // link - dummyAuditService.assertExecutionDeltas(1,1); + dummyAuditService.assertExecutionDeltas(1, 1); dummyAuditService.assertHasDelta(1, ChangeType.MODIFY, RoleType.class); // inbound dummyAuditService.assertTarget(ROLE_SWASHBUCKLER_OID); dummyAuditService.assertExecutionSuccess(); @@ -1205,15 +1132,13 @@ public void test200AddRoleSwashbuckler() throws Exception { */ @Test public void test210ModifyRoleSwashbucklerRiskLevel() throws Exception { - final String TEST_NAME = "test210ModifyRoleSwashbucklerRiskLevel"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); prepareTest(AssignmentPolicyEnforcementType.RELATIVE); assertRoleBefore(ROLE_SWASHBUCKLER_OID) - .extension() + .extension() .assertItems(PIRACY_COST_CENTER); // WHEN @@ -1225,12 +1150,12 @@ public void test210ModifyRoleSwashbucklerRiskLevel() throws Exception { assertSuccess(result); assertRoleAfter(ROLE_SWASHBUCKLER_OID) - .assertRiskLevel("99") - .extension() + .assertRiskLevel("99") + .extension() .assertItems(PIRACY_COST_CENTER, PIRACY_RISK_VECTOR) .containerSingle(PIRACY_RISK_VECTOR) - .assertPropertyEquals(PIRACY_RISK_VECTOR_RISK, "X") - .assertPropertyEquals(PIRACY_RISK_VECTOR_VALUE, 99); + .assertPropertyEquals(PIRACY_RISK_VECTOR_RISK, "X") + .assertPropertyEquals(PIRACY_RISK_VECTOR_VALUE, 99); } private void prepareTest(AssignmentPolicyEnforcementType enforcement) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java index ea2b2e2a02c..d399fee1965 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java @@ -402,9 +402,8 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { @Test public void test020ImportTask() throws Exception { - final String TEST_NAME = "test020ImportTask"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_TASK_FILE_NAME, false)); @@ -446,9 +445,8 @@ public void test020ImportTask() throws Exception { @Test public void test030ImportResource() throws Exception { - final String TEST_NAME = "test030ImportResource"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_FILE_NAME, true)); @@ -496,9 +494,8 @@ public void test030ImportResource() throws Exception { @Test public void test031ReimportResource() throws Exception { - final String TEST_NAME = "test031ReimportResource"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_CHANGED_FILE_NAME, false)); @@ -550,9 +547,8 @@ public void test031ReimportResource() throws Exception { @Test public void test032ImportResourceOidAndFilter() throws Exception { - final String TEST_NAME = "test032ImportResourceOidAndFilter"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DERBY_FILE_NAME, false)); @@ -603,9 +599,8 @@ public void test032ImportResourceOidAndFilter() throws Exception { */ @Test public void test033ImportResourceDummyRuntime() throws Exception { - final String TEST_NAME = "test033ImportResourceDummyRuntime"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_RUNTIME_FILE_NAME, false)); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java index ceceffed8b4..f14763ad47f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java @@ -118,7 +118,6 @@ protected boolean isDirect() { */ @Test public void test220ModifyUserWillDisable() throws Exception { - final String TEST_NAME = "test220ModifyUserWillDisable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -195,7 +194,6 @@ public void test220ModifyUserWillDisable() throws Exception { */ @Test public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { - final String TEST_NAME = "test230ModifyAccountWillChangePasswordAndEnable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -283,7 +281,6 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { */ @Test public void test240CloseDisableCaseAndReadAccountWill() throws Exception { - final String TEST_NAME = "test240CloseDisableCaseAndReadAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -373,7 +370,6 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { */ @Test public void test250RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test250RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -460,7 +456,6 @@ public void test250RecomputeWillAfter5min() throws Exception { @Test public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test252UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -518,7 +513,6 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test260ClosePasswordChangeCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -622,7 +616,6 @@ public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { */ @Test public void test270RecomputeWillAfter7min() throws Exception { - final String TEST_NAME = "test130RefreshAccountWillAfter7min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -720,7 +713,6 @@ public void test270RecomputeWillAfter7min() throws Exception { @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -778,7 +770,6 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test274RecomputeWillAfter22min() throws Exception { - final String TEST_NAME = "test292RecomputeWillAfter22min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -863,7 +854,6 @@ public void test274RecomputeWillAfter22min() throws Exception { */ @Test public void test280RecomputeWillAfter27min() throws Exception { - final String TEST_NAME = "test280RecomputeWillAfter27min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -936,7 +926,6 @@ public void test280RecomputeWillAfter27min() throws Exception { */ @Test public void test290RecomputeWillAfter32min() throws Exception { - final String TEST_NAME = "test290RecomputeWillAfter32min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -998,7 +987,6 @@ public void test290RecomputeWillAfter32min() throws Exception { @Test public void test300UnassignAccountWill() throws Exception { - final String TEST_NAME = "test300UnassignAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1074,7 +1062,6 @@ public void test300UnassignAccountWill() throws Exception { */ @Test public void test302RecomputeWill() throws Exception { - final String TEST_NAME = "test302RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1144,7 +1131,6 @@ public void test302RecomputeWill() throws Exception { */ @Test public void test310CloseCaseAndReconcileWill() throws Exception { - final String TEST_NAME = "test310CloseCaseAndReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1209,7 +1195,6 @@ protected void assertUnassignedShadow(ShadowAsserter shadowModelAsserter, boo */ @Test public void test320RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test320RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1262,7 +1247,6 @@ public void test320RecomputeWillAfter5min() throws Exception { */ @Test public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { - final String TEST_NAME = "test330UpdateBackingStoreAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1325,7 +1309,6 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { */ @Test public void test340RecomputeWillAfter25min() throws Exception { - final String TEST_NAME = "test340RecomputeWillAfter25min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1366,7 +1349,6 @@ public void test340RecomputeWillAfter25min() throws Exception { */ @Test public void test342RecomputeWillAfter35min() throws Exception { - final String TEST_NAME = "test342RecomputeWillAfter35min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1404,7 +1386,6 @@ public void test342RecomputeWillAfter35min() throws Exception { */ @Test public void test344RecomputeWillAfter165min() throws Exception { - final String TEST_NAME = "test344RecomputeWillAfter165min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1467,7 +1448,6 @@ public void test500AssignWillRoleOne() throws Exception { */ @Test public void test510UnassignWillRoleOne() throws Exception { - final String TEST_NAME = "test510UnassignWillRoleOne"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1537,7 +1517,6 @@ public void test510UnassignWillRoleOne() throws Exception { */ @Test public void test512ReconcileWill() throws Exception { - final String TEST_NAME = "test512ReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1607,7 +1586,6 @@ public void test512ReconcileWill() throws Exception { */ @Test public void test515CloseCasesAndReconcileWill() throws Exception { - final String TEST_NAME = "test515CloseCasesAndReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1707,7 +1685,6 @@ protected void assertWillUnassignPendingOperationCompleted(ShadowAsserter */ @Test public void test516RecomputeWillAfter20min() throws Exception { - final String TEST_NAME = "test516RecomputeWillAfter20min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1741,7 +1718,6 @@ public void test516RecomputeWillAfter20min() throws Exception { */ @Test public void test517RecomputeWillAfter50min() throws Exception { - final String TEST_NAME = "test517RecomputeWillAfter50min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1777,7 +1753,6 @@ public void test517RecomputeWillAfter50min() throws Exception { */ @Test public void test518RecomputeWillAfter180min() throws Exception { - final String TEST_NAME = "test518RecomputeWillAfter180min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1837,7 +1812,6 @@ public void test520AssignWillRoleOne() throws Exception { */ @Test public void test522AssignWillRoleTwoValidFrom() throws Exception { - final String TEST_NAME = "test522AssignWillRoleTwoValidFrom"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1870,7 +1844,6 @@ public void test522AssignWillRoleTwoValidFrom() throws Exception { */ @Test public void test524TwoHoursForRoleTwo() throws Exception { - final String TEST_NAME = "test524TwoHoursForRoleTwo"; // GIVEN clockForward("PT2H5M"); @@ -1938,7 +1911,6 @@ public void test524TwoHoursForRoleTwo() throws Exception { */ @Test public void test525CloseCasesAndReconcileWill() throws Exception { - final String TEST_NAME = "test525CloseCasesAndReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1975,7 +1947,6 @@ public void test525CloseCasesAndReconcileWill() throws Exception { */ @Test public void test526UnassignWillBothRoles() throws Exception { - final String TEST_NAME = "test526UnassignWillBothRoles"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2034,7 +2005,6 @@ protected void assertTest526Deltas(PrismObject shadowRepo, Operation @Test public void test528CloseCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test528CloseCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2114,7 +2084,6 @@ public void test529CleanUp() throws Exception { */ @Test public void test800ImportShadowRefreshTask() throws Exception { - final String TEST_NAME = "test800ImportShadowRefreshTask"; // GIVEN // WHEN @@ -2129,8 +2098,6 @@ public void test800ImportShadowRefreshTask() throws Exception { @Test public void test810AssignAccountWill() throws Exception { - final String TEST_NAME = "test810AssignAccountWill"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2152,7 +2119,6 @@ public void test810AssignAccountWill() throws Exception { @Test public void test820AssignAccountJack() throws Exception { - final String TEST_NAME = "test820AssignAccountJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2189,7 +2155,6 @@ public void test820AssignAccountJack() throws Exception { @Test public void test830CloseCaseWillAndWaitForRefresh() throws Exception { - final String TEST_NAME = "test830CloseCaseWillAndWaitForRefresh"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2216,7 +2181,6 @@ public void test830CloseCaseWillAndWaitForRefresh() throws Exception { @Test public void test840AddToBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test840AddToBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java index e84c5cf1ecd..e7e000251e5 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java @@ -360,7 +360,7 @@ public void test016ParsedSchema() throws Exception { // THEN // The returned type should have the schema pre-parsed - assertNotNull(RefinedResourceSchemaImpl.hasParsedSchema(resourceType)); + assertTrue(RefinedResourceSchemaImpl.hasParsedSchema(resourceType)); // Also test if the utility method returns the same thing ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); @@ -370,7 +370,7 @@ public void test016ParsedSchema() throws Exception { // Check whether it is reusing the existing schema and not parsing it all over again // Not equals() but == ... we want to really know if exactly the same // object instance is returned - assertTrue("Broken caching", resourceSchema == RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext)); + assertSame("Broken caching", resourceSchema, RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext)); ObjectClassComplexTypeDefinition accountDef = resourceSchema.findObjectClassDefinition(RESOURCE_ACCOUNT_OBJECTCLASS); assertNotNull("Account definition is missing", accountDef); @@ -703,7 +703,6 @@ public void test103RunPropagation() throws Exception { @Test public void test104RecomputeWill() throws Exception { - final String TEST_NAME = "test104RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2168,7 +2167,7 @@ protected void assertAttribute( assertAttribute(shadow.asObjectable(), attrName, expectedValues); } - protected void assertNoAttribute(PrismObject shadow, QName attrName) { + protected void assertNoAttribute(PrismObject shadow, QName attrName) { assertNoAttribute(shadow.asObjectable(), attrName); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java index 0565135974f..d1c9ef044f2 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java @@ -36,8 +36,6 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManual extends AbstractDirectManualResourceTest { - protected static final String ATTR_DISABLED = "disabled"; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java index e18c11ba6af..b4e4921a978 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java @@ -122,7 +122,6 @@ protected void assertShadowPassword(PrismObject shadow) { @Test @Override public void test400PhantomAccount() throws Exception { - final String TEST_NAME = "test400PhantomAccount"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java index 9dded5516b8..1aa62c982cf 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java @@ -63,8 +63,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100ImportFromResource() throws Exception { - final String TEST_NAME = "test100ImportFromResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -111,8 +109,6 @@ public void test100ImportFromResource() throws Exception { */ @Test public void test110ModifyAccountTitleCraticAndReconcile() throws Exception { - final String TEST_NAME = "test110ModifyAccountTitleCraticAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -139,8 +135,6 @@ public void test110ModifyAccountTitleCraticAndReconcile() throws Exception { */ @Test public void test112ModifyAccountTitleDidacticGraphicAndReconcile() throws Exception { - final String TEST_NAME = "test112ModifyAccountTitleDidacticGraphicAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -169,8 +163,6 @@ public void test112ModifyAccountTitleDidacticGraphicAndReconcile() throws Except @Test public void test200ImportFromResourceAssociations() throws Exception { - final String TEST_NAME = "test200ImportFromResourceAssociations"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.RELATIVE, false); // GIVEN @@ -219,8 +211,6 @@ public void test200ImportFromResourceAssociations() throws Exception { @Test public void test300ModifyAccountDirectAssign() throws Exception { - final String TEST_NAME = "test300ModifyAccountDirectAssign"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -246,8 +236,6 @@ public void test300ModifyAccountDirectAssign() throws Exception { @Test public void test301removeUserFromAutoGroup() throws Exception { - final String TEST_NAME = "test301removeUserFromAutoGroup"; - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // GIVEN @@ -292,8 +280,6 @@ public void test301removeUserFromAutoGroup() throws Exception { @Test public void test402assignAutoGroupDirectly() throws Exception { - final String TEST_NAME = "test402assignAutoGroupDirectly"; - DummyGroup craticGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_CRATIC_NAME); craticGroup.removeMember(USER_HERMAN_USERNAME); @@ -328,8 +314,6 @@ public void test402assignAutoGroupDirectly() throws Exception { @Test public void test403removeAllAssignments() throws Exception { - final String TEST_NAME = "test403removeAllAssignments"; - DummyGroup testersGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_TESTERS_NAME); testersGroup.removeMember(USER_HERMAN_USERNAME); @@ -356,8 +340,6 @@ public void test403removeAllAssignments() throws Exception { @Test public void test404importAssociationAutotesters() throws Exception { - final String TEST_NAME = "test404importAssociationAutotesters"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.FULL, true); DummyGroup craticGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_CRATIC_NAME); @@ -393,8 +375,6 @@ public void test404importAssociationAutotesters() throws Exception { @Test public void test405assignRoleAutocraticDirectly() throws Exception { - final String TEST_NAME = "test405assignRoleAutocraticDirectly"; - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // GIVEN Task task = getTestTask(); @@ -420,8 +400,6 @@ public void test405assignRoleAutocraticDirectly() throws Exception { @Test public void test406unassignRoleAutocraticDirectly() throws Exception { - final String TEST_NAME = "test406unassignRoleAutocraticAutotestersDirectly"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.FULL, true); // GIVEN @@ -448,8 +426,6 @@ public void test406unassignRoleAutocraticDirectly() throws Exception { @Test public void test407addHermanToTestersReconcile() throws Exception { - final String TEST_NAME = "test407addHermanToTestersReconcile"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.FULL, true); DummyGroup craticGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_CRATIC_NAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java index f991e41a4ef..fb0ee822279 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java @@ -6,6 +6,20 @@ */ package com.evolveum.midpoint.model.intest.mapping; +import static java.util.Collections.singleton; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummySyncStyle; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; @@ -26,29 +40,13 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.io.File; -import java.io.FileNotFoundException; -import java.nio.charset.StandardCharsets; - -import javax.xml.namespace.QName; - -import static java.util.Collections.singleton; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; - /** * Tests inbound mappings. Uses live sync to do that. * These tests are much simpler and more focused than those in AbstractSynchronizationStoryTest. * * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMappingInbound extends AbstractMappingTest { @@ -81,7 +79,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti controller.extendSchemaPirate(); controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_LOCKER_NAME, String.class, false, false) - .setSensitive(true); + .setSensitive(true); controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_PROOF_NAME, String.class, false, false); controller.setSyncStyle(DummySyncStyle.SMART); @@ -91,8 +89,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010SanitySchema() throws Exception { - final String TEST_NAME = "test010SanitySchema"; - // GIVEN Task task = getTestTask(); @@ -118,26 +114,15 @@ public void test010SanitySchema() throws Exception { @Test public void test100ImportLiveSyncTaskDummyTeaGreen() throws Exception { - final String TEST_NAME = "test100ImportLiveSyncTaskDummyTeaGreen"; - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); importSyncTask(); - // THEN then(); - waitForSyncTaskStart(); } @Test public void test110AddDummyTeaGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test110AddDummyTeaGreenAccountMancomb"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -171,19 +156,19 @@ public void test110AddDummyTeaGreenAccountMancomb() throws Exception { UserAsserter mancombUserAsserter = assertUserAfterByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); mancombLocker = mancombUserAsserter - .links() + .links() .single() - .assertOid(accountMancomb.getOid()) - .end() + .assertOid(accountMancomb.getOid()) .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .extension() + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .extension() .property(PIRACY_LOCKER) - .singleValue() - .protectedString() - .assertIsEncrypted() - .assertCompareCleartext(LOCKER_BIG_SECRET) - .getProtectedString(); + .singleValue() + .protectedString() + .assertIsEncrypted() + .assertCompareCleartext(LOCKER_BIG_SECRET) + .getProtectedString(); assertJpegPhoto(UserType.class, mancombUserAsserter.getOid(), "water".getBytes(StandardCharsets.UTF_8), result); // assertUsers(6); @@ -197,8 +182,6 @@ public void test110AddDummyTeaGreenAccountMancomb() throws Exception { */ @Test public void test120ModifyMancombPhotoSource() throws Exception { - final String TEST_NAME = "test120ModifyMancombPhotoSource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -232,8 +215,6 @@ public void test120ModifyMancombPhotoSource() throws Exception { */ @Test public void test130ModifyMancombPhotoSourceAndReconcile() throws Exception { - final String TEST_NAME = "test130ModifyMancombPhotoSourceAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -271,8 +252,6 @@ public void test130ModifyMancombPhotoSourceAndReconcile() throws Exception { */ @Test public void test140ModifyMancombPhotoInRepo() throws Exception { - final String TEST_NAME = "test140ModifyMancombPhotoInRepo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -307,8 +286,6 @@ public void test140ModifyMancombPhotoInRepo() throws Exception { */ @Test public void test150UserReconcile() throws Exception { - final String TEST_NAME = "test150UserReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -336,23 +313,23 @@ public void test150UserReconcile() throws Exception { assertShadowOperationalData(accountMancomb, SynchronizationSituationType.LINKED, null); assertUserAfterByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME) - .links() + .links() .single() - .assertOid(accountMancomb.getOid()) - .end() + .assertOid(accountMancomb.getOid()) + .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .extension() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .extension() .property(PIRACY_LOCKER) - .singleValue() - .protectedString() - .assertIsEncrypted() - .assertCompareCleartext(LOCKER_BIG_SECRET) - // Make sure that this is exactly the same content of protected string - // including all the randomized things (IV). If it is the same, - // there is a good chance we haven't had any phantom changes - // MID-5197 - .assertEquals(mancombLocker); + .singleValue() + .protectedString() + .assertIsEncrypted() + .assertCompareCleartext(LOCKER_BIG_SECRET) + // Make sure that this is exactly the same content of protected string + // including all the randomized things (IV). If it is the same, + // there is a good chance we haven't had any phantom changes + // MID-5197 + .assertEquals(mancombLocker); // assertUsers(6); @@ -365,13 +342,6 @@ public void test150UserReconcile() throws Exception { @Test public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test300DeleteDummyTeaGreenAccountMancomb"; - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); getDummyResource(RESOURCE_DUMMY_TEA_GREEN_NAME).deleteAccountByName(ACCOUNT_MANCOMB_DUMMY_USERNAME); @@ -387,12 +357,12 @@ public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_TEA_GREEN_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertUserAfterByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME) - .assertFullName("Mancomb Seepgood") - .links() + .assertFullName("Mancomb Seepgood") + .links() .single() - .resolveTarget() - .assertTombstone() - .assertSynchronizationSituation(SynchronizationSituationType.DELETED); + .resolveTarget() + .assertTombstone() + .assertSynchronizationSituation(SynchronizationSituationType.DELETED); // assertUsers(7 + getNumberOfExtraDummyUsers()); @@ -403,8 +373,6 @@ public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { // Remove livesync task so it won't get into the way for next tests @Test public void test399DeleteDummyTeaGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test399DeleteDummyTeaGreenAccountMancomb"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -421,8 +389,6 @@ public void test399DeleteDummyTeaGreenAccountMancomb() throws Exception { @Test public void test400AddUserLeeloo() throws Exception { - final String TEST_NAME = "test400AddUserLeeloo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -449,13 +415,13 @@ public void test400AddUserLeeloo() throws Exception { then(); userLeelooOid = assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .getOid(); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .getOid(); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -474,8 +440,6 @@ public void test400AddUserLeeloo() throws Exception { */ @Test public void test402UserLeelooRecompute() throws Exception { - final String TEST_NAME = "test402UserLeelooRecompute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -490,12 +454,12 @@ public void test402UserLeelooRecompute() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(0); @@ -507,8 +471,6 @@ public void test402UserLeelooRecompute() throws Exception { */ @Test public void test404UserLeelooReconcile() throws Exception { - final String TEST_NAME = "test404UserLeelooReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -523,12 +485,12 @@ public void test404UserLeelooReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -544,8 +506,6 @@ public void test404UserLeelooReconcile() throws Exception { */ @Test public void test410UserLeeloominaiReconcile() throws Exception { - final String TEST_NAME = "test410UserLeeloominaiReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -564,12 +524,12 @@ public void test410UserLeeloominaiReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -586,8 +546,6 @@ public void test410UserLeeloominaiReconcile() throws Exception { */ @Test public void test412UserLeeloominaiRecompute() throws Exception { - final String TEST_NAME = "test412UserLeeloominaiRecompute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -602,12 +560,12 @@ public void test412UserLeeloominaiRecompute() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(0); @@ -619,8 +577,6 @@ public void test412UserLeeloominaiRecompute() throws Exception { */ @Test public void test414UserLeeloominaiReconcile() throws Exception { - final String TEST_NAME = "test414UserLeeloominaiReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -635,12 +591,12 @@ public void test414UserLeeloominaiReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -656,8 +612,6 @@ public void test414UserLeeloominaiReconcile() throws Exception { */ @Test public void test420UserLeelooStrangeReconcile() throws Exception { - final String TEST_NAME = "test420UserLeelooStrangeReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -676,13 +630,13 @@ public void test420UserLeelooStrangeReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -699,8 +653,6 @@ public void test420UserLeelooStrangeReconcile() throws Exception { */ @Test public void test424UserLeelooStrangeReconcile() throws Exception { - final String TEST_NAME = "test424UserLeelooStrangeReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -715,13 +667,13 @@ public void test424UserLeelooStrangeReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java index 482e0c5684a..75b872f0fc7 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java @@ -6,8 +6,6 @@ */ package com.evolveum.midpoint.model.intest.misc; -import static org.testng.AssertJUnit.assertEquals; - import java.io.File; import org.springframework.test.annotation.DirtiesContext; @@ -58,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test050SanityLost1() throws Exception { - final String TEST_NAME = "test050SanityLost1"; - // WHEN when(); PrismObject shadowLost1Repo = getShadowRepo(SHADOW_ACCOUNT_DUMMY_LOST1_OID); @@ -77,8 +73,6 @@ public void test050SanityLost1() throws Exception { */ @Test public void test100RefreshTaskDefault() throws Exception { - final String TEST_NAME = "test100RefreshTaskDefault"; - addObject(TASK_SHADOW_REFRESH_FILE); // WHEN @@ -101,8 +95,6 @@ public void test100RefreshTaskDefault() throws Exception { */ @Test public void test110RefreshTaskExplicitDummy() throws Exception { - final String TEST_NAME = "test110RefreshTaskExplicitDummy"; - addObject(TASK_SHADOW_REFRESH_EXPLICIT_DUMMY_FILE); // WHEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java index 0afde18db71..b6c3e330dff 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java @@ -6,22 +6,15 @@ */ package com.evolveum.midpoint.model.intest.misc; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.List; - import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; -import com.evolveum.midpoint.prism.PrismContext; - -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.util.exception.SystemException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -30,8 +23,10 @@ import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.Objectable; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.RepositoryDiag; @@ -43,17 +38,10 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RelationDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMisc extends AbstractInitializedModelIntegrationTest { @@ -90,9 +78,7 @@ public void initSystem(Task initTask, OperationResult initResult) } @Test - public void test100GetRepositoryDiag() throws Exception { - final String TEST_NAME = "test100GetRepositoryDiag"; - + public void test100GetRepositoryDiag() { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -112,9 +98,7 @@ public void test100GetRepositoryDiag() throws Exception { } @Test - public void test110RepositorySelfTest() throws Exception { - final String TEST_NAME = "test110RepositorySelfTest"; - + public void test110RepositorySelfTest() { // GIVEN Task task = getTestTask(); @@ -132,8 +116,6 @@ public void test110RepositorySelfTest() throws Exception { @Test public void test200ExportUsers() throws Exception { - final String TEST_NAME = "test200ExportUsers"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -148,9 +130,9 @@ public void test200ExportUsers() throws Exception { assertSuccess(result); assertEquals("Unexpected number of users", 6, users.size()); - for (PrismObject user: users) { + for (PrismObject user : users) { display("Exporting user", user); - assertNotNull("Null definition in "+user, user.getDefinition()); + assertNotNull("Null definition in " + user, user.getDefinition()); display("Definition", user.getDefinition()); String xmlString = prismContext.serializerFor(PrismContext.LANG_XML).serialize(user); display("Exported user", xmlString); @@ -162,10 +144,8 @@ public void test200ExportUsers() throws Exception { validator.validate(new DOMSource(xmlDocument)); PrismObject parsedUser = prismContext.parseObject(xmlString); - assertTrue("Re-parsed user is not equal to original: "+user, user.equals(parsedUser)); - + assertEquals("Re-parsed user is not equal to original: " + user, parsedUser, user); } - } /** @@ -174,21 +154,19 @@ public void test200ExportUsers() throws Exception { */ @Test public void test210SearchUsersMatchingRulesPolystringNorm() throws Exception { - final String TEST_NAME = "test210SearchUsersMatchingRulesPolystringNorm"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = queryFor(UserType.class) .item(UserType.F_NAME) - .eq("JacK") - .matchingNorm() + .eq("JacK") + .matchingNorm() .build(); // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query,null , task, result); + List> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN then(); @@ -207,8 +185,6 @@ public void test210SearchUsersMatchingRulesPolystringNorm() throws Exception { */ @Test public void test212SearchUsersMatchingRulesPolystringIgnoreCase() throws Exception { - final String TEST_NAME = "test212SearchUsersMatchingRulesPolystringIgnoreCase"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -222,8 +198,7 @@ public void test212SearchUsersMatchingRulesPolystringIgnoreCase() throws Excepti try { // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query, null, task, result); - + modelService.searchObjects(UserType.class, query, null, task, result); } catch (SystemException e) { // this is expected } @@ -236,8 +211,6 @@ public void test212SearchUsersMatchingRulesPolystringIgnoreCase() throws Excepti */ @Test public void test214SearchUsersMatchingRulesStringIgnoreCase() throws Exception { - final String TEST_NAME = "test214SearchUsersMatchingRulesStringIgnoreCase"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -250,7 +223,7 @@ public void test214SearchUsersMatchingRulesStringIgnoreCase() throws Exception { // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query,null , task, result); + List> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN then(); @@ -269,8 +242,6 @@ public void test214SearchUsersMatchingRulesStringIgnoreCase() throws Exception { */ @Test public void test216SearchUsersMatchingRulesStringNorm() throws Exception { - final String TEST_NAME = "test216SearchUsersMatchingRulesStringNorm"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -283,7 +254,7 @@ public void test216SearchUsersMatchingRulesStringNorm() throws Exception { // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query,null , task, result); + List> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN then(); @@ -298,8 +269,6 @@ public void test216SearchUsersMatchingRulesStringNorm() throws Exception { */ @Test public void test300RecomputeJack() throws Exception { - final String TEST_NAME = "test300RecomputeJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -322,8 +291,6 @@ public void test300RecomputeJack() throws Exception { */ @Test public void test302UpdateKeyJack() throws Exception { - final String TEST_NAME = "test302UpdateKeyJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -343,8 +310,6 @@ public void test302UpdateKeyJack() throws Exception { @Test public void test310AddUserClean() throws Exception { - final String TEST_NAME = "test310AddUserClean"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -371,8 +336,6 @@ public void test310AddUserClean() throws Exception { */ @Test public void test312UpdateBinaryIdClean() throws Exception { - final String TEST_NAME = "test312UpdateBinaryIdClean"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -394,19 +357,14 @@ public void test312UpdateBinaryIdClean() throws Exception { * MID-4660, MID-4491, MID-3581 */ @Test - public void test320DefaultRelations() throws Exception { - final String TEST_NAME="test320DefaultRelations"; - - Task task = getTestTask(); - OperationResult result = task.getResult(); - + public void test320DefaultRelations() { // WHEN when(); List relations = modelInteractionService.getRelationDefinitions(); // THEN - then(); - display("Relations", relations); + then(); + display("Relations", relations); assertRelationDef(relations, SchemaConstants.ORG_MANAGER, "RelationTypes.manager"); assertRelationDef(relations, SchemaConstants.ORG_OWNER, "RelationTypes.owner"); assertEquals("Unexpected number of relation definitions", 7, relations.size()); @@ -417,8 +375,6 @@ public void test320DefaultRelations() throws Exception { */ @Test public void test400ImportRoleWithFilters() throws Exception { - final String TEST_NAME = "test400ImportRoleWithFilters"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -441,8 +397,6 @@ public void test400ImportRoleWithFilters() throws Exception { @Test public void test500AddHocProvisioningScriptAssignJackResourceScripty() throws Exception { - final String TEST_NAME = "test500AddHocProvisioningScriptAssignJackResourceScripty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -474,8 +428,6 @@ public void test500AddHocProvisioningScriptAssignJackResourceScripty() throws Ex */ @Test public void test502GetAccountJackResourceScripty() throws Exception { - final String TEST_NAME = "test502GetAccountJackResourceScripty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -506,8 +458,6 @@ public void test502GetAccountJackResourceScripty() throws Exception { */ @Test public void test504GetAccountJackResourceScriptyAgain() throws Exception { - final String TEST_NAME = "test504GetAccountJackResourceScriptyAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -543,8 +493,6 @@ public void test504GetAccountJackResourceScriptyAgain() throws Exception { */ @Test public void test506ModifyResourceGetAccountJackResourceScripty() throws Exception { - final String TEST_NAME = "test506ModifyResourceGetAccountJackResourceScripty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -567,33 +515,26 @@ public void test506ModifyResourceGetAccountJackResourceScripty() throws Exceptio PrismObject resourceAfter = getObject(ResourceType.class, RESOURCE_SCRIPTY_OID); display("Resource version after", resourceAfter.getVersion()); - assertFalse("Resource version is still the same: "+resourceAfter.getVersion(), resourceBefore.getVersion().equals(resourceAfter.getVersion())); + assertThat(resourceAfter.getVersion()) + .withFailMessage("Resource version is still the same") + .isNotEqualTo(resourceBefore.getVersion()); PrismObject accountShadow = modelService.getObject(ShadowType.class, accountOid, null, task, result); Integer dummyConnectorNumber = ShadowUtil.getAttributeValue(accountShadow, getDummyResourceController(RESOURCE_DUMMY_SCRIPTY_NAME).getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEALTH_NAME)); - assertTrue("Connector number hash changed: "+lastDummyConnectorNumber+" -> "+dummyConnectorNumber, - lastDummyConnectorNumber.equals(dummyConnectorNumber)); + assertEquals("Connector number hash changed: " + lastDummyConnectorNumber + " -> " + dummyConnectorNumber, + dummyConnectorNumber, lastDummyConnectorNumber); } - - /** * MID-4504 * midpoint.getLinkedShadow fails recomputing without throwing exception during shadow delete - * + *

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

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

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

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

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

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

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

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

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

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

* This situation is a kind of abnormal, but deleting non-present value is considered to be legal. * So we should treat a situation like this well. */ @Test public void test309JackConflictPlusAndMinusAgain() throws Exception { - final String TEST_NAME = "test309JackConflictPlusAndMinusAgain"; - - executeConflictPlusAndMinus(TEST_NAME); + executeConflictPlusAndMinus(); } /** @@ -854,8 +784,6 @@ public void test309JackConflictPlusAndMinusAgain() throws Exception { */ @Test public void test310JackConflictParentOrgRefAndAssignmentsAddOrg() throws Exception { - final String TEST_NAME = "test310JackConflictParentOrgRefAndAssignmentsAddOrg"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -887,12 +815,13 @@ public void test310JackConflictParentOrgRefAndAssignmentsAddOrg() throws Excepti */ @Test public void test349DeleteJack() throws Exception { - final String TEST_NAME = "test349DeleteJack"; - - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } - protected void executeDeleteJack(String TEST_NAME) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + protected void executeDeleteJack() + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -908,7 +837,7 @@ protected void executeDeleteJack(String TEST_NAME) throws ObjectAlreadyExistsExc TestUtil.assertSuccess(result); try { - PrismObject user = getUser(USER_JACK_OID); + getUser(USER_JACK_OID); AssertJUnit.fail("Jack survived!"); } catch (ObjectNotFoundException e) { // This is expected @@ -920,8 +849,6 @@ protected void executeDeleteJack(String TEST_NAME) throws ObjectAlreadyExistsExc */ @Test public void test350AddJackAsMinistryOfOffenseManager() throws Exception { - final String TEST_NAME = "test350AddJackAsMinistryOfOffenseManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -969,8 +896,6 @@ public void test350AddJackAsMinistryOfOffenseManager() throws Exception { @Test public void test360ElaineAssignGovernor() throws Exception { - final String TEST_NAME = "test360ElaineAssignGovernor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1005,8 +930,6 @@ public void test360ElaineAssignGovernor() throws Exception { @Test public void test362ElaineAssignGovernmentMember() throws Exception { - final String TEST_NAME = "test362ElaineAssignGovernmentMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1042,8 +965,6 @@ public void test362ElaineAssignGovernmentMember() throws Exception { @Test public void test365GuybrushAssignSwashbucklerMember() throws Exception { - final String TEST_NAME = "test365GuybrushAssignSwashbucklerMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1085,8 +1006,6 @@ public void test365GuybrushAssignSwashbucklerMember() throws Exception { @Test public void test368GuybrushAssignSwashbucklerManager() throws Exception { - final String TEST_NAME = "test368GuybrushAssignSwashbucklerManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1130,8 +1049,6 @@ public void test368GuybrushAssignSwashbucklerManager() throws Exception { @Test public void test370BarbossaAssignOffenseMember() throws Exception { - final String TEST_NAME = "test370BarbossaAssignOffenseMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1180,8 +1097,6 @@ public void test370BarbossaAssignOffenseMember() throws Exception { @Test public void test372HermanAssignSwashbucklerMember() throws Exception { - final String TEST_NAME = "test365GuybrushAssignSwashbucklerMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userHerman = getUser(USER_HERMAN_OID); @@ -1239,9 +1154,7 @@ public void test372HermanAssignSwashbucklerMember() throws Exception { @Test public void test399DeleteJack() throws Exception { - final String TEST_NAME = "test399DeleteJack"; - - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } /** @@ -1249,8 +1162,6 @@ public void test399DeleteJack() throws Exception { */ @Test public void test400AddJackWithOrgUnit() throws Exception { - final String TEST_NAME = "test400AddJackWithOrgUnit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1277,14 +1188,12 @@ public void test400AddJackWithOrgUnit() throws Exception { @Test public void test402JackChangeMinistryOfOffenseMemberToManagerByAddingRemovingAssignment() throws Exception { - final String TEST_NAME = "test402JackChangeMinistryOfOffenseMemberToManagerByAddingRemovingAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject jack = getUser(USER_JACK_OID); + assertThat(getUser(USER_JACK_OID)).isNotNull(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, null, null, null, false)); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, true)); @@ -1312,14 +1221,12 @@ public void test402JackChangeMinistryOfOffenseMemberToManagerByAddingRemovingAss @Test public void test404JackChangeMinistryOfOffenseManagerToMemberByAddingRemovingAssignment() throws Exception { - final String TEST_NAME = "test404JackChangeMinistryOfOffenseManagerToMemberByAddingRemovingAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject jack = getUser(USER_JACK_OID); + assertThat(getUser(USER_JACK_OID)).isNotNull(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, false)); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); @@ -1345,9 +1252,7 @@ public void test404JackChangeMinistryOfOffenseManagerToMemberByAddingRemovingAss @Test public void test409DeleteJack() throws Exception { - final String TEST_NAME = "test409DeleteJack"; - - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } /** @@ -1356,8 +1261,6 @@ public void test409DeleteJack() throws Exception { */ @Test public void test410AddJackWithOrgUnit() throws Exception { - final String TEST_NAME = "test400AddJackWithOrgUnit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1385,15 +1288,13 @@ public void test410AddJackWithOrgUnit() throws Exception { // this test should generate a SchemaException (modifying targetRef in assignment should be prohibited) @Test public void test412JackChangeMinistryOfOffenseMemberToManagerByModifyingAssignment() throws Exception { - final String TEST_NAME = "test412JackChangeMinistryOfOffenseMemberToManagerByModifyingAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject jack = getUser(USER_JACK_OID); Long id = findAssignmentIdForTarget(jack, ORG_MINISTRY_OF_OFFENSE_OID); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceDefinition referenceDefinition = getUserDefinition() .findItemDefinition( @@ -1426,8 +1327,6 @@ public void test412JackChangeMinistryOfOffenseMemberToManagerByModifyingAssignme // import temp org + assign to jack (preparation for the next test) @Test public void test420JackAssignTempOrg() throws Exception { - final String TEST_NAME = "test420JackAssignTempOrg"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1449,8 +1348,6 @@ public void test420JackAssignTempOrg() throws Exception { // delete the org and then unassign it @Test public void test425JackUnassignDeletedOrg() throws Exception { - final String TEST_NAME = "test425JackUnassignDeletedOrg"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1477,8 +1374,6 @@ public void test425JackUnassignDeletedOrg() throws Exception { @Test public void test430JackAssignMetaroleOffender() throws Exception { - final String TEST_NAME = "test430JackAssignMetaroleOffender"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1487,7 +1382,7 @@ public void test430JackAssignMetaroleOffender() throws Exception { assertAssignedOrgs(userJackBefore, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(userJackBefore, ORG_MINISTRY_OF_OFFENSE_OID); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ROLE_OFFENDER_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); @@ -1496,7 +1391,6 @@ public void test430JackAssignMetaroleOffender() throws Exception { // WHEN modelService.executeChanges(deltas, null, task, result); - // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -1512,12 +1406,10 @@ public void test430JackAssignMetaroleOffender() throws Exception { @Test public void test431JackAssignMetaroleOffenderAdmin() throws Exception { - final String TEST_NAME = "test431JackAssignMetaroleOffenderAdmin"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ROLE_OFFENDER_ADMIN_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); @@ -1526,7 +1418,6 @@ public void test431JackAssignMetaroleOffenderAdmin() throws Exception { // WHEN modelService.executeChanges(deltas, null, task, result); - // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); @@ -1540,8 +1431,6 @@ public void test431JackAssignMetaroleOffenderAdmin() throws Exception { @Test public void test437JackUnassignOffender() throws Exception { - final String TEST_NAME = "test437JackUnassignOffender"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1567,8 +1456,6 @@ public void test437JackUnassignOffender() throws Exception { @Test public void test438JackUnassignOffenderAdmin() throws Exception { - final String TEST_NAME = "test438JackUnassignOffenderAdmin"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1593,8 +1480,6 @@ public void test438JackUnassignOffenderAdmin() throws Exception { @Test public void test439JackCleanup() throws Exception { - final String TEST_NAME = "test439JackCleanup"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1613,7 +1498,6 @@ public void test439JackCleanup() throws Exception { assertMonkeyIslandOrgSanity(); } - // Now let's test working with assignments when there is an object template that prescribes an org assignment // based on organizationalUnit property. @@ -1622,8 +1506,6 @@ public void test439JackCleanup() throws Exception { */ @Test public void test440JackModifyEmployeeTypeRolePirate() throws Exception { - final String TEST_NAME = "test440JackModifyEmployeeTypeRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1651,8 +1533,6 @@ public void test440JackModifyEmployeeTypeRolePirate() throws Exception { */ @Test public void test441JackModifyEmployeeTypeRoleCaptain() throws Exception { - final String TEST_NAME = "test441JackModifyEmployeeTypeRoleCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1677,8 +1557,6 @@ public void test441JackModifyEmployeeTypeRoleCaptain() throws Exception { */ @Test public void test443JackModifyEmployeeTypeRoleNotExist() throws Exception { - final String TEST_NAME = "test443JackModifyEmployeeTypeRoleNotExist"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1698,14 +1576,11 @@ public void test443JackModifyEmployeeTypeRoleNotExist() throws Exception { assertMonkeyIslandOrgSanity(); } - /** * MID-3545 */ @Test public void test449JackModifyEmployeeTypeNull() throws Exception { - final String TEST_NAME = "test449JackModifyEmployeeTypeNull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1726,8 +1601,6 @@ public void test449JackModifyEmployeeTypeNull() throws Exception { @Test public void test500JackEndPirate() throws Exception { - final String TEST_NAME = "test500JackEndPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1761,8 +1634,6 @@ public void test500JackEndPirate() throws Exception { */ @Test public void test510JackEndPirate() throws Exception { - final String TEST_NAME = "test510JackEndPirate"; - login(USER_JACK_USERNAME); Task task = getTestTask(); @@ -1789,23 +1660,18 @@ public void test510JackEndPirate() throws Exception { assertMonkeyIslandOrgSanity(); } - - @Test public void test799DeleteJack() throws Exception { - final String TEST_NAME = "test799DeleteJack"; - login(USER_ADMINISTRATOR_USERNAME); - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } - // BEWARE, tests 800+ are executed in TestOrgStructMeta, so this class has to end with test799 and no jack present // --------------------------------------------------------------------------------------------------------------- protected void assertUserOrg(PrismObject user, String... orgOids) throws Exception { - for (String orgOid: orgOids) { + for (String orgOid : orgOids) { assertAssignedOrg(user, orgOid); assertHasOrg(user, orgOid); } @@ -1828,19 +1694,20 @@ private void assertManager(String userOid, String managerOid, String orgType, bo if (managers == null || managers.isEmpty()) { return; } else { - AssertJUnit.fail("Expected no manager for "+user+", but got "+managers); + AssertJUnit.fail("Expected no manager for " + user + ", but got " + managers); } } else { if (managers == null) { - AssertJUnit.fail("Expected manager for "+user+", but got no manager"); - } if (managers.size() != 1) { - AssertJUnit.fail("Expected one manager for "+user+", but got: "+managers); + AssertJUnit.fail("Expected manager for " + user + ", but got no manager"); + } + if (managers.size() != 1) { + AssertJUnit.fail("Expected one manager for " + user + ", but got: " + managers); } else { UserType manager = managers.iterator().next(); if (manager.getOid().equals(managerOid)) { return; } else { - AssertJUnit.fail("Expected manager with OID "+managerOid+" for "+user+", but got "+manager); + AssertJUnit.fail("Expected manager with OID " + managerOid + " for " + user + ", but got " + manager); } } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java index be3601033a4..a901a7e061b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java @@ -8,15 +8,14 @@ import java.io.File; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Listeners; import org.testng.annotations.Test; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; @@ -28,9 +27,8 @@ /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationTest { @@ -38,7 +36,6 @@ public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationT public static final File TEST_DIR = new File("src/test/resources/orgstruct"); protected static final File ORG_CARIBBEAN_FILE = new File(TEST_DIR, "org-caribbean.xml"); - protected static final String ORG_CARIBBEAN_TOP_OID = "00000000-8888-6666-0000-c00000000001"; protected static final String ORG_CARIBBEAN_THE_CROWN_OID = "00000000-8888-6666-0000-c00000000002"; protected static final String ORG_CARIBBEAN_JAMAICA_OID = "00000000-8888-6666-0000-c00000000003"; protected static final String ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID = "00000000-8888-6666-0000-c00000000004"; @@ -54,7 +51,6 @@ public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationT public static final String USER_PINTEL_USERNAME = "pintel"; public static final File ROLE_META_PIRACY_ORG_FILE = new File(TEST_DIR, "role-meta-piracy-org.xml"); - public static final String ROLE_META_PIRACY_ORG_OID = "d534f1b2-a26c-11e6-abf5-e71dff038896"; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -64,19 +60,14 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti addObject(USER_PINTEL_FILE); addObject(ROLE_META_PIRACY_ORG_FILE); - - //DebugUtil.setDetailedDebugDump(true); } - /** * MID-3448 */ @Test public void test100AddOrgCaribbean() throws Exception { - final String TEST_NAME = "test100AddOrgCaribbean"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -109,9 +100,7 @@ public void test100AddOrgCaribbean() throws Exception { */ @Test public void test102RecomputeJamaica() throws Exception { - final String TEST_NAME = "test102RecomputeJamaica"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -139,9 +128,7 @@ public void test102RecomputeJamaica() throws Exception { */ @Test public void test103ReconcileJamaica() throws Exception { - final String TEST_NAME = "test103ReconcileJamaica"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -169,9 +156,7 @@ public void test103ReconcileJamaica() throws Exception { */ @Test public void test104RecomputeGovernor() throws Exception { - final String TEST_NAME = "test104RecomputeGovernor"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -199,9 +184,7 @@ public void test104RecomputeGovernor() throws Exception { */ @Test public void test105ReconcileGovernor() throws Exception { - final String TEST_NAME = "test105ReconcileGovernor"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -227,14 +210,12 @@ public void test105ReconcileGovernor() throws Exception { /** * Jamaica has an inducement to Monkey Island Governor Office. * Sub-orgs of Jamaica should appear under Governor office. - * + *

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

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

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

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

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

* i.e. it works only when evaluateAllAssignmentRelationsOnRecompute option is set */ @Test(enabled = false) public void test950JackSelfExclusion() throws Exception { - final String TEST_NAME = "test950JackSelfExclusion"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1765,8 +1625,6 @@ public void test950JackSelfExclusion() throws Exception { @Test public void test952JackSelfExclusionManagerMember() throws Exception { - final String TEST_NAME = "test952JackSelfExclusionManagerMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1795,8 +1653,6 @@ public void test952JackSelfExclusionManagerMember() throws Exception { // MID-5207 @Test public void test960JimGoldByMapping() throws Exception { - final String TEST_NAME = "test960JimGoldByMapping"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1805,7 +1661,7 @@ public void test960JimGoldByMapping() throws Exception { UserType jim = new UserType(prismContext) .name("jim") .beginAssignment() - .targetRef(ROLE_PRIZE_SILVER_OID, RoleType.COMPLEX_TYPE) + .targetRef(ROLE_PRIZE_SILVER_OID, RoleType.COMPLEX_TYPE) .end(); addObject(jim.asPrismObject()); @@ -1827,7 +1683,11 @@ public void test960JimGoldByMapping() throws Exception { assertNotAssignedRole(userAfter, ROLE_PRIZE_BRONZE_OID); } - private PrismObject assignRolePolicyFailure(String TEST_NAME, String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, SecurityViolationException { + private PrismObject assignRolePolicyFailure( + String userOid, String roleOid, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + SecurityViolationException { try { // WHEN @@ -1849,15 +1709,4 @@ private PrismObject assignRolePolicyFailure(String TEST_NAME, String u assertNotAssignedRole(userAfter, roleOid); return userAfter; } - - private void assertPolicySituation(PrismObject user, String targetOid, String... expectedPolicySituation) { - for (AssignmentType assignment: user.asObjectable().getAssignment()) { - ObjectReferenceType targetRef = assignment.getTargetRef(); - if (targetRef != null && targetOid.equals(targetRef.getOid())) { - PrismAsserts.assertSets("Wrong policy situation for target "+targetOid+" in "+user, assignment.getPolicySituation(), expectedPolicySituation); - } - } - } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java index db98a3d791c..585cf3d7840 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java @@ -159,7 +159,6 @@ protected int getNumberOfRoles() { */ @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -187,7 +186,6 @@ public void test000Sanity() throws Exception { */ @Test public void test080AutzJackEndUserPassword() throws Exception { - final String TEST_NAME = "test080AutzJackEndUserPassword"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -230,7 +228,6 @@ public void test080AutzJackEndUserPassword() throws Exception { @Test public void test100AutzJackPersonaManagement() throws Exception { - final String TEST_NAME = "test100AutzJackPersonaManagement"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PERSONA_MANAGEMENT_OID); @@ -256,7 +253,6 @@ public void test100AutzJackPersonaManagement() throws Exception { @Test public void test102AutzLechuckPersonaManagement() throws Exception { - final String TEST_NAME = "test102AutzLechuckPersonaManagement"; // GIVEN cleanupAutzTest(USER_LECHUCK_OID, 1); assignRole(USER_LECHUCK_OID, ROLE_PERSONA_MANAGEMENT_OID); @@ -286,7 +282,6 @@ public void test102AutzLechuckPersonaManagement() throws Exception { */ @Test public void test110AutzJackPersonaAdmin() throws Exception { - final String TEST_NAME = "test110AutzJackAddPersonaAdmin"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PERSONA_MANAGEMENT_OID); @@ -342,7 +337,6 @@ public void test110AutzJackPersonaAdmin() throws Exception { @Test public void test120AutzJackDelagator() throws Exception { - final String TEST_NAME = "test120AutzJackDelagator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_OID); @@ -449,7 +443,6 @@ public void test120AutzJackDelagator() throws Exception { */ @Test public void test122AutzJackDelagatorValidity() throws Exception { - final String TEST_NAME = "test122AutzJackDelagatorValidity"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_OID); @@ -595,7 +588,6 @@ public void test122AutzJackDelagatorValidity() throws Exception { */ @Test public void test124AutzJackDelagatorPlusValidity() throws Exception { - final String TEST_NAME = "test124AutzJackDelagatorPlusValidity"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_PLUS_OID); @@ -750,7 +742,6 @@ public void test124AutzJackDelagatorPlusValidity() throws Exception { @Test public void test150AutzJackApproverUnassignRoles() throws Exception { - final String TEST_NAME = "test150AutzJackApproverUnassignRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID); @@ -794,7 +785,6 @@ public void test150AutzJackApproverUnassignRoles() throws Exception { @Test public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { - final String TEST_NAME = "test151AutzJackApproverUnassignRolesAndRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID); @@ -836,7 +826,6 @@ public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { */ @Test public void test154AutzJackApproverRead() throws Exception { - final String TEST_NAME = "test154AutzJackApproverRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_BASIC_ITEMS_OID); @@ -901,7 +890,6 @@ public void test154AutzJackApproverRead() throws Exception { */ @Test public void test155AutzJackApproverSelf() throws Exception { - final String TEST_NAME = "test155AutzJackApproverSelf"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_OID); @@ -958,7 +946,6 @@ public void test155AutzJackApproverSelf() throws Exception { @Test public void test157AutzJackReadRoleMembers() throws Exception { - final String TEST_NAME = "test157AutzJackReadRoleMembers"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_OID); @@ -1010,7 +997,6 @@ public void test157AutzJackReadRoleMembers() throws Exception { @Test public void test158AutzJackReadRoleMembersWrong() throws Exception { - final String TEST_NAME = "test158AutzJackReadRoleMembersWrong"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_WRONG_OID); @@ -1062,7 +1048,6 @@ public void test158AutzJackReadRoleMembersWrong() throws Exception { @Test public void test159AutzJackReadRoleMembersNone() throws Exception { - final String TEST_NAME = "test159AutzJackReadRoleMembersNone"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_NONE_OID); @@ -1164,7 +1149,6 @@ private void assert15xCommon() throws Exception { */ @Test public void test200AutzJackModifyOrgunit() throws Exception { - final String TEST_NAME = "test200AutzJackModifyOrgunit"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SELF_MODIFY_ORGUNIT_OID); @@ -1224,7 +1208,6 @@ public void test200AutzJackModifyOrgunit() throws Exception { */ @Test public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { - final String TEST_NAME = "test202AutzJackModifyOrgunitAndAssignRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SELF_MODIFY_ORGUNIT_OID); @@ -1298,7 +1281,6 @@ public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { */ @Test public void test220AutzJackRoleExpressionNoConstCenter() throws Exception { - final String TEST_NAME = "test220AutzJackRoleExpressionNoConstCenter"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EXPRESSION_READ_ROLES_OID); @@ -1337,7 +1319,6 @@ public void test220AutzJackRoleExpressionNoConstCenter() throws Exception { */ @Test public void test222AutzJackRoleExpressionConstCenterBusiness() throws Exception { - final String TEST_NAME = "test222AutzJackRoleExpressionConstCenterBusiness"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EXPRESSION_READ_ROLES_OID); @@ -1379,7 +1360,6 @@ public void test222AutzJackRoleExpressionConstCenterBusiness() throws Exception */ @Test public void test230AttorneyCaribbeanUnlimited() throws Exception { - final String TEST_NAME = "test230AttorneyCaribbeanUnlimited"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_CARIBBEAN_UNLIMITED_OID); @@ -1452,7 +1432,6 @@ public void test230AttorneyCaribbeanUnlimited() throws Exception { */ @Test public void test232ManagerAttorneyNoOrg() throws Exception { - final String TEST_NAME = "test232ManagerAttorneyNoOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_MANAGER_WORKITEMS_OID); @@ -1501,7 +1480,6 @@ public void test232ManagerAttorneyNoOrg() throws Exception { */ @Test public void test234ManagerAttorneyRum() throws Exception { - final String TEST_NAME = "test234ManagerAttorneyRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_MANAGER_WORKITEMS_OID); @@ -1567,7 +1545,6 @@ public void test234ManagerAttorneyRum() throws Exception { */ @Test public void test235ManagerAttorneyRumRogersEntitled() throws Exception { - final String TEST_NAME = "test234ManagerAttorneyRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_MANAGER_WORKITEMS_OID); @@ -1635,7 +1612,6 @@ public void test235ManagerAttorneyRumRogersEntitled() throws Exception { */ @Test public void test236ManagerAttorneyCaribbeanRum() throws Exception { - final String TEST_NAME = "test236ManagerAttorneyCaribbeanRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_CARIBBEAN_UNLIMITED_OID); @@ -1716,7 +1692,6 @@ public void test236ManagerAttorneyCaribbeanRum() throws Exception { */ @Test public void test250AssignRequestableSelfOtherApporver() throws Exception { - final String TEST_NAME = "test250AssignRequestableSelfOtherApporver"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_SELF_REQUESTABLE_ANY_APPROVER_OID); @@ -1809,7 +1784,6 @@ public void test250AssignRequestableSelfOtherApporver() throws Exception { */ @Test public void test252AssignRequestableSelfOtherApporverEmptyDelta() throws Exception { - final String TEST_NAME = "test252AssignRequestableSelfOtherApporverEmptyDelta"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_SELF_REQUESTABLE_ANY_APPROVER_OID); @@ -1880,7 +1854,6 @@ public void test252AssignRequestableSelfOtherApporverEmptyDelta() throws Excepti @Test public void test254AssignUnassignRequestableSelf() throws Exception { - final String TEST_NAME = "test254AssignUnassignRequestableSelf"; // GIVENds cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UNASSIGN_SELF_REQUESTABLE_OID); @@ -1916,7 +1889,6 @@ public void test254AssignUnassignRequestableSelf() throws Exception { @Test public void test256AssignUnassignRequestableSelfEmptyDelta() throws Exception { - final String TEST_NAME = "test256AssignUnassignRequestableSelfEmptyDelta"; // GIVENds cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UNASSIGN_SELF_REQUESTABLE_OID); @@ -1952,7 +1924,6 @@ public void test256AssignUnassignRequestableSelfEmptyDelta() throws Exception { @Test public void test260AutzJackLimitedRoleAdministrator() throws Exception { - final String TEST_NAME = "test260AutzJackLimitedRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2089,7 +2060,6 @@ public void test260AutzJackLimitedRoleAdministrator() throws Exception { */ @Test public void test262AutzJackLimitedRoleAdministratorAndAssignApplicationRoles() throws Exception { - final String TEST_NAME = "test260AutzJackLimitedRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2215,7 +2185,6 @@ public void test262AutzJackLimitedRoleAdministratorAndAssignApplicationRoles() t */ @Test public void test264AutzJackLimitedReadRoleAdministrator() throws Exception { - final String TEST_NAME = "test264AutzJackLimitedReadRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_READ_ROLE_ADMINISTRATOR_OID); @@ -2316,7 +2285,6 @@ public void test264AutzJackLimitedReadRoleAdministrator() throws Exception { */ @Test public void test266AutzJackRoleAdministrator() throws Exception { - final String TEST_NAME = "test266AutzJackRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ROLE_ADMINISTRATOR_OID); @@ -2373,7 +2341,6 @@ public void test266AutzJackRoleAdministrator() throws Exception { @Test public void test270AutzJackModifyPolicyException() throws Exception { - final String TEST_NAME = "test270AutzJackModifyPolicyException"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_MODIFY_POLICY_EXCEPTION_OID); @@ -2430,7 +2397,6 @@ public void test270AutzJackModifyPolicyException() throws Exception { @Test public void test272AutzJackModifyPolicyExceptionFirstRule() throws Exception { - final String TEST_NAME = "test272AutzJackModifyPolicyExceptionFirstRule"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_MODIFY_POLICY_EXCEPTION_OID); @@ -2530,7 +2496,6 @@ public void test274AutzJackModifyPolicyExceptionSituation() throws Exception { */ @Test public void test280AutzJackModifyPolicyExceptionAndAssignOrg() throws Exception { - final String TEST_NAME = "test280AutzJackModifyPolicyExceptionAndAssignOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2566,7 +2531,6 @@ public void test280AutzJackModifyPolicyExceptionAndAssignOrg() throws Exception */ @Test public void test282AutzJackModifyPolicyExceptionAndAssignOrgDeny() throws Exception { - final String TEST_NAME = "test282AutzJackModifyPolicyExceptionAndAssignOrgDeny"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2599,7 +2563,6 @@ public void test282AutzJackModifyPolicyExceptionAndAssignOrgDeny() throws Except */ @Test public void test283AutzJackModifyPolicyAssignOrg() throws Exception { - final String TEST_NAME = "test283AutzJackModifyPolicyAssignOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_ORG_OID); @@ -2642,7 +2605,6 @@ protected void modifyRoleAddExclusionAndAssignOrg( @Test public void test300AutzJackExceptAssignment() throws Exception { - final String TEST_NAME = "test300AutzJackExceptAssignment"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_EXCEPT_ASSIGNMENT_OID); @@ -2705,7 +2667,6 @@ public void test300AutzJackExceptAssignment() throws Exception { @Test public void test302AutzJackExceptAdministrativeStatus() throws Exception { - final String TEST_NAME = "test302AutzJackExceptAdministrativeStatus"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_EXCEPT_ADMINISTRATIVE_STATUS_OID); @@ -2773,7 +2734,6 @@ public void test302AutzJackExceptAdministrativeStatus() throws Exception { */ @Test public void test304AutzJackPropExceptAssignmentReadSomeModifySomeUser() throws Exception { - final String TEST_NAME = "test304AutzJackPropExceptAssignmentReadSomeModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID); @@ -2830,7 +2790,6 @@ public void test304AutzJackPropExceptAssignmentReadSomeModifySomeUser() throws E */ @Test public void test306AutzJackPropExceptAssignmentExceptAdministrativeStatus() throws Exception { - final String TEST_NAME = "test306AutzJackPropExceptAssignmentExceptAdministrativeStatus"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_EXCEPT_ADMINISTRATIVE_STATUS_OID); @@ -2887,7 +2846,6 @@ public void test306AutzJackPropExceptAssignmentExceptAdministrativeStatus() thro */ @Test public void test308AutzJackPropExceptAssignmentAssignApplicationRoles() throws Exception { - final String TEST_NAME = "test308AutzJackPropExceptAssignmentAssignApplicationRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_APPLICATION_ROLES_OID); @@ -2981,7 +2939,6 @@ public void test308AutzJackPropExceptAssignmentAssignApplicationRoles() throws E */ @Test public void test310AutzJackPropSubtypeDenyEscapingZoneOfControl() throws Exception { - final String TEST_NAME = "test310AutzJackPropSubtypeDenyEscapingZoneOfControl"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_SUBTYPE_OID); @@ -3016,7 +2973,6 @@ public void test310AutzJackPropSubtypeDenyEscapingZoneOfControl() throws Excepti */ @Test public void test312AutzJackPropSubtypeAllowEscapingZoneOfControl() throws Exception { - final String TEST_NAME = "test312AutzJackPropSubtypeAllowEscapingZoneOfControl"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_SUBTYPE_ESCAPE_OID); @@ -3102,7 +3058,6 @@ public void test320AutzJackGuybrushValutDweller() throws Exception { */ @Test public void test330AutzJackEndUserWithPrivacy() throws Exception { - final String TEST_NAME = "test330AutzJackEndUserWithPrivacy"; // GIVEN cleanupAutzTest(USER_JACK_OID); assertNoDummyAccount(RESOURCE_DUMMY_VAULT_NAME, USER_GUYBRUSH_USERNAME); @@ -3148,7 +3103,6 @@ public void test330AutzJackEndUserWithPrivacy() throws Exception { */ @Test public void test340AutzJackSuperUserAndExecRead() throws Exception { - final String TEST_NAME = "test340AutzJackSuperUserAndExecRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3181,7 +3135,6 @@ public void test340AutzJackSuperUserAndExecRead() throws Exception { */ @Test public void test350AutzJackResourceRead() throws Exception { - final String TEST_NAME = "test350AutzJackResourceRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3207,7 +3160,6 @@ public void test350AutzJackResourceRead() throws Exception { */ @Test public void test360AutzAdminResourceRead() throws Exception { - final String TEST_NAME = "test350AutzAdminResourceRead"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); @@ -3286,10 +3238,13 @@ private AssignmentType assertExclusion(PrismObject roleExclusion, Stri } @Override - protected void cleanupAutzTest(String userOid, int expectedAssignments) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException, IOException { + protected void cleanupAutzTest(String userOid, int expectedAssignments) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + PolicyViolationException, SecurityViolationException, IOException { super.cleanupAutzTest(userOid, expectedAssignments); - Task task = taskManager.createTaskInstance(TestSecurityAdvanced.class.getName() + ".cleanupAutzTest"); + Task task = getTestTask(); OperationResult result = task.getResult(); assignRole(userRumRogersOid, ROLE_ORDINARY_OID, task, result); @@ -3299,14 +3254,16 @@ protected void cleanupAutzTest(String userOid, int expectedAssignments) throws O } - private void assertDeputySearchDelegatorRef(String delegatorOid, String... expectedDeputyOids) throws Exception { + private void assertDeputySearchDelegatorRef(String delegatorOid, String... expectedDeputyOids) + throws Exception { PrismReferenceValue rval = itemFactory().createReferenceValue(delegatorOid, UserType.COMPLEX_TYPE); rval.setRelation(SchemaConstants.ORG_DEPUTY); ObjectQuery query = queryFor(UserType.class).item(UserType.F_DELEGATED_REF).ref(rval).build(); assertSearch(UserType.class, query, expectedDeputyOids); } - private void assertDeputySearchAssignmentTarget(String delegatorOid, String... expectedDeputyOids) throws Exception { + private void assertDeputySearchAssignmentTarget( + String delegatorOid, String... expectedDeputyOids) throws Exception { PrismReferenceValue rval = itemFactory().createReferenceValue(delegatorOid, UserType.COMPLEX_TYPE); rval.setRelation(SchemaConstants.ORG_DEPUTY); ObjectQuery query = queryFor(UserType.class) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java index 8f38fc3e0b9..8b148cdd5bf 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java @@ -1339,7 +1339,6 @@ public void test241AutzJackManagerFullControlMemberMinistryOfRum() throws Except */ @Test public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Exception { - final String TEST_NAME = "test242AutzJackManagerFullControlManagerMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1357,7 +1356,7 @@ public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Excep // WHEN when(); - assertJack24xManager(TEST_NAME, true); + assertJack24xManager(true); assertGlobalStateUntouched(); } @@ -1367,7 +1366,6 @@ public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Excep */ @Test public void test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense() throws Exception { - final String TEST_NAME = "test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1388,7 +1386,7 @@ public void test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense() th // WHEN when(); - assertJack24xManagerDefense(TEST_NAME, true); + assertJack24xManagerDefense(true); assertGlobalStateUntouched(); } @@ -1423,7 +1421,6 @@ public void test245AutzJackManagerUserAdminMemberMinistryOfRum() throws Exceptio */ @Test public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Exception { - final String TEST_NAME = "test246AutzJackManagerUserAdminManagerMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1441,7 +1438,7 @@ public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Excepti // WHEN when(); - assertJack24xManager(TEST_NAME, false); + assertJack24xManager(false); assertGlobalStateUntouched(); } @@ -1451,7 +1448,6 @@ public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Excepti */ @Test public void test247AutzJackManagerUserAdminManagerMinistryOfRumAndDefense() throws Exception { - final String TEST_NAME = "test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1470,7 +1466,7 @@ public void test247AutzJackManagerUserAdminManagerMinistryOfRumAndDefense() thro // WHEN when(); - assertJack24xManagerDefense(TEST_NAME, false); + assertJack24xManagerDefense(false); assertGlobalStateUntouched(); } @@ -1504,7 +1500,7 @@ private void assertJack24xMember(String accountOid) throws Exception { new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext)), 0); } - private void assertJack24xManager(final String TEST_NAME, boolean fullControl) throws Exception { + private void assertJack24xManager(boolean fullControl) throws Exception { assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); @@ -1530,7 +1526,7 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t assertAddDenyRaw(USER_MANCOMB_FILE); assertAddAllow(USER_MANCOMB_FILE); // MID-3874 - Task task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); + Task task = createPlainTask(); OperationResult result = task.getResult(); try { addObject(ORG_CHEATERS_FILE, task, result); // MID-3874 @@ -1570,7 +1566,7 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t // MID-2822 - task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); + task = createPlainTask(); result = task.getResult(); ObjectQuery query = prismContext.queryFactory().createQuery( @@ -1599,7 +1595,7 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t assertVisibleUsers(4); } - private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) throws Exception { + private void assertJack24xManagerDefense(boolean fullControl) throws Exception { assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); @@ -1654,7 +1650,7 @@ private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) // MID-2822 - Task task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); + Task task = createPlainTask(); OperationResult result = task.getResult(); ObjectQuery query = prismContext.queryFactory().createQuery( @@ -3003,7 +2999,7 @@ public void test295AutzJackAssignOrgRelation() throws Exception { .assertNotNull() .getFilter(); - Task task = taskManager.createTaskInstance(); + Task task = createPlainTask(); SearchResultList> assignableRolesJack = modelService.searchObjects(AbstractRoleType.class, prismContext.queryFactory().createQuery(jackAssignableRoleFilter), null, task, task.getResult()); display("Assignable roles", assignableRolesJack); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java index 0f03b6409da..847f36f7979 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java @@ -21,14 +21,12 @@ /** * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSecurityMedium extends AbstractSecurityTest { protected static final File USER_EMPLOYEE_FRED_FILE = new File(TEST_DIR, "user-employee-fred.xml"); - protected static final String USER_EMPLOYEE_FRED_OID = "4e63d9a2-d575-11e9-9c19-cb0e0207a10e"; protected static final File ROLE_EMPLOYEE_MANAGER_FILE = new File(TEST_DIR, "role-employee-manager.xml"); protected static final String ROLE_EMPLOYEE_MANAGER_OID = "5549cb8e-d573-11e9-a61e-7f2eff22715a"; @@ -53,7 +51,6 @@ protected int getNumberOfRoles() { */ @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -77,7 +74,6 @@ public void test000Sanity() throws Exception { */ @Test public void test100AutzEmployeeManager() throws Exception { - final String TEST_NAME = "test100AutzEmployeeManager"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EMPLOYEE_MANAGER_OID); @@ -107,7 +103,6 @@ public void test100AutzEmployeeManager() throws Exception { */ @Test public void test102AutzEmployeeManagerAddEmployee() throws Exception { - final String TEST_NAME = "test102AutzEmployeeManagerAddEmployee"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EMPLOYEE_MANAGER_OID); @@ -126,6 +121,4 @@ public void test102AutzEmployeeManagerAddEmployee() throws Exception { assertDeleteDeny(); assertGlobalStateUntouched(); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java index 1449864b2ee..203c5911a22 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java @@ -211,7 +211,6 @@ protected int getNumberOfRoles() { */ @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -239,7 +238,6 @@ public void test000Sanity() throws Exception { */ @Test public void test010ImportOrgstruct() throws Exception { - final String TEST_NAME = "test010ImportOrgstruct"; // GIVEN Task task = getTestTask(); @@ -375,7 +373,6 @@ public void test010ImportOrgstruct() throws Exception { */ @Test public void test100AutzLetoRead() throws Exception { - final String TEST_NAME = "test100AutzLetoRead"; // GIVEN cleanupAutzTest(null); @@ -416,7 +413,6 @@ public void test100AutzLetoRead() throws Exception { */ @Test public void test102AutzLetoAdd() throws Exception { - final String TEST_NAME = "test102AutzLetoAdd"; // GIVEN cleanupAutzTest(null); @@ -460,7 +456,6 @@ public void test102AutzLetoAdd() throws Exception { */ @Test public void test104AutzLetoModify() throws Exception { - final String TEST_NAME = "test104AutzLetoModify"; // GIVEN cleanupAutzTest(null); @@ -491,7 +486,6 @@ public void test104AutzLetoModify() throws Exception { */ @Test public void test106AutzLetoAddResourceTask() throws Exception { - final String TEST_NAME = "test106AutzLetoAddResourceTask"; // GIVEN cleanupAutzTest(null); @@ -524,7 +518,7 @@ private void assertAddDummyResourceAllow(File file) throws SchemaException, IOEx assertAddAllow(resource, null); } - private void assertAddDummyResourceDeny(File file) throws SchemaException, IOException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + private void assertAddDummyResourceDeny(File file) throws SchemaException, IOException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { PrismObject resource = PrismTestUtil.parseObject(file); resource.asObjectable() .connectorRef(dummyConnector.getOid(), ConnectorType.COMPLEX_TYPE); @@ -536,7 +530,6 @@ private void assertAddDummyResourceDeny(File file) throws SchemaException, IOExc */ @Test public void test109AutzLetoDelete() throws Exception { - final String TEST_NAME = "test109AutzLetoDelete"; // GIVEN cleanupAutzTest(null); @@ -565,7 +558,6 @@ public void test109AutzLetoDelete() throws Exception { */ @Test public void test110AutzLetoAddOrgs() throws Exception { - final String TEST_NAME = "test110AutzLetoAddOrgs"; // GIVEN cleanupAutzTest(null); @@ -619,7 +611,6 @@ public void test110AutzLetoAddOrgs() throws Exception { */ @Test public void test112AutzLetoProtectTenant() throws Exception { - final String TEST_NAME = "test112AutzLetoProtectTenant"; // GIVEN cleanupAutzTest(null); @@ -688,7 +679,6 @@ public void test112AutzLetoProtectTenant() throws Exception { */ @Test public void test114AutzLetoKeepWithinTenant() throws Exception { - final String TEST_NAME = "test114AutzLetoKeepWithinTenant"; // GIVEN cleanupAutzTest(null); @@ -750,7 +740,6 @@ public void test114AutzLetoKeepWithinTenant() throws Exception { */ @Test public void test116AutzLetoProtectTenantAdminRole() throws Exception { - final String TEST_NAME = "test114AutzLetoKeepWithinTenant"; // GIVEN cleanupAutzTest(null); @@ -807,7 +796,6 @@ public void test116AutzLetoProtectTenantAdminRole() throws Exception { */ @Test public void test118AutzLetoBusinessRoles() throws Exception { - final String TEST_NAME = "test118AutzLetoBusinessRoles"; // GIVEN cleanupAutzTest(null); @@ -846,7 +834,6 @@ public void test118AutzLetoBusinessRoles() throws Exception { */ @Test public void test120AutzPaulEndUser() throws Exception { - final String TEST_NAME = "test120AutzPaulEndUser"; // GIVEN cleanupAutzTest(null); @@ -881,7 +868,6 @@ public void test120AutzPaulEndUser() throws Exception { @Test public void test122AutzDuncanRoleManager() throws Exception { - final String TEST_NAME = "test122AutzDuncanRoleManager"; // GIVEN cleanupAutzTest(null); @@ -930,7 +916,6 @@ public void test122AutzDuncanRoleManager() throws Exception { */ @Test public void test130AutzEdricRead() throws Exception { - final String TEST_NAME = "test120AutzEdricRead"; // GIVEN cleanupAutzTest(null); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java index 93c14b2ce37..babb347fcd9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java @@ -20,13 +20,11 @@ import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationPhaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -39,7 +37,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010GetUserAdministrator() throws Exception { - final String TEST_NAME = "test010GetUserAdministrator"; resetAuthentication(); // WHEN @@ -56,7 +53,6 @@ public void test010GetUserAdministrator() throws Exception { @Test public void test050GetUserJack() throws Exception { - final String TEST_NAME = "test050GetUserJack"; resetAuthentication(); // WHEN @@ -75,7 +71,6 @@ public void test050GetUserJack() throws Exception { @Test public void test051GetUserBarbossa() throws Exception { - final String TEST_NAME = "test051GetUserBarbossa"; resetAuthentication(); // WHEN @@ -97,7 +92,6 @@ public void test051GetUserBarbossa() throws Exception { @Test public void test052GetUserGuybrush() throws Exception { - final String TEST_NAME = "test052GetUserGuybrush"; resetAuthentication(); // WHEN @@ -118,7 +112,6 @@ public void test052GetUserGuybrush() throws Exception { @Test public void test060GuybrushConditionalRoleFalse() throws Exception { - final String TEST_NAME = "test060GuybrushConditionalRoleFalse"; login(USER_ADMINISTRATOR_USERNAME); assignRole(USER_GUYBRUSH_OID, ROLE_CONDITIONAL_OID); @@ -145,7 +138,6 @@ public void test060GuybrushConditionalRoleFalse() throws Exception { @Test public void test061GuybrushConditionalRoleTrue() throws Exception { - final String TEST_NAME = "test061GuybrushConditionalRoleTrue"; login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -176,7 +168,6 @@ public void test061GuybrushConditionalRoleTrue() throws Exception { @Test public void test062GuybrushConditionalRoleUnassign() throws Exception { - final String TEST_NAME = "test062GuybrushConditionalRoleUnassign"; login(USER_ADMINISTRATOR_USERNAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CONDITIONAL_OID); @@ -201,7 +192,6 @@ public void test062GuybrushConditionalRoleUnassign() throws Exception { @Test public void test100JackRolePirate() throws Exception { - final String TEST_NAME = "test100JackRolePirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -234,7 +224,6 @@ public void test100JackRolePirate() throws Exception { @Test public void test109JackUnassignRolePirate() throws Exception { - final String TEST_NAME = "test109JackUnassignRolePirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -264,7 +253,6 @@ public void test109JackUnassignRolePirate() throws Exception { @Test public void test110GuybrushRoleNicePirate() throws Exception { - final String TEST_NAME = "test110GuybrushRoleNicePirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -288,7 +276,6 @@ public void test110GuybrushRoleNicePirate() throws Exception { @Test public void test111GuybrushRoleCaptain() throws Exception { - final String TEST_NAME = "test111GuybrushRoleCaptain"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -312,7 +299,6 @@ public void test111GuybrushRoleCaptain() throws Exception { @Test public void test119GuybrushUnassignRoles() throws Exception { - final String TEST_NAME = "test119GuybrushUnassignRoles"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -339,7 +325,6 @@ public void test119GuybrushUnassignRoles() throws Exception { */ @Test public void test120JackRoleIndirectPirate() throws Exception { - final String TEST_NAME = "test120JackRoleIndirectPirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); @@ -371,7 +356,6 @@ public void test120JackRoleIndirectPirate() throws Exception { */ @Test public void test122JackOrgIndirectPirate() throws Exception { - final String TEST_NAME = "test122JackOrgIndirectPirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java index 7c09d0feabb..f3d33bd5f8c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java @@ -53,8 +53,6 @@ import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; -import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; -import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; @@ -69,10 +67,9 @@ /** * @author semancik - * */ @SuppressWarnings("SpellCheckingInspection") -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestImportRecon extends AbstractInitializedModelIntegrationTest { @@ -206,11 +203,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Create an account that midPoint does not know about yet getDummyResourceController().addAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, "Scabb Island"); getDummyResource().getAccountByUsername(USER_RAPP_USERNAME) - .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); + .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); dummyResourceCtlLime.addAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, "Scabb Island"); dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME) - .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); + .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); dummyResourceCtlLime.addAccount(ACCOUNT_RUM_NAME, "Rum Rogers"); dummyResourceCtlLime.addAccount(ACCOUNT_MURRAY_NAME, "Murray"); @@ -391,15 +388,15 @@ public void test150ImportFromResourceDummy() throws Exception { assertTask(task, "task after") .display() .synchronizationInformation() - .assertUnmatched( 1, 0) - .assertUnlinked( 1, 0) - .assertLinked( 3, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) - .end() + .assertUnmatched(1, 0) + .assertUnlinked(1, 0) + .assertLinked(3, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) + .end() .iterativeTaskInformation() - .assertTotalCounts(7, 0) - .end() + .assertTotalCounts(7, 0) + .end() .assertProgress(7); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 6); @@ -466,13 +463,13 @@ public void test155ImportFromResourceDummyAgain() throws Exception { assertTask(task, "task after") .display() .synchronizationInformation() - .assertLinked( 5, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) + .assertLinked(5, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) .end() .iterativeTaskInformation() - .assertTotalCounts(7, 0) - .end() + .assertTotalCounts(7, 0) + .end() .assertProgress(7); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 3); @@ -548,13 +545,13 @@ public void test160ImportFromResourceDummyLime() throws Exception { assertTask(task, "task after") .display() .synchronizationInformation() - .assertUnmatched( 2, 0) - .assertUnlinked( 1, 0) - .assertLinked( 0, 3) - .assertTotal(3, 3) + .assertUnmatched(2, 0) + .assertUnlinked(1, 0) + .assertLinked(0, 3) + .assertTotal(3, 3) .end() .iterativeTaskInformation() - .assertTotalCounts(3, 0) + .assertTotalCounts(3, 0) .end() .assertProgress(3); @@ -780,7 +777,6 @@ public void test200ReconcileDummy() throws Exception { // Quote is tolerant. The extra values should stay as it is guybrushDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "I want to be a pirate!"); - // Calypso is protected, this should not reconcile DummyAccount calypsoDummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); calypsoDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); @@ -807,12 +803,12 @@ public void test200ReconcileDummy() throws Exception { assertTask(taskAfter, "task after") .display() .synchronizationInformation() - .assertLinked( 5, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) + .assertLinked(5, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) .end() .iterativeTaskInformation() - .assertTotalCounts(9, 0) // protected accounts are processed also in the third stage + .assertTotalCounts(9, 0) // protected accounts are processed also in the third stage .end() .assertProgress(7); // or should be 9? @@ -1068,12 +1064,12 @@ public void test220ReconcileDummyBrokenGuybrush() throws Exception { assertTask(taskAfter, "task after") .display() .synchronizationInformation() - .assertLinked( 5, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) + .assertLinked(5, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) .end() .iterativeTaskInformation() - .assertTotalCounts(8, 1) + .assertTotalCounts(8, 1) .end() .assertProgress(7); // or should be 9? @@ -1239,14 +1235,14 @@ public void test230ReconcileDummyRename() throws Exception { assertTask(taskAfter, "task after") .display() .synchronizationInformation() - .assertUnmatched(1, 0) - .assertLinked( 4, 5) - .assertDeleted(1, 1) - .assertProtected( 2, 2) - .assertTotal(8, 8) + .assertUnmatched(1, 0) + .assertLinked(4, 5) + .assertDeleted(1, 1) + .assertProtected(2, 2) + .assertTotal(8, 8) .end() .iterativeTaskInformation() - .assertTotalCounts(10, 0) + .assertTotalCounts(10, 0) .end() .assertProgress(8); // or should be 10? @@ -1263,7 +1259,7 @@ public void test230ReconcileDummyRename() throws Exception { assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); // not deleted. reaction=unlink assertRepoShadow(hermanShadowOid) - .assertTombstone(); + .assertTombstone(); assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); @@ -1396,7 +1392,6 @@ public void test300ReconcileDummyAzureAddAccountOtis() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - assertEquals("Unexpected number of users", getNumberOfUsers() + 5, users.size()); display("Dummy resource (azure)", dummyResourceAzure.debugDump()); @@ -1446,7 +1441,6 @@ public void test310ReconcileDummyAzureAgain() throws Exception { assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - // Otis assertNoImporterUserByUsername(ACCOUNT_OTIS_NAME); assertDummyAccount(RESOURCE_DUMMY_AZURE_NAME, ACCOUNT_OTIS_NAME, ACCOUNT_OTIS_FULLNAME, false); @@ -1528,7 +1522,7 @@ public void test320ReconcileDummyAzureDeleteOtis() throws Exception { "Calypso"); assertRepoShadow(otisShadow.getOid()) - .assertTombstone(); + .assertTombstone(); assertShadows(17); @@ -1546,8 +1540,6 @@ public void test320ReconcileDummyAzureDeleteOtis() throws Exception { */ @Test public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { - final String TEST_NAME = "test330ReconcileDummyAzureAddAccountRapp"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1598,7 +1590,7 @@ public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The crew of The Elaine"); - //Checking password policy + //Checking password policy PrismObject userRapp = findUserByUsername(USER_RAPP_USERNAME); assertNotNull("No user Rapp", userRapp); UserType userTypeRapp = userRapp.asObjectable(); @@ -1615,13 +1607,13 @@ public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { } assertNotNull("No clear text password", stringPassword); - assertTrue("Rapp's password is supposed to contain letter a: "+stringPassword, stringPassword.contains("a")); - + assertTrue("Rapp's password is supposed to contain letter a: " + stringPassword, stringPassword.contains("a")); PrismObject passwordPolicy = getObjectViaRepo(ValuePolicyType.class, PASSWORD_POLICY_LOWER_CASE_ALPHA_AZURE.oid); - boolean isPasswordValid = valuePolicyProcessor.validateValue(stringPassword, passwordPolicy.asObjectable(), - createUserOriginResolver(userRapp), TEST_NAME, task, result); + boolean isPasswordValid = valuePolicyProcessor.validateValue( + stringPassword, passwordPolicy.asObjectable(), + createUserOriginResolver(userRapp), getTestNameShort(), task, result); assertTrue("Password doesn't satisfy password policy, generated password: " + stringPassword, isPasswordValid); // These are protected accounts, they should not be imported @@ -1662,7 +1654,7 @@ public void test332ModifyUserRappAndReconcileDummyAzure() throws Exception { ObjectDelta userRappDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_RAPP_OID, - UserType.F_ORGANIZATIONAL_UNIT, createPolyString("The six feet under crew")); + UserType.F_ORGANIZATIONAL_UNIT, createPolyString("The six feet under crew")); repositoryService.modifyObject(UserType.class, USER_RAPP_OID, userRappDelta.getModifications(), result); userRappBefore = getUser(USER_RAPP_OID); @@ -1792,7 +1784,6 @@ public void test334AssignRoleCorpseToRappAndReconcileDummyAzure() throws Excepti assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE.oid); } - @Test public void test339ReconcileDummyAzureDeleteRapp() throws Exception { // GIVEN @@ -1856,7 +1847,7 @@ public void test339ReconcileDummyAzureDeleteRapp() throws Exception { "Calypso"); assertRepoShadow(rappShadow.getOid()) - .assertTombstone(); + .assertTombstone(); assertShadows(19); @@ -1868,7 +1859,6 @@ public void test339ReconcileDummyAzureDeleteRapp() throws Exception { assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE.oid); } - @Test public void test400ReconcileDummyLimeAddAccount() throws Exception { // GIVEN @@ -1968,7 +1958,6 @@ public void test401ReconcileDummyLimeKateOnlyEmpty() throws Exception { display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - @Test public void test402ReconcileDummyLimeKateOnlyGrog() throws Exception { // GIVEN @@ -2580,7 +2569,7 @@ public void test610SearchDummyAccountsNameSubstring() throws Exception { ObjectQueryUtil.createResourceAndObjectClassFilterPrefix(RESOURCE_DUMMY_OID, DUMMY_ACCOUNT_OBJECT_CLASS, prismContext) .and().item(ItemPath.create(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME), ObjectFactory.createResourceAttributeDefinition(SchemaConstants.ICFS_NAME, DOMUtil.XSD_STRING, prismContext)) - .contains("s") + .contains("s") .build(); // WHEN @@ -2608,7 +2597,7 @@ public void test900DeleteDummyShadows() throws Exception { dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - // WHEN + // WHEN when(); importObjectFromFile(TASK_DELETE_DUMMY_SHADOWS.file); @@ -2633,7 +2622,7 @@ public void test900DeleteDummyShadows() throws Exception { OperationResult opExecResult = opExecResults.get(0); TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 18, opExecResult.getCount()); - assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); + assertTrue("Too many subresults: " + deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); assertUsers(getNumberOfUsers() + 12); @@ -2677,7 +2666,7 @@ public void test910DeleteDummyAccounts() throws Exception { OperationResult opExecResult = opExecResults.get(0); TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 15, opExecResult.getCount()); - assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); + assertTrue("Too many subresults: " + deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); assertUsers(getNumberOfUsers() + 12); @@ -2692,7 +2681,7 @@ private void assertDummyAccountShadows(int expected, boolean raw, Task task, Ope final MutableInt count = new MutableInt(0); ResultHandler handler = (shadow, parentResult) -> { count.increment(); - display("Found",shadow); + display("Found", shadow); return true; }; Collection> options = null; @@ -2700,7 +2689,7 @@ private void assertDummyAccountShadows(int expected, boolean raw, Task task, Ope options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); } modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result); - assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue()); + assertEquals("Unexpected number of search results (raw=" + raw + ")", expected, count.getValue()); } private void assertImportAuditModifications(int expectedModifications) { @@ -2708,26 +2697,26 @@ private void assertImportAuditModifications(int expectedModifications) { List auditRecords = dummyAuditService.getRecords(); - int i=0; + int i = 0; int modifications = 0; - for (; i < (auditRecords.size() - 1); i+=2) { + for (; i < (auditRecords.size() - 1); i += 2) { AuditEventRecord requestRecord = auditRecords.get(i); - assertNotNull("No request audit record ("+i+")", requestRecord); - assertEquals("Got this instead of request audit record ("+i+"): "+requestRecord, AuditEventStage.REQUEST, requestRecord.getEventStage()); + assertNotNull("No request audit record (" + i + ")", requestRecord); + assertEquals("Got this instead of request audit record (" + i + "): " + requestRecord, AuditEventStage.REQUEST, requestRecord.getEventStage()); Collection> requestDeltas = requestRecord.getDeltas(); - assertTrue("Unexpected delta in request audit record "+requestRecord, requestDeltas == null || + assertTrue("Unexpected delta in request audit record " + requestRecord, requestDeltas == null || requestDeltas.isEmpty() || (requestDeltas.size() == 1 && requestDeltas.iterator().next().getObjectDelta().isAdd())); - AuditEventRecord executionRecord = auditRecords.get(i+1); - assertNotNull("No execution audit record ("+i+")", executionRecord); - assertEquals("Got this instead of execution audit record ("+i+"): "+executionRecord, AuditEventStage.EXECUTION, executionRecord.getEventStage()); + AuditEventRecord executionRecord = auditRecords.get(i + 1); + assertNotNull("No execution audit record (" + i + ")", executionRecord); + assertEquals("Got this instead of execution audit record (" + i + "): " + executionRecord, AuditEventStage.EXECUTION, executionRecord.getEventStage()); - assertTrue("Empty deltas in execution audit record "+executionRecord, executionRecord.getDeltas() != null && ! executionRecord.getDeltas().isEmpty()); + assertTrue("Empty deltas in execution audit record " + executionRecord, executionRecord.getDeltas() != null && !executionRecord.getDeltas().isEmpty()); modifications++; // check next records while (i < (auditRecords.size() - 2)) { - AuditEventRecord nextRecord = auditRecords.get(i+2); + AuditEventRecord nextRecord = auditRecords.get(i + 2); if (nextRecord.getEventStage() == AuditEventStage.EXECUTION) { // more than one execution record is OK i++; @@ -2749,7 +2738,7 @@ private void assertReconAuditModifications(int expectedModifications, String tas // Record from some other task, skip it auditRecords.removeIf(record -> record.getTaskOid() != null && !record.getTaskOid().equals(taskOid)); - int i=0; + int i = 0; while (i < (auditRecords.size() - 1)) { AuditEventRecord reconStartRecord = auditRecords.get(i); if (reconStartRecord.getEventType() == AuditEventType.EXECUTE_CHANGES_RAW) { @@ -2757,9 +2746,9 @@ private void assertReconAuditModifications(int expectedModifications, String tas continue; } assertNotNull("No reconStartRecord audit record", reconStartRecord); - assertEquals("Wrong stage in reconStartRecord audit record: "+reconStartRecord, AuditEventStage.REQUEST, reconStartRecord.getEventStage()); - assertEquals("Wrong type in reconStartRecord audit record: "+reconStartRecord, AuditEventType.RECONCILIATION, reconStartRecord.getEventType()); - assertTrue("Unexpected delta in reconStartRecord audit record "+reconStartRecord, reconStartRecord.getDeltas() == null || reconStartRecord.getDeltas().isEmpty()); + assertEquals("Wrong stage in reconStartRecord audit record: " + reconStartRecord, AuditEventStage.REQUEST, reconStartRecord.getEventStage()); + assertEquals("Wrong type in reconStartRecord audit record: " + reconStartRecord, AuditEventType.RECONCILIATION, reconStartRecord.getEventType()); + assertTrue("Unexpected delta in reconStartRecord audit record " + reconStartRecord, reconStartRecord.getDeltas() == null || reconStartRecord.getDeltas().isEmpty()); i++; break; } @@ -2767,7 +2756,7 @@ private void assertReconAuditModifications(int expectedModifications, String tas int modifications = 0; for (; i < (auditRecords.size() - 1); ) { AuditEventRecord record = auditRecords.get(i); - assertNotNull("No request audit record ("+i+")", record); + assertNotNull("No request audit record (" + i + ")", record); i++; if (record.getEventStage() == AuditEventStage.EXECUTION && record.getEventType() == AuditEventType.RECONCILIATION) { @@ -2790,25 +2779,25 @@ record = auditRecords.get(i); AuditEventRecord reconStopRecord = auditRecords.get(i); assertNotNull("No reconStopRecord audit record", reconStopRecord); - assertEquals("Wrong stage in reconStopRecord audit record: "+reconStopRecord, AuditEventStage.EXECUTION, reconStopRecord.getEventStage()); - assertEquals("Wrong type in reconStopRecord audit record: "+reconStopRecord, AuditEventType.RECONCILIATION, reconStopRecord.getEventType()); - assertTrue("Unexpected delta in reconStopRecord audit record "+reconStopRecord, reconStopRecord.getDeltas() == null || reconStopRecord.getDeltas().isEmpty()); + assertEquals("Wrong stage in reconStopRecord audit record: " + reconStopRecord, AuditEventStage.EXECUTION, reconStopRecord.getEventStage()); + assertEquals("Wrong type in reconStopRecord audit record: " + reconStopRecord, AuditEventType.RECONCILIATION, reconStopRecord.getEventType()); + assertTrue("Unexpected delta in reconStopRecord audit record " + reconStopRecord, reconStopRecord.getDeltas() == null || reconStopRecord.getDeltas().isEmpty()); } private void assertNoImporterUserByUsername(String username) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(username); - assertNull("User "+username+" sneaked in", user); + assertNull("User " + username + " sneaked in", user); } private void assertImportedUserByOid(String userOid, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); - assertNotNull("No user "+userOid, user); + assertNotNull("No user " + userOid, user); assertImportedUser(user, resourceOids); } private PrismObject assertImportedUserByUsername(String username, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(username); - assertNotNull("No user "+username, user); + assertNotNull("No user " + username, user); assertImportedUser(user, resourceOids); return user; } @@ -2816,7 +2805,7 @@ private PrismObject assertImportedUserByUsername(String username, Stri private void assertImportedUser(PrismObject user, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("Imported user", user); assertLinks(user, resourceOids.length); - for (String resourceOid: resourceOids) { + for (String resourceOid : resourceOids) { assertAccount(user, resourceOid); } assertAdministrativeStatusEnabled(user); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java index 12889136655..aa8dd916ef3 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java @@ -194,8 +194,6 @@ protected PrismObject getDefaultActor() { @Test public void test001Sanity() throws Exception { - final String TEST_NAME = "test001Sanity"; - display("Dummy resource azure", dummyResourceSteelBlue); // WHEN @@ -212,8 +210,6 @@ public void test001Sanity() throws Exception { @Test public void test002SanityRefined() throws Exception { - final String TEST_NAME = "test002SanityRefined"; - // WHEN RefinedResourceSchema refinedSchemaSteelBlue = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelBlueType, prismContext); RefinedResourceSchema refinedSchemaSteelGrey = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelGreyType, prismContext); @@ -228,8 +224,6 @@ public void test002SanityRefined() throws Exception { @Test public void test100Synchronize() throws Exception { - final String TEST_NAME = "test100Synchronize"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java index c17274ea029..13fbd6f945f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java @@ -164,8 +164,6 @@ protected PrismObject getDefaultActor() { @Test public void test001SanityAzure() throws Exception { - final String TEST_NAME = "test001SanityAzure"; - display("Dummy resource azure", dummyResourceSteelBlue); // WHEN @@ -179,8 +177,6 @@ public void test001SanityAzure() throws Exception { @Test public void test002SanityAzureRefined() throws Exception { - final String TEST_NAME = "test002SanityAzureRefined"; - // WHEN RefinedResourceSchema refinedSchemaAzure = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelBlueType, prismContext); @@ -192,8 +188,6 @@ public void test002SanityAzureRefined() throws Exception { @Test public void test100Synchronize() throws Exception { - final String TEST_NAME = "test100Synchronize"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java index 2fe18ec720d..6ccb2337a2e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java @@ -9,18 +9,12 @@ import static org.testng.AssertJUnit.assertEquals; import java.io.File; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.security.api.MidPointPrincipal; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -29,27 +23,29 @@ import com.evolveum.midpoint.model.impl.trigger.RecomputeTriggerHandler; import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.model.intest.TestActivation; -import com.evolveum.midpoint.model.intest.TestTriggerTask; -import com.evolveum.midpoint.model.intest.mapping.TestMapping; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DebugUtil; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author Radovan Semancik - * * @see TestActivation - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestValidityRecomputeTask extends AbstractInitializedModelIntegrationTest { @@ -82,16 +78,11 @@ protected String getValidityScannerTaskFileName() { @Test public void test100ImportValidityScannerTask() throws Exception { - final String TEST_NAME = "test100ImportValidityScannerTask"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - // Pretend that the user was added a long time ago clock.override(LONG_LONG_TIME_AGO); addObject(USER_HERMAN_FILE); - // Make sure that it is effectivelly disabled + // Make sure that it is effectively disabled PrismObject userHermanBefore = getUser(USER_HERMAN_OID); assertEffectiveActivation(userHermanBefore, ActivationStatusType.DISABLED); assertValidityStatus(userHermanBefore, TimeIntervalStatusType.BEFORE); @@ -118,8 +109,6 @@ public void test100ImportValidityScannerTask() throws Exception { @Test public void test110JackAssignJudgeDisabled() throws Exception { - final String TEST_NAME = "test110JackAssignJudgeDisabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -127,45 +116,39 @@ public void test110JackAssignJudgeDisabled() throws Exception { ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.DISABLED); - testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeInvalid(activationType, task, result); } @Test public void test111JackAssignJudgeNotYetValid() throws Exception { - final String TEST_NAME = "test111JackAssignJudgeNotYetValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); - validFrom.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validFrom.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead activationType.setValidFrom(validFrom); - testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeInvalid(activationType, task, result); } @Test public void test112JackAssignJudgeAfterValidity() throws Exception { - final String TEST_NAME = "test112JackAssignJudgeAfterValidity"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago + validTo.add(XmlTypeConverter.createDuration(-60 * 60 * 1000)); // one hour ago activationType.setValidTo(validTo); - testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeInvalid(activationType, task, result); } @Test public void test115JackAssignJudgeEnabled() throws Exception { - final String TEST_NAME = "test115JackAssignJudgeEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -173,29 +156,28 @@ public void test115JackAssignJudgeEnabled() throws Exception { ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - testJackAssignRoleJudgeValid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeValid(activationType, task, result); } @Test public void test115JackAssignJudgeValid() throws Exception { - final String TEST_NAME = "test115JackAssignJudgeValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); - validFrom.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago + validFrom.add(XmlTypeConverter.createDuration(-60 * 60 * 1000)); // one hour ago activationType.setValidFrom(validFrom); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validTo.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead activationType.setValidTo(validTo); - testJackAssignRoleJudgeValid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeValid(activationType, task, result); } - private void testJackAssignRoleJudgeValid(final String TEST_NAME, ActivationType activationType, Task task, OperationResult result) throws Exception { + private void testJackAssignRoleJudgeValid( + ActivationType activationType, Task task, OperationResult result) throws Exception { // WHEN when(); @@ -227,7 +209,8 @@ private void testJackAssignRoleJudgeValid(final String TEST_NAME, ActivationType assertNoDummyAccount(null, USER_JACK_USERNAME); } - private void testJackAssignRoleJudgeInvalid(final String TEST_NAME, ActivationType activationType, Task task, OperationResult result) throws Exception { + private void testJackAssignRoleJudgeInvalid( + ActivationType activationType, Task task, OperationResult result) throws Exception { // WHEN when(); @@ -264,11 +247,8 @@ private void assert11xUserOk(PrismObject user) { assertEffectiveActivation(user, ActivationStatusType.ENABLED); } - @Test public void test120JackDisableAssignmentJudge() throws Exception { - final String TEST_NAME = "test120JackDisableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -298,8 +278,6 @@ public void test120JackDisableAssignmentJudge() throws Exception { @Test public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws Exception { - final String TEST_NAME = "test122JackReplaceNullAdministrativeStatusAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -322,8 +300,6 @@ public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws E @Test public void test123JackDisableAssignmentJudge() throws Exception { - final String TEST_NAME = "test123JackDisableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -346,8 +322,6 @@ public void test123JackDisableAssignmentJudge() throws Exception { @Test public void test124JackEnableAssignmentJudge() throws Exception { - final String TEST_NAME = "test124JackEnableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -370,8 +344,6 @@ public void test124JackEnableAssignmentJudge() throws Exception { @Test public void test125JackDeleteAdministrativeStatusAssignmentJudge() throws Exception { - final String TEST_NAME = "test125JackDeleteAdministrativeStatusAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -396,8 +368,6 @@ public void test125JackDeleteAdministrativeStatusAssignmentJudge() throws Except @Test public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception { - final String TEST_NAME = "test126JackAddAdministrativeStatusAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -422,8 +392,6 @@ public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception @Test public void test127JackDeleteActivationAssignmentJudge() throws Exception { - final String TEST_NAME = "test127JackDeleteActivationAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -449,8 +417,6 @@ public void test127JackDeleteActivationAssignmentJudge() throws Exception { @Test public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { - final String TEST_NAME = "test128JackAssignmentJudgeValidToSetInvalid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -459,7 +425,7 @@ public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago + validTo.add(XmlTypeConverter.createDuration(-60 * 60 * 1000)); // one hour ago activationType.setValidTo(validTo); // WHEN @@ -478,8 +444,6 @@ public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { @Test public void test129JackAssignmentJudgeValidToSetValid() throws Exception { - final String TEST_NAME = "test129JackAssignmentJudgeValidToSetValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -487,7 +451,7 @@ public void test129JackAssignmentJudgeValidToSetValid() throws Exception { assertNoDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validTo.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead // WHEN when(); @@ -520,8 +484,6 @@ private AssignmentType getJudgeAssignment(String userOid) throws ObjectNotFoundE */ @Test public void test130BarbossaAssignJudgeEnabled() throws Exception { - final String TEST_NAME = "test130BarbossaAssignJudgeEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -565,8 +527,6 @@ public void test130BarbossaAssignJudgeEnabled() throws Exception { @Test public void test131BarbossaAssignSailorEnabled() throws Exception { - final String TEST_NAME = "test131BarbossaAssignSailorEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -606,8 +566,6 @@ public void test131BarbossaAssignSailorEnabled() throws Exception { @Test public void test132BarbossaDisableAssignmentJudge() throws Exception { - final String TEST_NAME = "test132BarbossaDisableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -646,8 +604,6 @@ public void test132BarbossaDisableAssignmentJudge() throws Exception { @Test public void test133BarbossaDisableAssignmentSailor() throws Exception { - final String TEST_NAME = "test133BarbossaDisableAssignmentSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -681,8 +637,6 @@ public void test133BarbossaDisableAssignmentSailor() throws Exception { @Test public void test134BarbossaEnableAssignmentJudge() throws Exception { - final String TEST_NAME = "test134BarbossaEnableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -718,8 +672,6 @@ public void test134BarbossaEnableAssignmentJudge() throws Exception { @Test public void test135BarbossaEnableAssignmentSailor() throws Exception { - final String TEST_NAME = "test135BarbossaEnableAssignmentSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -755,8 +707,6 @@ public void test135BarbossaEnableAssignmentSailor() throws Exception { @Test public void test136BarbossaDisableBothAssignments() throws Exception { - final String TEST_NAME = "test136BarbossaDisableBothAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -771,8 +721,8 @@ public void test136BarbossaDisableBothAssignments() throws Exception { AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create(UserType.F_ASSIGNMENT, sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); // WHEN when(); @@ -800,8 +750,6 @@ public void test136BarbossaDisableBothAssignments() throws Exception { @Test public void test137BarbossaEnableBothAssignments() throws Exception { - final String TEST_NAME = "test137BarbossaEnableBothAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -819,11 +767,11 @@ public void test137BarbossaEnableBothAssignments() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.ENABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.ENABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.ENABLED); // WHEN when(); @@ -860,8 +808,6 @@ public void test137BarbossaEnableBothAssignments() throws Exception { */ @Test public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { - final String TEST_NAME = "test139BarbossaDisableBothAssignmentsUnassign"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -883,11 +829,11 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); @@ -939,8 +885,6 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { */ @Test public void test140BarbossaAssignRedJudgeEnabled() throws Exception { - final String TEST_NAME = "test140BarbossaAssignRedJudgeEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -988,8 +932,6 @@ public void test140BarbossaAssignRedJudgeEnabled() throws Exception { @Test public void test141BarbossaAssignRedSailorEnabled() throws Exception { - final String TEST_NAME = "test141BarbossaAssignRedSailorEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1029,8 +971,6 @@ public void test141BarbossaAssignRedSailorEnabled() throws Exception { @Test public void test142BarbossaDisableAssignmentRedJudge() throws Exception { - final String TEST_NAME = "test142BarbossaDisableAssignmentRedJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1069,8 +1009,6 @@ public void test142BarbossaDisableAssignmentRedJudge() throws Exception { @Test public void test143BarbossaDisableAssignmentRedSailor() throws Exception { - final String TEST_NAME = "test143BarbossaDisableAssignmentRedSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1108,8 +1046,6 @@ public void test143BarbossaDisableAssignmentRedSailor() throws Exception { @Test public void test144BarbossaEnableAssignmentRedJudge() throws Exception { - final String TEST_NAME = "test144BarbossaEnableAssignmentRedJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1145,8 +1081,6 @@ public void test144BarbossaEnableAssignmentRedJudge() throws Exception { @Test public void test145BarbossaEnableAssignmentRedSailor() throws Exception { - final String TEST_NAME = "test145BarbossaEnableAssignmentRedSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1182,8 +1116,6 @@ public void test145BarbossaEnableAssignmentRedSailor() throws Exception { @Test public void test146BarbossaDisableBothRedAssignments() throws Exception { - final String TEST_NAME = "test146BarbossaDisableBothRedAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1201,11 +1133,11 @@ public void test146BarbossaDisableBothRedAssignments() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); // WHEN when(); @@ -1237,8 +1169,6 @@ public void test146BarbossaDisableBothRedAssignments() throws Exception { @Test public void test147BarbossaEnableBothRedAssignments() throws Exception { - final String TEST_NAME = "test147BarbossaEnableBothRedAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1256,11 +1186,11 @@ public void test147BarbossaEnableBothRedAssignments() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.ENABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.ENABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.ENABLED); // WHEN when(); @@ -1297,8 +1227,6 @@ public void test147BarbossaEnableBothRedAssignments() throws Exception { */ @Test public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception { - final String TEST_NAME = "test149BarbossaDisableBothRedAssignmentsUnassign"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1317,11 +1245,11 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); @@ -1373,15 +1301,9 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - @Test public void test190HermanGoesInvalid() throws Exception { - final String TEST_NAME = "test190HermanGoesInvalid"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); PrismObject userHermanBefore = getUser(USER_HERMAN_OID); @@ -1413,9 +1335,6 @@ public void test190HermanGoesInvalid() throws Exception { @Test public void test200ImportTriggerScannerTask() throws Exception { // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); /// WHEN @@ -1439,10 +1358,8 @@ public void test200ImportTriggerScannerTask() throws Exception { */ @Test public void test205AccountRedElaineDisable() throws Exception { - final String TEST_NAME = "test205AccountRedElaineDisable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -1464,10 +1381,8 @@ public void test205AccountRedElaineDisable() throws Exception { */ @Test public void test210JackAssignAndUnassignAccountRed() throws Exception { - final String TEST_NAME = "test210JackAssignAndUnassignAccountRed"; - // GIVEN - Task task = taskManager.createTaskInstance(TestMapping.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // assign @@ -1521,12 +1436,7 @@ public void test210JackAssignAndUnassignAccountRed() throws Exception { */ @Test public void test215JackDummyAccountDeleteAfterMonth() throws Exception { - final String TEST_NAME = "test215JackDummyAccountDeleteAfterMonth"; - // GIVEN - Task task = taskManager.createTaskInstance(TestMapping.class.getName() + "." + TEST_NAME); - OperationResult result = task.getResult(); - XMLGregorianCalendar time = clock.currentTimeXMLGregorianCalendar(); // A month and a day, to make sure we move past the trigger time.add(XmlTypeConverter.createDuration(true, 0, 1, 1, 0, 0, 0)); @@ -1545,8 +1455,6 @@ public void test215JackDummyAccountDeleteAfterMonth() throws Exception { @Test public void test220AddDrake() throws Exception { - final String TEST_NAME = "test220AddDrake"; - XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); display("Start", start); @@ -1610,8 +1518,6 @@ public void test220AddDrake() throws Exception { @Test public void test222Drake4DaysBeforeValidFrom() throws Exception { - final String TEST_NAME = "test222Drake4DaysBeforeValidFrom"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidFrom.clone(); start.add(XmlTypeConverter.createDuration(false, 0, 0, 4, 0, 0, 0)); clock.override(start); @@ -1637,8 +1543,6 @@ public void test222Drake4DaysBeforeValidFrom() throws Exception { @Test public void test224Drake1DaysAfterValidFrom() throws Exception { - final String TEST_NAME = "test224Drake1DaysAfterValidFrom"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidFrom.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 1, 0, 0, 0)); clock.override(start); @@ -1663,8 +1567,6 @@ public void test224Drake1DaysAfterValidFrom() throws Exception { @Test public void test226Drake1DayBeforeValidTo() throws Exception { - final String TEST_NAME = "test226Drake1DayBeforeValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(false, 0, 0, 1, 0, 0, 0)); clock.override(start); @@ -1689,8 +1591,6 @@ public void test226Drake1DayBeforeValidTo() throws Exception { @Test public void test228Drake1DayAfterValidTo() throws Exception { - final String TEST_NAME = "test228Drake1DayAfterValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 1, 0, 0, 0)); clock.override(start); @@ -1716,8 +1616,6 @@ public void test228Drake1DayAfterValidTo() throws Exception { @Test public void test230Drake20DaysAfterValidTo() throws Exception { - final String TEST_NAME = "test230Drake20DaysAfterValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 20, 0, 0, 0)); clock.override(start); @@ -1743,8 +1641,6 @@ public void test230Drake20DaysAfterValidTo() throws Exception { @Test public void test232Drake40DaysAfterValidTo() throws Exception { - final String TEST_NAME = "test232Drake40DaysAfterValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 40, 0, 0, 0)); clock.override(start); @@ -1771,8 +1667,6 @@ public void test232Drake40DaysAfterValidTo() throws Exception { */ @Test public void test250CheckAccountRedElaine() throws Exception { - final String TEST_NAME = "test250CheckAccountRedElaine"; - // GIVEN // WHEN @@ -1789,18 +1683,16 @@ public void test250CheckAccountRedElaine() throws Exception { @Test public void test300HermanAssignJudgeNotYetValid() throws Exception { - final String TEST_NAME = "test300HermanAssignJudgeNotYetValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); judgeAssignmentValidFrom = clock.currentTimeXMLGregorianCalendar(); - judgeAssignmentValidFrom.add(XmlTypeConverter.createDuration(10*60*1000)); // 10 minutes ahead + judgeAssignmentValidFrom.add(XmlTypeConverter.createDuration(10 * 60 * 1000)); // 10 minutes ahead activationType.setValidFrom(judgeAssignmentValidFrom); judgeAssignmentValidTo = clock.currentTimeXMLGregorianCalendar(); - judgeAssignmentValidTo.add(XmlTypeConverter.createDuration(30*60*1000)); // 30 minutes ahead + judgeAssignmentValidTo.add(XmlTypeConverter.createDuration(30 * 60 * 1000)); // 30 minutes ahead activationType.setValidTo(judgeAssignmentValidTo); display("Assignment validFrom", judgeAssignmentValidFrom); display("Assignment validTo", judgeAssignmentValidTo); @@ -1816,12 +1708,7 @@ public void test300HermanAssignJudgeNotYetValid() throws Exception { @Test public void test310HermanAssignJudgeBecomesValid() throws Exception { - final String TEST_NAME = "test310HermanAssignJudgeBecomesValid"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - PrismObject user = getUser(USER_HERMAN_OID); display("User before", user); XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidFrom.clone(); @@ -1833,19 +1720,14 @@ public void test310HermanAssignJudgeBecomesValid() throws Exception { // just wait waitForValidityNextRunAssertSuccess(); - assertRoleJudgeValid(TEST_NAME, task, result); + assertRoleJudgeValid(); } @Test public void test315HermanAssignJudgeBecomesInValid() throws Exception { - final String TEST_NAME = "test315HermanAssignJudgeBecomesInValid"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidTo.clone(); - start.add(XmlTypeConverter.createDuration(1*60*1000)); + start.add(XmlTypeConverter.createDuration(Duration.ofMinutes(1).toMillis())); clock.override(start); display("Start", start); @@ -1853,17 +1735,17 @@ public void test315HermanAssignJudgeBecomesInValid() throws Exception { // just wait waitForValidityNextRunAssertSuccess(); - assertRoleJudgeInValid(TEST_NAME, task, result); + assertRoleJudgeInValid(); } - private void assertRoleJudgeValid(final String TEST_NAME, Task task, OperationResult result) throws Exception { + private void assertRoleJudgeValid() throws Exception { assertDummyAccount(null, USER_HERMAN_USERNAME); PrismObject user = getUser(USER_HERMAN_OID); display("User after", user); assertLinks(user, 1); } - private void assertRoleJudgeInValid(final String TEST_NAME, Task task, OperationResult result) throws Exception { + private void assertRoleJudgeInValid() throws Exception { assertNoDummyAccount(null, USER_HERMAN_USERNAME); PrismObject user = getUser(USER_HERMAN_OID); display("User after", user); @@ -1881,12 +1763,12 @@ private void modifyAssignmentAdministrativeStatus(String userOid, long assignmen task, result); } else { modifyObjectReplaceProperty(UserType.class, userOid, - ItemPath.create( - UserType.F_ASSIGNMENT, - assignmentId, - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - task, result, status); + ItemPath.create( + UserType.F_ASSIGNMENT, + assignmentId, + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + task, result, status); } } diff --git a/model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml b/model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml new file mode 100644 index 00000000000..3ddb2fd3ffd --- /dev/null +++ b/model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml @@ -0,0 +1,47 @@ + + + + User Template 6045 + + + strong + + name + + + + + + assignment + + + + + + + + + + + + + diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index f59698c360b..8684b46f894 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -146,12 +146,6 @@ public abstract class AbstractModelIntegrationTest extends AbstractIntegrationTe protected static final String CONNECTOR_DUMMY_VERSION = "2.0"; protected static final String CONNECTOR_DUMMY_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector"; - protected static final String CONNECTOR_LDAP_TYPE = "com.evolveum.polygon.connector.ldap.LdapConnector"; - protected static final String CONNECTOR_LDAP_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector"; - - protected static final String CONNECTOR_AD_TYPE = "Org.IdentityConnectors.ActiveDirectory.ActiveDirectoryConnector"; - protected static final String CONNECTOR_AD_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/ActiveDirectory.Connector/Org.IdentityConnectors.ActiveDirectory.ActiveDirectoryConnector"; - protected static final ItemPath ACTIVATION_ADMINISTRATIVE_STATUS_PATH = SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; protected static final ItemPath ACTIVATION_VALID_FROM_PATH = SchemaConstants.PATH_ACTIVATION_VALID_FROM; protected static final ItemPath ACTIVATION_VALID_TO_PATH = SchemaConstants.PATH_ACTIVATION_VALID_TO; @@ -475,7 +469,6 @@ protected void searchObjectsIterative(Class type, Task task = createPlainTask("searchObjectsIterative"); OperationResult result = task.getResult(); final MutableInt count = new MutableInt(0); - // Cannot convert to lambda here. Java does not want to understand the generic types properly. SearchResultMetadata searchMetadata = modelService.searchObjectsIterative(type, query, (object, oresult) -> { count.increment(); if (handler != null) { @@ -493,7 +486,8 @@ protected void assertUserProperty(String userOid, QName propertyName, Object... assertUserProperty(user, propertyName, expectedPropValues); } - protected void assertUserNoProperty(String userOid, QName propertyName) throws ObjectNotFoundException, SchemaException { + protected void assertUserNoProperty(String userOid, QName propertyName) + throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("getObject"); PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertUserNoProperty(user, propertyName); @@ -584,7 +578,8 @@ protected void modifyObjectAddProperty(Class type, Str modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectReplaceContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) + protected void modifyObjectReplaceContainer( + Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -593,7 +588,8 @@ protected void modifyObjectRepla modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectAddContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) + protected void modifyObjectAddContainer( + Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -602,7 +598,8 @@ protected void modifyObjectAddCo modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectDeleteContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) + protected void modifyObjectDeleteContainer( + Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -611,7 +608,8 @@ protected void modifyObjectDelet modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectReplaceReference(Class type, String oid, ItemPath refPath, Task task, OperationResult result, PrismReferenceValue... refVals) + protected void modifyObjectReplaceReference( + Class type, String oid, ItemPath refPath, Task task, OperationResult result, PrismReferenceValue... refVals) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -647,7 +645,8 @@ protected void modifyAccountShadowReplace(String accountOid, ItemPath propertyPa modelService.executeChanges(deltas, null, task, result); } - protected ObjectDelta createOldNewPasswordDelta(String oid, String oldPassword, String newPassword) throws SchemaException { + protected ObjectDelta createOldNewPasswordDelta( + String oid, String oldPassword, String newPassword) throws SchemaException { ProtectedStringType oldPasswordPs = new ProtectedStringType(); oldPasswordPs.setClearValue(oldPassword); @@ -794,8 +793,10 @@ protected void assignRole(Class focusClass, Stri modifyAssignmentHolderAssignment(focusClass, focusOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, result); } - protected void assignService(Class focusClass, String focusOid, String targetOid, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, - SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + protected void assignService(Class focusClass, String focusOid, + String targetOid, ActivationType activationType, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyAssignmentHolderAssignment(focusClass, focusOid, targetOid, ServiceType.COMPLEX_TYPE, null, task, null, activationType, true, result); } @@ -806,8 +807,11 @@ protected void assignRole(Class focusClass, String focusOid modifyAssignmentHolderAssignment(focusClass, focusOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, options, result); } - protected void assignFocus(Class focusClass, String focusOid, QName targetType, String targetOid, QName relation, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, - SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + protected void assignFocus(Class focusClass, + String focusOid, QName targetType, String targetOid, QName relation, + ActivationType activationType, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyAssignmentHolderAssignment(focusClass, focusOid, targetOid, targetType, relation, task, null, activationType, true, result); } @@ -1044,7 +1048,7 @@ protected void assignOrg(Class focusType, String focusO throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { - modifyFocusAssignment(focusType, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, (Consumer) null, true, result); + modifyFocusAssignment(focusType, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, null, true, result); } protected void unassignOrg(String userOid, String orgOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1080,7 +1084,7 @@ protected void unassignOrg(Class type, String focusOid, throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { - modifyFocusAssignment(type, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, (Consumer) null, false, result); + modifyFocusAssignment(type, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, null, false, result); } protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, @@ -1230,7 +1234,7 @@ protected void unassignAll(PrismObject focusBefore, Tas /** * Creates unassign delta by removing each assignment individually by id. */ - protected ObjectDelta createUnassignAllDelta(PrismObject focusBefore) throws SchemaException { + protected ObjectDelta createUnassignAllDelta(PrismObject focusBefore) { Collection> modifications = new ArrayList<>(); for (AssignmentType assignmentType : focusBefore.asObjectable().getAssignment()) { modifications.add((createAssignmentModification(assignmentType.getId(), false))); @@ -1378,7 +1382,8 @@ protected ObjectDelta createAssignmentFocusD return prismContext.deltaFactory().object().createModifyDelta(focusOid, modifications, focusClass); } - protected ObjectDelta createAssignmentFocusEmptyDeleteDelta(PrismObject existingFocus, String roleOid, QName relation) throws SchemaException { + protected ObjectDelta createAssignmentFocusEmptyDeleteDelta( + PrismObject existingFocus, String roleOid, QName relation) { Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentEmptyDeleteModification(existingFocus, roleOid, relation))); return prismContext.deltaFactory().object().createModifyDelta( @@ -5971,10 +5976,7 @@ protected ShadowAsserter assertModelShadow(String oid) throws ObjectNotFou protected ShadowAsserter assertModelShadowNoFetch(String oid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject repoShadow = getShadowModelNoFetch(oid); - ShadowAsserter asserter = ShadowAsserter.forShadow(repoShadow, "model(noFetch)"); - asserter - .display(); - return asserter; + return ShadowAsserter.forShadow(repoShadow, "model(noFetch)").display(); } protected ShadowAsserter assertModelShadowFuture(String oid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -6179,12 +6181,9 @@ protected SearchResultList> assertSearch(C try { logAttempt("searchIterative", type, query); final List> iterativeObjects = new ArrayList<>(); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject object, OperationResult parentResult) { - iterativeObjects.add(object); - return true; - } + ResultHandler handler = (object, parentResult) -> { + iterativeObjects.add(object); + return true; }; modelService.searchObjectsIterative(type, query, handler, options, task, result); display("Search iterative returned", iterativeObjects.toString()); diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java index 5dcc5ea2f9e..844c2e693bf 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java @@ -93,11 +93,6 @@ public String getName() { return "dummy"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java index f28b7430d5e..42d4b51a57f 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java @@ -154,11 +154,6 @@ public String toString() { return sb.toString(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder rv = new StringBuilder(); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java index afaf9a04aa2..c5b7ca4b6b9 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java @@ -138,6 +138,6 @@ protected Trace getLogger() { protected String getContentType() { return "text/html"; - }; + } } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java index c2ec57ee205..d44a030386d 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java @@ -264,7 +264,7 @@ private Object getVariableValue(String name, Mode mode) { } } - enum Mode { DEFAULT, OLD, ESTIMATED }; + enum Mode { DEFAULT, OLD, ESTIMATED } // NOT USED diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java index 1a3d9be1c5f..ff91897d09b 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java @@ -67,8 +67,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ReportUserList() throws Exception { - final String TEST_NAME = "test100ReportUserList"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -98,8 +96,7 @@ public void test100ReportUserList() throws Exception { */ @Test public void test110ReportUserListExpressionsCsv() throws Exception { - final String TEST_NAME = "test110ReportUserListExpressionsCsv"; - testReportListUsersCsv(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_CSV_OID); + testReportListUsersCsv(REPORT_USER_LIST_EXPRESSIONS_CSV_OID); } /** @@ -109,8 +106,7 @@ public void test110ReportUserListExpressionsCsv() throws Exception { */ @Test public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception { - final String TEST_NAME = "test112ReportUserListExpressionsPoisonousQueryCsv"; - testReportListUsersCsv(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); + testReportListUsersCsv(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); } /** @@ -120,14 +116,11 @@ public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception */ @Test public void test114ReportUserListExpressionsPoisonousFieldCsv() throws Exception { - final String TEST_NAME = "test114ReportUserListExpressionsPoisonousFieldCsv"; - testReportListUsersCsv(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); + testReportListUsersCsv(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); } @Test public void test200ReportUserListScript() throws Exception { - final String TEST_NAME = "test200ReportUserListScript"; - if (!isOsUnix()) { displaySkip(); return; @@ -165,37 +158,35 @@ public void test200ReportUserListScript() throws Exception { */ @Test public void test300ReportAuditLegacy() throws Exception { - final String TEST_NAME = "test300ReportAuditLegacy"; - testReportAuditCsvSuccess(TEST_NAME, REPORT_AUDIT_CSV_LEGACY_OID); + testReportAuditCsvSuccess(REPORT_AUDIT_CSV_LEGACY_OID); } @Test public void test310ReportAudit() throws Exception { - final String TEST_NAME = "test310ReportAudit"; - testReportAuditCsvSuccess(TEST_NAME, REPORT_AUDIT_CSV_OID); + testReportAuditCsvSuccess(REPORT_AUDIT_CSV_OID); } - protected void testReportListUsersCsv(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportListUsersCsv(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, false); + PrismObject finishedTask = runReport(report, false); assertSuccess("Finished report task result", finishedTask.asObjectable().getResult()); checkCsvUserReport(report); } - protected void testReportListUsersCsvFailure(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportListUsersCsvFailure(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, true); + PrismObject finishedTask = runReport(report, true); assertFailure("Finished report task result", finishedTask.asObjectable().getResult()); assertNoCsvReport(report); } - protected PrismObject runReport(final String TEST_NAME, PrismObject report, boolean errorOk) throws Exception { + protected PrismObject runReport(PrismObject report, boolean errorOk) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -234,34 +225,34 @@ protected void checkCsvUserReport(PrismObject report) throws IOExcep assertEquals("Unexpected number of report lines", currentUsers.size() + 1, lines.size()); } - protected void assertNoCsvReport(PrismObject report) throws IOException, SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertNoCsvReport(PrismObject report) { File outputFile = findOutputFile(report); display("Found report file (expected null)", outputFile); assertNull("Unexpected output file for "+report+": "+outputFile, outputFile); } - protected void testReportAuditCsvSuccess(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportAuditCsvSuccess(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, false); + PrismObject finishedTask = runReport(report, false); assertSuccess("Report task result", finishedTask.asObjectable().getResult()); checkCsvAuditReport(report); } - protected void testReportAuditCsvFailure(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportAuditCsvFailure(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, true); + PrismObject finishedTask = runReport(report, true); assertFailure("Finished report task result", finishedTask.asObjectable().getResult()); assertNoCsvReport(report); } - protected void checkCsvAuditReport(PrismObject report) throws IOException, SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void checkCsvAuditReport(PrismObject report) throws IOException { File outputFile = findOutputFile(report); display("Found report file", outputFile); assertNotNull("No output file for "+report, outputFile); diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java index f353f37c08c..8c784a2029f 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java @@ -41,8 +41,7 @@ protected File getSystemConfigurationFile() { @Test @Override public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception { - final String TEST_NAME = "test110ReportUserListExpressionsCsv"; - testReportListUsersCsvFailure(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); + testReportListUsersCsvFailure(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); } /** @@ -52,8 +51,7 @@ public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception */ @Test public void test114ReportUserListExpressionsPoisonousFieldCsv() throws Exception { - final String TEST_NAME = "test114ReportUserListExpressionsPoisonousFieldCsv"; - testReportListUsersCsvFailure(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); + testReportListUsersCsvFailure(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); } /** @@ -62,8 +60,6 @@ public void test114ReportUserListExpressionsPoisonousFieldCsv() throws Exception */ @Test public void test300ReportAuditLegacy() throws Exception { - final String TEST_NAME = "test300ReportAuditLegacy"; - testReportAuditCsvFailure(TEST_NAME, REPORT_AUDIT_CSV_LEGACY_OID); + testReportAuditCsvFailure(REPORT_AUDIT_CSV_LEGACY_OID); } - } diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java index 0b22a72d490..b2ef7806060 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java @@ -21,12 +21,7 @@ import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -60,16 +55,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @Test - public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - + public void test000Sanity() { assertNotNull("No web service", reportWebService); } @Test public void test100ProcessReportUserList() throws Exception { - final String TEST_NAME = "test100ProcessReportUserList"; - String query = createAllQueryString(UserType.class); RemoteReportParametersType parameters = createReportParameters(); @@ -79,15 +70,13 @@ public void test100ProcessReportUserList() throws Exception { // THEN then(); - display("Returned user list ("+userList.getObject().size()+" objects)", userList); + display("Returned user list (" + userList.getObject().size() + " objects)", userList); assertUserList(userList); } @Test - public void test110ProcessReportUserListNoReportOid() throws Exception { - final String TEST_NAME = "test110ProcessReportUserListNoReportOid"; - + public void test110ProcessReportUserListNoReportOid() { String query = createAllQueryString(UserType.class); RemoteReportParametersType parameters = createReportParameters(); @@ -107,9 +96,7 @@ public void test110ProcessReportUserListNoReportOid() throws Exception { } @Test - public void test112ProcessReportUserListInvalidReportOid() throws Exception { - final String TEST_NAME = "test112ProcessReportUserListInvalidReportOid"; - + public void test112ProcessReportUserListInvalidReportOid() { String query = createAllQueryString(UserType.class); RemoteReportParametersType parameters = createReportParameters(); @@ -133,8 +120,6 @@ public void test112ProcessReportUserListInvalidReportOid() throws Exception { */ @Test public void test115ProcessReportUserListUnauthorizedReader() throws Exception { - final String TEST_NAME = "test115ProcessReportUserListUnauthorizedReader"; - login(USER_READER_USERNAME); String query = createAllQueryString(UserType.class); @@ -162,8 +147,6 @@ public void test115ProcessReportUserListUnauthorizedReader() throws Exception { */ @Test public void test116ProcessReportUserListUnauthorizedRunner() throws Exception { - final String TEST_NAME = "test116ProcessReportUserListUnauthorizedRunner"; - login(USER_RUNNER_USERNAME); String query = createAllQueryString(UserType.class); @@ -191,8 +174,6 @@ public void test116ProcessReportUserListUnauthorizedRunner() throws Exception { */ @Test public void test119ProcessReportUserListReaderRunner() throws Exception { - final String TEST_NAME = "test119ProcessReportUserListReaderRunner"; - login(USER_READER_RUNNER_USERNAME); String query = createAllQueryString(UserType.class); @@ -211,7 +192,7 @@ public void test119ProcessReportUserListReaderRunner() throws Exception { // THEN then(); - display("Returned user list ("+userList.getObject().size()+" objects)", userList); + display("Returned user list (" + userList.getObject().size() + " objects)", userList); assertUserList(userList); } @@ -219,22 +200,20 @@ public void test119ProcessReportUserListReaderRunner() throws Exception { // TODO: test that violates safe profile private String createAllQueryString(Class type) { - return ""+type.getSimpleName()+""; + return "" + type.getSimpleName() + ""; } private RemoteReportParametersType createReportParameters() { - RemoteReportParametersType parameters = new RemoteReportParametersType(); - return parameters; + return new RemoteReportParametersType(); } private void assertUserList(ObjectListType userList) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = getTestTask(); OperationResult result = task.getResult(); SearchResultList> currentUsers = modelService.searchObjects(UserType.class, null, null, task, result); - display("Current users in midPoint ("+currentUsers.size()+" users)", currentUsers.toString()); + display("Current users in midPoint (" + currentUsers.size() + " users)", currentUsers.toString()); assertEquals("Unexpected number of returned objects", currentUsers.size(), userList.getObject().size()); } - } diff --git a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java index 292490644e9..b7860937bb4 100644 --- a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java +++ b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java @@ -148,11 +148,6 @@ public String toString() { '}'; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java index a963dfcfa32..df698bd1210 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java @@ -303,9 +303,7 @@ boolean decideOnApproval(CaseType subcase, */ @Test public void test100AddJackToGuests() throws Exception { - final String TEST_NAME = "test100AddJackToGuests"; - - Task modelTask = taskManager.createTaskInstance(TEST_NAME); + Task modelTask = getTestTask(); OperationResult result = createOperationResult(); modelTask.setOwner(repositoryService.getObject(UserType.class, USER_ADMINISTRATOR_OID, null, result)); @@ -362,7 +360,7 @@ void assertsAfterImmediateExecutionFinished(CaseType task, OperationResult resul void assertsRootCaseFinishes(CaseType aCase, List subcases, Task opTask, OperationResult result) throws Exception { } boolean decideOnApproval(CaseType subcase, ApprovalContextType wfContext) throws Exception { return true; } - String getObjectOid(CaseType task, OperationResult result) throws SchemaException { return null; }; + String getObjectOid(CaseType task, OperationResult result) throws SchemaException { return null; } boolean removeAssignmentsBeforeTest() { return true; } } diff --git a/pom.xml b/pom.xml index 5cf468d864b..cc25cc12407 100644 --- a/pom.xml +++ b/pom.xml @@ -41,10 +41,15 @@ Extra test run with custom JVM args (we have 16g on CI server, but it works without args too), runs just under 900 tests, skips distribution and any common unit/IT tests (~1h50m): mvn clean install -P extratest,-dist -Dsurefire.args="-Xmx8g" -Dfailsafe.args="-Xmx8g -Duser.language=en" + (Skipping of default tests is managed by "extratest" profile.) Extra test run for a single module, -D property matches the module in -pl: mvn clean install -DskipConnTests=false -pl testing/conntest + Running a single IT test class in one module from the "extra" set with output to stdout: + mvn integration-test -DskipConnTests=false -DredirectTestOutputToFile=false -pl testing/conntest -Dit.test=TestAdLdapChimera + Note usage of "it.test" property (for failsafe), not just "test" (for surefire). + Full build with extra tests for a single module, "-DskipTests" suppresses other default tests: mvn clean install -P -dist -DskipTests -DskipStoryTests=false See "extratest" profile in testing/pom.xml for all individual properties enabling extra tests. @@ -141,7 +146,6 @@ 2.6 2.6 - 3.7 1.2 3.3.1 3.3.0 @@ -562,11 +566,6 @@ commons-lang ${commons.lang.version} - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - commons-pool commons-pool diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java index 2b7a62476aa..0384546e40c 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java @@ -77,14 +77,6 @@ public String toString() { + ")"; } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java index f022a30eae7..aeecae5d4c2 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java @@ -165,14 +165,6 @@ public String toString() { + ", resource=" + resource + (unrelatedChange ? " UNRELATED" : "") + (simulate ? " SIMULATE" : "") + (cleanDeadShadow ? " CLEAN DEAD SHADOW" : "") + ")"; } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java index 2fc68a04e73..9847705d877 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java @@ -145,14 +145,6 @@ public String toString() { ", result=" + result + ")"; } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java index 8f960e70d5d..c05a354644c 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java @@ -39,7 +39,6 @@ import com.evolveum.midpoint.prism.Objectable; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.crypto.EncryptionException; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; @@ -107,8 +106,6 @@ public class ProvisioningServiceImpl implements ProvisioningService, SystemConfi @Qualifier("cacheRepositoryService") private RepositoryService cacheRepositoryService; - private PrismObjectDefinition resourceObjectShadowDefinition; - private SystemConfigurationType systemConfiguration; private static final Trace LOGGER = TraceManager.getTrace(ProvisioningServiceImpl.class); @@ -269,7 +266,7 @@ public String addObject(PrismObject object, OperationP result.addArbitraryObjectAsParam("scripts", scripts); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - String oid = null; + String oid; if (object.canRepresent(ShadowType.class)) { try { // calling shadow cache to add object @@ -491,7 +488,7 @@ private SearchResultList> searchRepoObject // TODO: what else do to with objResult?? - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) { + } catch (ObjectNotFoundException | SchemaException | ExpressionEvaluationException e) { LOGGER.error("Error while completing {}: {}-{}. Using non-complete object.", repoObject, e.getMessage(), e); objResult.recordFatalError(e); repoObject.asObjectable().setFetchResult(objResult.createOperationResultType()); @@ -518,8 +515,8 @@ private SearchResultList> searchRepoObject // TODO: move to ResourceManager and ConnectorManager // the shadow-related code is already in the ShadowCache - private PrismObject completeObject(Class type, PrismObject inObject, - Collection> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private PrismObject completeObject( + Class type, PrismObject inObject, Collection> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { if (ResourceType.class.equals(type)) { //noinspection unchecked @@ -530,7 +527,6 @@ private PrismObject completeObject(Class type, Pris throw new IllegalStateException("BOOOM!"); } else { //TODO: connectors etc.. - } return inObject; } @@ -551,7 +547,7 @@ public Integer countObjects(Class type, ObjectQuery qu LOGGER.trace("Start of counting objects. Query:\n{}", query != null ? query.debugDump(1) : " (null)"); } - if (filter != null && filter instanceof NoneFilter) { + if (filter instanceof NoneFilter) { result.recordSuccessIfUnknown(); result.cleanupResult(); LOGGER.trace("Finished counting. Nothing to do. Filter is NONE"); @@ -570,11 +566,9 @@ public Integer countObjects(Class type, ObjectQuery qu Integer count; try { - count = shadowCache.countObjects(query, task, result); result.computeStatus(); - } catch (ConfigurationException | CommunicationException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; @@ -704,7 +698,7 @@ public PrismObject deleteObject(Class type, String ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: security violation: " + e.getMessage(), e); throw e; } catch (ExpressionEvaluationException e) { - ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: expression errror: " + e.getMessage(), e); + ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: expression error: " + e.getMessage(), e); throw e; } catch (PolicyViolationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: " + e.getMessage(), e); @@ -743,9 +737,8 @@ public PrismObject deleteObject(Class type, String * @see com.evolveum.midpoint.provisioning.api.ProvisioningService#executeScript(java.lang.Class, java.lang.String, com.evolveum.midpoint.xml.ns._public.common.common_3.ProvisioningScriptType, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @Override - public Object executeScript(String resourceOid, ProvisioningScriptType script, - Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, - CommunicationException, ConfigurationException, ExpressionEvaluationException { + public Object executeScript(String resourceOid, ProvisioningScriptType script, Task task, OperationResult parentResult) + throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Validate.notNull(resourceOid, "Oid of object for script execution must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); @@ -1118,11 +1111,6 @@ public void applyDefinition(PrismObject object, Task t } } - private void setProtectedShadow(PrismObject shdaow, OperationResult result) - throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - shadowCache.setProtectedShadow(shdaow, result); - } - @Override public void applyDefinition(Class type, ObjectQuery query, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -1252,14 +1240,6 @@ public void exitConstraintsCheckerCache() { ConstraintsChecker.exitCache(); } - private PrismObjectDefinition getResourceObjectShadowDefinition() { - if (resourceObjectShadowDefinition == null) { - resourceObjectShadowDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass( - ShadowType.class); - } - return resourceObjectShadowDefinition; - } - private PrismObject getRepoObject(Class type, String oid, Collection> options, OperationResult result) throws ObjectNotFoundException, SchemaException { diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java index 1dfd1151287..1cb8bfc36d0 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java @@ -77,7 +77,7 @@ public class ProvisioningUtil { private static final QName FAKE_SCRIPT_ARGUMENT_NAME = new QName(SchemaConstants.NS_C, "arg"); public static final Duration DEFAULT_OPERATION_RETRY_PERIOD_DURATION = XmlTypeConverter.createDuration("PT30M"); public static final int DEFAULT_OPERATION_RETRY_MAX_ATTEMPTS = 3; - private static final Duration DEFAULT_PENDING_OPERATION_RETENTION_PERIOD_DURATION = XmlTypeConverter.createDuration("P1D");; + private static final Duration DEFAULT_PENDING_OPERATION_RETENTION_PERIOD_DURATION = XmlTypeConverter.createDuration("P1D"); public static final Duration DEFAULT_DEAD_SHADOW_RETENTION_PERIOD_DURATION = XmlTypeConverter.createDuration("P7D"); private static final Trace LOGGER = TraceManager.getTrace(ProvisioningUtil.class); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java index d0c04781bff..f9a7383bbcb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java @@ -47,9 +47,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test001Connectors() throws Exception { - final String TEST_NAME = "test001Connectors"; - - OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN when(); @@ -91,9 +89,7 @@ public void testListConnectors() throws Exception { @Test public void testSearchConnectorSimple() throws SchemaException { - final String TEST_NAME = "testSearchConnectorSimple"; - OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); PrismObject ldapConnector = findConnectorByType(IntegrationTestTools.LDAP_CONNECTOR_TYPE, result); assertEquals("Type does not match", IntegrationTestTools.LDAP_CONNECTOR_TYPE, ldapConnector.asObjectable().getConnectorType()); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java index c75e77340c4..e571352b298 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java @@ -6,20 +6,16 @@ */ package com.evolveum.midpoint.provisioning.impl; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.util.Collection; -import com.evolveum.midpoint.prism.util.PrismAsserts; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; -import com.evolveum.midpoint.provisioning.api.ProvisioningService; +import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorFactory; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; @@ -34,7 +30,6 @@ public class TestConnectorManager extends AbstractIntegrationTest { private static final String CONNID_FRAMEWORK_VERSION = "1.5.0.10"; - @Autowired private ProvisioningService provisioningService; @Autowired private ConnectorManager connectorManager; @Override @@ -45,10 +40,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @Test - public void test100ListConnectorFactories() throws Exception { - final String TEST_NAME = "test100ListConnectorFactories"; - - OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); + public void test100ListConnectorFactories() { + OperationResult result = createOperationResult(); // WHEN when(); @@ -58,13 +51,12 @@ public void test100ListConnectorFactories() throws Exception { then(); assertNotNull("Null connector factories", connectorFactories); assertFalse("No connector factories found", connectorFactories.isEmpty()); - display("Found "+connectorFactories.size()+" connector factories"); + display("Found " + connectorFactories.size() + " connector factories"); assertSuccess(result); - for (ConnectorFactory connectorFactory : connectorFactories) { - display("Found connector factory " +connectorFactory, connectorFactory); + display("Found connector factory " + connectorFactory, connectorFactory); } PrismAsserts.assertEqualsUnordered("Wrong connector factories", @@ -74,10 +66,8 @@ public void test100ListConnectorFactories() throws Exception { } @Test - public void test110SelfTest() throws Exception { - final String TEST_NAME = "test100ListConnectorFactories"; - - Task task = taskManager.createTaskInstance(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); + public void test110SelfTest() { + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -90,15 +80,11 @@ public void test110SelfTest() throws Exception { } @Test - public void test120FrameworkVersion() throws Exception { - final String TEST_NAME = "test120FrameworkVersion"; - + public void test120FrameworkVersion() { // WHEN String frameworkVersion = connectorManager.getFrameworkVersion(); // THEN assertEquals("Unexpected framework version", CONNID_FRAMEWORK_VERSION, frameworkVersion); - } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java index cb21b2a2aae..5a2120dec17 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java @@ -123,10 +123,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test101AddAccountWithoutName() throws Exception { - final String TEST_NAME = "test101AddAccountWithoutName"; // GIVEN - Task syncTask = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + Task syncTask = getTestTask(); + OperationResult result = syncTask.getResult(); syncServiceMock.reset(); ShadowType account = parseObjectType(ACCOUNT_MORGAN_FILE, ShadowType.class); @@ -207,9 +206,8 @@ public void test101AddAccountWithoutName() throws Exception { */ @Test public void test107AGetModifiedAccountFromCacheMax() throws Exception { - final String TEST_NAME = "test107AGetModifiedAccountFromCacheMax"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -261,9 +259,8 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { */ @Test public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception { - final String TEST_NAME = "test107BGetModifiedAccountFromCacheHighStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -311,9 +308,8 @@ public void test107CSkipCachingForIncompleteAttributes() throws Exception { */ @Test public void test108GetAccountLowStaleness() throws Exception { - final String TEST_NAME = "test106GetModifiedAccount"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); Collection> options = @@ -367,10 +363,8 @@ public void test108GetAccountLowStaleness() throws Exception { */ @Test public void test109ModifiedAccountCleanup() throws Exception { - final String TEST_NAME = "test109ModifiedAccountCleanup"; - // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -407,10 +401,8 @@ public void test109ModifiedAccountCleanup() throws Exception { @Test public void test110SearchIterative() throws Exception { - final String TEST_NAME = "test110SeachIterative"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // Make sure there is an account on resource that the provisioning has // never seen before, so there is no shadow @@ -524,10 +516,8 @@ public boolean handle(PrismObject object, OperationResult parentResu @Test public void test111SeachIterativeNoFetch() throws Exception { - final String TEST_NAME = "test111SeachIterativeNoFetch"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), @@ -578,10 +568,8 @@ public void test111SeachIterativeNoFetch() throws Exception { @Test public void test112SeachIterativeKindIntent() throws Exception { - final String TEST_NAME = "test112SeachIterativeKindIntent"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, "default", prismContext); @@ -655,10 +643,8 @@ public void test113SearchAllShadowsInRepository() throws Exception { @Test public void test114SearchAllAccounts() throws Exception { - final String TEST_NAME = "test114SearchAllAccounts"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -685,9 +671,8 @@ public void test114SearchAllAccounts() throws Exception { @Test public void test115CountAllAccounts() throws Exception { - final String TEST_NAME = "test115CountAllAccounts"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -713,10 +698,8 @@ protected Integer getTest115ExpectedCount() { @Test public void test116SearchNullQueryResource() throws Exception { - final String TEST_NAME = "test116SearchNullQueryResource"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN List> allResources = provisioningService.searchObjects(ResourceType.class, @@ -764,10 +747,8 @@ public void test117CountNullQueryResource() throws Exception { */ @Test public void test118SearchAllAccountsLongStaleness() throws Exception { - final String TEST_NAME = "test118SearchAllAccountsLongStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -811,10 +792,8 @@ public void test118SearchAllAccountsLongStaleness() throws Exception { */ @Test public void test119SearchAllAccountsMaxStaleness() throws Exception { - final String TEST_NAME = "test119SearchAllAccountsMaxStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -854,8 +833,6 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { @Test public void test120ModifyWillReplaceFullname() throws Exception { - final String TEST_NAME = "test120ModifyWillReplaceFullname"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -885,8 +862,6 @@ public void test120ModifyWillReplaceFullname() throws Exception { @Test public void test121ModifyObjectAddPirate() throws Exception { - final String TEST_NAME = "test121ModifyObjectAddPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -919,8 +894,6 @@ public void test121ModifyObjectAddPirate() throws Exception { @Test public void test122ModifyObjectAddCaptain() throws Exception { - final String TEST_NAME = "test122ModifyObjectAddCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -953,8 +926,6 @@ public void test122ModifyObjectAddCaptain() throws Exception { @Test public void test123ModifyObjectDeletePirate() throws Exception { - final String TEST_NAME = "test123ModifyObjectDeletePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -990,8 +961,6 @@ public void test123ModifyObjectDeletePirate() throws Exception { */ @Test public void test124ModifyAccountWillAddCaptainAgain() throws Exception { - final String TEST_NAME = "test124ModifyAccountWillAddCaptainAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1026,10 +995,8 @@ public void test124ModifyAccountWillAddCaptainAgain() throws Exception { */ @Test public void test125CompareAccountWillPassword() throws Exception { - final String TEST_NAME = "test125CompareAccountWillPassword"; - - testComparePassword(TEST_NAME, "match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); - testComparePassword(TEST_NAME, "mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); + testComparePassword("match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); + testComparePassword("mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); assertSteadyResource(); } @@ -1039,8 +1006,6 @@ public void test125CompareAccountWillPassword() throws Exception { */ @Test public void test126ModifyAccountWillPassword() throws Exception { - final String TEST_NAME = "test126ModifyAccountWillPassword"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1081,16 +1046,15 @@ public void test126ModifyAccountWillPassword() throws Exception { */ @Test public void test127CompareAccountWillPassword() throws Exception { - final String TEST_NAME = "test125CompareAccountWillPassword"; - - testComparePassword(TEST_NAME, "match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); - testComparePassword(TEST_NAME, "mismatch old password", ACCOUNT_WILL_OID, ACCOUNT_WILL_PASSWORD, getExpectedPasswordComparisonResultMismatch()); - testComparePassword(TEST_NAME, "mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); + testComparePassword("match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); + testComparePassword("mismatch old password", ACCOUNT_WILL_OID, ACCOUNT_WILL_PASSWORD, getExpectedPasswordComparisonResultMismatch()); + testComparePassword("mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); assertSteadyResource(); } - protected void testComparePassword(final String TEST_NAME, String tag, String shadowOid, String expectedPassword, ItemComparisonResult expectedResult) throws Exception { + protected void testComparePassword(String tag, String shadowOid, + String expectedPassword, ItemComparisonResult expectedResult) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1115,8 +1079,6 @@ protected void testComparePassword(final String TEST_NAME, String tag, String sh */ @Test public void test129NullAttributeValue() throws Exception { - final String TEST_NAME = "test129NullAttributeValue"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1143,10 +1105,8 @@ public void test129NullAttributeValue() throws Exception { @Test public void test131AddScript() throws Exception { - final String TEST_NAME = "test131AddScript"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1241,10 +1201,8 @@ public void test132ModifyScript() throws Exception { */ @Test public void test133ModifyScriptNoExec() throws Exception { - final String TEST_NAME = "test133ModifyScriptNoExec"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1282,10 +1240,8 @@ public void test133ModifyScriptNoExec() throws Exception { @Test public void test134DeleteScript() throws Exception { - final String TEST_NAME = "test134DeleteScript"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1318,10 +1274,8 @@ public void test134DeleteScript() throws Exception { @Test public void test135ExecuteScript() throws Exception { - final String TEST_NAME = "test135ExecuteScript"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1348,10 +1302,8 @@ public void test135ExecuteScript() throws Exception { @Test public void test150DisableAccount() throws Exception { - final String TEST_NAME = "test150DisableAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1392,10 +1344,8 @@ public void test150DisableAccount() throws Exception { @Test public void test151SearchDisabledAccounts() throws Exception { - final String TEST_NAME = "test151SearchDisabledAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1424,10 +1374,8 @@ public void test151SearchDisabledAccounts() throws Exception { @Test public void test152ActivationStatusUndefinedAccount() throws Exception { - final String TEST_NAME = "test152ActivationStatusUndefinedAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1460,8 +1408,8 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); - assertEquals("Wrong dummy account " + transformNameFromResource(ACCOUNT_WILL_USERNAME) + " enabled flag", - null, dummyAccount.isEnabled()); + assertNull("Wrong dummy account " + transformNameFromResource(ACCOUNT_WILL_USERNAME) + " enabled flag", + dummyAccount.isEnabled()); syncServiceMock.assertNotifySuccessOnly(); @@ -1470,10 +1418,8 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { @Test public void test154EnableAccount() throws Exception { - final String TEST_NAME = "test154EnableAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1482,7 +1428,7 @@ public void test154EnableAccount() throws Exception { display("Retrieved account shadow", accountType); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); - assertEquals("Wrong dummy account enabled flag", null, dummyAccount.isEnabled()); + assertNull("Wrong dummy account enabled flag", dummyAccount.isEnabled()); syncServiceMock.reset(); @@ -1513,10 +1459,8 @@ public void test154EnableAccount() throws Exception { @Test public void test155SearchDisabledAccounts() throws Exception { - final String TEST_NAME = "test155SearchDisabledAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1542,10 +1486,8 @@ public void test155SearchDisabledAccounts() throws Exception { @Test public void test156SetValidFrom() throws Exception { - final String TEST_NAME = "test156SetValidFrom"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1586,10 +1528,8 @@ public void test156SetValidFrom() throws Exception { @Test public void test157SetValidTo() throws Exception { - final String TEST_NAME = "test157SetValidTo"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1633,10 +1573,8 @@ public void test157SetValidTo() throws Exception { @Test public void test158DeleteValidToValidFrom() throws Exception { - final String TEST_NAME = "test158DeleteValidToValidFrom"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1688,10 +1626,8 @@ public void test158DeleteValidToValidFrom() throws Exception { @Test public void test159GetLockedoutAccount() throws Exception { - final String TEST_NAME = "test159GetLockedoutAccount"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); dummyAccount.setLockout(true); @@ -1730,10 +1666,8 @@ public void test159GetLockedoutAccount() throws Exception { @Test public void test160SearchLockedAccounts() throws Exception { - final String TEST_NAME = "test160SearchLockedAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1762,10 +1696,8 @@ public void test160SearchLockedAccounts() throws Exception { @Test public void test162UnlockAccount() throws Exception { - final String TEST_NAME = "test162UnlockAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1807,10 +1739,8 @@ public void test162UnlockAccount() throws Exception { @Test public void test163GetAccount() throws Exception { - final String TEST_NAME = "test163GetAccount"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); @@ -1847,10 +1777,8 @@ public void test163GetAccount() throws Exception { @Test public void test163SearchLockedAccounts() throws Exception { - final String TEST_NAME = "test163SearchLockedAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1876,7 +1804,7 @@ public void test163SearchLockedAccounts() throws Exception { @Test public void test170SearchNull() throws Exception { - testSeachIterative(null, null, true, true, false, + testSearchIterative(null, null, true, true, false, "meathook", "daemon", transformNameFromResource("morgan"), transformNameFromResource("Will")); } @@ -1939,10 +1867,9 @@ SchemaConstants.ICFS_NAME, getWillRepoIcfName(), null, true, @Test public void test180SearchNullPagingOffset0Size3() throws Exception { - final String TEST_NAME = "test180SearchNullPagingSize5"; ObjectPaging paging = prismContext.queryFactory().createPaging(0, 3); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18x(0, 3)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @@ -1953,30 +1880,27 @@ public void test180SearchNullPagingOffset0Size3() throws Exception { */ @Test public void test181SearchNullPagingOffset0Size3Desc() throws Exception { - final String TEST_NAME = "test181SearchNullPagingOffset0Size3Desc"; ObjectPaging paging = prismContext.queryFactory().createPaging(0, 3); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME, OrderDirection.DESCENDING)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18xDesc(0, 3)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @Test public void test182SearchNullPagingOffset1Size2() throws Exception { - final String TEST_NAME = "test182SearchNullPagingOffset1Size2"; ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18x(1, 2)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @Test public void test183SearchNullPagingOffset2Size3Desc() throws Exception { - final String TEST_NAME = "test183SearchNullPagingOffset1Size3Desc"; ObjectPaging paging = prismContext.queryFactory().createPaging(2, 3); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME, OrderDirection.DESCENDING)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18xDesc(2, 3)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @@ -2040,7 +1964,7 @@ public void test197SearchIcfNameAndUidExactNoFetch() throws Exception { @Test public void test198SearchNone() throws Exception { ObjectFilter attrFilter = FilterCreationUtil.createNone(prismContext); - testSeachIterative(attrFilter, null, true, true, false); + testSearchIterative(attrFilter, null, true, true, false); } /** @@ -2050,10 +1974,8 @@ public void test198SearchNone() throws Exception { */ @Test public void test199SearchOnAndOffResource() throws Exception { - final String TEST_NAME = "test199SearchOnAndOffResource"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = createOnOffQuery(); @@ -2091,10 +2013,8 @@ public boolean handle(PrismObject object, OperationResult parentResu */ @Test public void test196SearchOnAndOffResourceNoFetch() throws Exception { - final String TEST_NAME = "test196SearchOnAndOffResourceNoFetch"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = createOnOffQuery(); @@ -2148,7 +2068,7 @@ protected void testSeachIterativeSingleAttrFilter(QName attrQName, T attrVal ObjectFilter filter = prismContext.queryFor(ShadowType.class) .itemWithDef(attrDef, ShadowType.F_ATTRIBUTES, attrDef.getItemName()).eq(attrVal) .buildFilter(); - testSeachIterative(filter, rootOptions, fullShadow, true, false, expectedAccountNames); + testSearchIterative(filter, rootOptions, fullShadow, true, false, expectedAccountNames); } protected void testSeachIterativeAlternativeAttrFilter(QName attr1QName, T attr1Val, @@ -2162,10 +2082,10 @@ protected void testSeachIterativeAlternativeAttrFilter(QName attr1QName, T a .itemWithDef(attr1Def, ShadowType.F_ATTRIBUTES, attr1Def.getItemName()).eq(attr1Val) .or().itemWithDef(attr2Def, ShadowType.F_ATTRIBUTES, attr2Def.getItemName()).eq(attr2Val) .buildFilter(); - testSeachIterative(filter, rootOptions, fullShadow, false, true, expectedAccountNames); + testSearchIterative(filter, rootOptions, fullShadow, false, true, expectedAccountNames); } - private SearchResultMetadata testSeachIterative( + private SearchResultMetadata testSearchIterative( ObjectFilter attrFilter, GetOperationOptions rootOptions, final boolean fullShadow, boolean useObjectClassFilter, final boolean useRepo, String... expectedAccountNames) throws Exception { @@ -2188,8 +2108,6 @@ private SearchResultMetadata testSeachIterative( display("Query", query); - final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - final List> foundObjects = new ArrayList<>(); ResultHandler handler = new ResultHandler() { @@ -2197,8 +2115,6 @@ private SearchResultMetadata testSeachIterative( public boolean handle(PrismObject shadow, OperationResult parentResult) { foundObjects.add(shadow); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - assertTrue(shadow.canRepresent(ShadowType.class)); if (!useRepo) { try { @@ -2254,9 +2170,10 @@ public boolean handle(PrismObject shadow, OperationResult parentResu // This has to be a different method than ordinary search. We care about ordering here. // Also, paged search without sorting does not make much sense anyway. - private SearchResultMetadata testSeachIterativePaging(final String TEST_NAME, ObjectFilter attrFilter, ObjectPaging paging, GetOperationOptions rootOptions, String... expectedAccountNames) throws Exception { - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + private SearchResultMetadata testSeachIterativePaging(ObjectFilter attrFilter, + ObjectPaging paging, GetOperationOptions rootOptions, String... expectedAccountNames) + throws Exception { + OperationResult result = createOperationResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext); @@ -2268,8 +2185,6 @@ private SearchResultMetadata testSeachIterativePaging(final String TEST_NAME, Ob display("Query", query); - final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - final List> foundObjects = new ArrayList<>(); ResultHandler handler = new ResultHandler() { @@ -2277,8 +2192,6 @@ private SearchResultMetadata testSeachIterativePaging(final String TEST_NAME, Ob public boolean handle(PrismObject shadow, OperationResult parentResult) { foundObjects.add(shadow); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - assertTrue(shadow.canRepresent(ShadowType.class)); try { checkAccountShadow(shadow, parentResult, true); @@ -2321,9 +2234,8 @@ public boolean handle(PrismObject shadow, OperationResult parentResu @Test public void test200AddGroup() throws Exception { - final String TEST_NAME = "test200AddGroup"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -2383,10 +2295,8 @@ public void test200AddGroup() throws Exception { @Test public void test202GetGroup() throws Exception { - final String TEST_NAME = "test202GetGroup"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2425,10 +2335,8 @@ private void checkGroupPirates(PrismObject shadow, OperationResult r @Test public void test203GetGroupNoFetch() throws Exception { - final String TEST_NAME = "test203GetGroupNoFetch"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); GetOperationOptions rootOptions = new GetOperationOptions(); rootOptions.setNoFetch(true); @@ -2459,10 +2367,7 @@ public void test203GetGroupNoFetch() throws Exception { @Test public void test205ModifyGroupReplace() throws Exception { - final String TEST_NAME = "test205ModifyGroupReplace"; - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2498,9 +2403,8 @@ public void test205ModifyGroupReplace() throws Exception { @Test public void test210AddPrivilege() throws Exception { - final String TEST_NAME = "test210AddPrivilege"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -2551,10 +2455,8 @@ public void test210AddPrivilege() throws Exception { @Test public void test212GetPriv() throws Exception { - final String TEST_NAME = "test212GetPriv"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, PRIVILEGE_PILLAGE_OID, null, null, result); @@ -2589,9 +2491,8 @@ private void checkPrivPillage(PrismObject shadow, OperationResult re @Test public void test214AddPrivilegeBargain() throws Exception { - final String TEST_NAME = "test214AddPrivilegeBargain"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -2659,9 +2560,7 @@ private void checkPrivBargain(PrismObject shadow, OperationResult re @Test public void test220EntitleAccountWillPirates() throws Exception { - final String TEST_NAME = "test220EntitleAccountWillPirates"; - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2704,10 +2603,7 @@ public void test220EntitleAccountWillPirates() throws Exception { */ @Test public void test221GetPirateWill() throws Exception { - final String TEST_NAME = "test221GetPirateWill"; - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2736,8 +2632,6 @@ public void test221GetPirateWill() throws Exception { @Test public void test222EntitleAccountWillPillage() throws Exception { - final String TEST_NAME = "test222EntitleAccountWillPillage"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2791,8 +2685,6 @@ public void test222EntitleAccountWillPillage() throws Exception { @Test public void test223EntitleAccountWillBargain() throws Exception { - final String TEST_NAME = "test223EntitleAccountWillBargain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3014,8 +2906,6 @@ public void test226WillNonsensePrivilege() throws Exception { @Test public void test230DetitleAccountWillPirates() throws Exception { - final String TEST_NAME = "test230DetitleAccountWillPirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3046,8 +2936,6 @@ public void test230DetitleAccountWillPirates() throws Exception { */ @Test public void test232EntitleAccountWillPiratesIdentifiersName() throws Exception { - final String TEST_NAME = "test232EntitleAccountWillPiratesIdentifiersName"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3078,8 +2966,6 @@ public void test232EntitleAccountWillPiratesIdentifiersName() throws Exception { */ @Test public void test233DetitleAccountWillPiratesIdentifiersName() throws Exception { - final String TEST_NAME = "test233DetitleAccountWillPiratesIdentifiersName"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3110,8 +2996,6 @@ public void test233DetitleAccountWillPiratesIdentifiersName() throws Exception { */ @Test public void test234EntitleAccountWillPiratesIdentifiersUid() throws Exception { - final String TEST_NAME = "test234EntitleAccountWillPiratesIdentifiersUid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3142,8 +3026,6 @@ public void test234EntitleAccountWillPiratesIdentifiersUid() throws Exception { */ @Test public void test235DetitleAccountWillPiratesIdentifiersUid() throws Exception { - final String TEST_NAME = "test235DetitleAccountWillPiratesIdentifiersUid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3542,8 +3424,6 @@ public void test299DeleteGroupPirates() throws Exception { @Test public void test300AccountRename() throws Exception { - final String TEST_NAME = "test300AccountRename"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3595,8 +3475,6 @@ public void test300AccountRename() throws Exception { */ @Test public void test310ModifyMorganEnlistTimestamp() throws Exception { - final String TEST_NAME = "test310ModifyMorganEnlistTimestamp"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3635,8 +3513,6 @@ public void test310ModifyMorganEnlistTimestamp() throws Exception { */ @Test public void test330ModifyAccountWillPasswordSelfService() throws Exception { - final String TEST_NAME = "test330ModifyAccountWillPasswordSelfService"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3685,8 +3561,6 @@ public void test330ModifyAccountWillPasswordSelfService() throws Exception { */ @Test public void test340ModifyWillReplaceGossipBloodAvast() throws Exception { - final String TEST_NAME = "test340ModifyWillReplaceGossipBloodAvast"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3717,8 +3591,6 @@ public void test340ModifyWillReplaceGossipBloodAvast() throws Exception { */ @Test public void test342ModifyWillAddGossipEunuch() throws Exception { - final String TEST_NAME = "test342ModifyWillAddGossipEunuch"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3749,8 +3621,6 @@ public void test342ModifyWillAddGossipEunuch() throws Exception { */ @Test public void test344ModifyWillDeleteGossipAvast() throws Exception { - final String TEST_NAME = "test344ModifyWillDeleteGossipAvast"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3822,7 +3692,6 @@ protected String getLastModifierName(String expected) { @Test public void test500AddProtectedAccount() throws Exception { - final String TEST_NAME = "test500AddProtectedAccount"; testAddProtectedAccount(ACCOUNT_DAVIEJONES_USERNAME); } @@ -3890,10 +3759,8 @@ public void test502ModifyProtectedAccountShadowAttributes() throws Exception { */ @Test public void test503ModifyProtectedAccountShadowProperty() throws Exception { - final String TEST_NAME = "test503ModifyProtectedAccountShadowProperty"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3919,7 +3786,6 @@ public void test503ModifyProtectedAccountShadowProperty() throws Exception { @Test public void test509DeleteProtectedAccountShadow() throws Exception { - final String TEST_NAME = "test509DeleteProtectedAccountShadow"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3950,7 +3816,6 @@ public void test509DeleteProtectedAccountShadow() throws Exception { @Test public void test510AddProtectedAccounts() throws Exception { - final String TEST_NAME = "test510AddProtectedAccounts"; // GIVEN testAddProtectedAccount("Xavier"); testAddProtectedAccount("Xenophobia"); @@ -4034,7 +3899,6 @@ private void testAddAccount(String username) throws Exception { */ @Test public void test520MigrationPrimaryIdentifierValueRefresh() throws Exception { - final String TEST_NAME = "test520MigrationPrimaryIdentifierValueRefresh"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -4066,10 +3930,9 @@ public void test520MigrationPrimaryIdentifierValueRefresh() throws Exception { */ @Test public void test600AddAccountAlreadyExist() throws Exception { - final String TEST_NAME = "test600AddAccountAlreadyExist"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResourceCtl.addAccount(ACCOUNT_MURRAY_USERNAME, ACCOUNT_MURRAY_USERNAME); @@ -4111,7 +3974,6 @@ public void test600AddAccountAlreadyExist() throws Exception { @Test public void test800LiveSyncInit() throws Exception { - final String TEST_NAME = "test800LiveSyncInit"; syncTokenTask = taskManager.createTaskInstance(TestDummy.class.getName() + ".syncTask"); dummyResource.setSyncStyle(DummySyncStyle.DUMB); @@ -4146,10 +4008,8 @@ public void test800LiveSyncInit() throws Exception { @Test public void test801LiveSyncAddBlackbeard() throws Exception { - final String TEST_NAME = "test801LiveSyncAddBlackbeard"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -4214,10 +4074,8 @@ public void test801LiveSyncAddBlackbeard() throws Exception { @Test public void test802LiveSyncModifyBlackbeard() throws Exception { - final String TEST_NAME = "test802LiveSyncModifyBlackbeard"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); @@ -4275,108 +4133,107 @@ public void test802LiveSyncModifyBlackbeard() throws Exception { @Test public void test810LiveSyncAddDrakeDumbObjectClass() throws Exception { - testLiveSyncAddDrake("test810LiveSyncAddDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncAddDrake(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test812LiveSyncModifyDrakeDumbObjectClass() throws Exception { - testLiveSyncModifyDrake("test812LiveSyncModifyDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncModifyDrake(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test815LiveSyncAddCorsairsDumbObjectClass() throws Exception { - testLiveSyncAddCorsairs("test815LiveSyncAddCorsairsDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncAddCorsairs(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test817LiveSyncDeleteCorsairsDumbObjectClass() throws Exception { - testLiveSyncDeleteCorsairs("test817LiveSyncDeleteCorsairsDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncDeleteCorsairs(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test819LiveSyncDeleteDrakeDumbObjectClass() throws Exception { - testLiveSyncDeleteDrake("test819LiveSyncDeleteDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncDeleteDrake(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test820LiveSyncAddDrakeSmartObjectClass() throws Exception { - testLiveSyncAddDrake("test820LiveSyncAddDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncAddDrake(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test822LiveSyncModifyDrakeSmartObjectClass() throws Exception { - testLiveSyncModifyDrake("test822LiveSyncModifyDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncModifyDrake(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test825LiveSyncAddCorsairsSmartObjectClass() throws Exception { - testLiveSyncAddCorsairs("test825LiveSyncAddCorsairsDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncAddCorsairs(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test827LiveSyncDeleteCorsairsSmartObjectClass() throws Exception { - testLiveSyncDeleteCorsairs("test827LiveSyncDeleteCorsairsDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncDeleteCorsairs(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test829LiveSyncDeleteDrakeSmartObjectClass() throws Exception { - testLiveSyncDeleteDrake("test829LiveSyncDeleteDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncDeleteDrake(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test830LiveSyncAddDrakeDumbAny() throws Exception { - testLiveSyncAddDrake("test830LiveSyncAddDrakeDumbAny", DummySyncStyle.DUMB, null); + testLiveSyncAddDrake(DummySyncStyle.DUMB, null); } @Test public void test832LiveSyncModifyDrakeDumbAny() throws Exception { - testLiveSyncModifyDrake("test832LiveSyncModifyDrakeDumbAny", DummySyncStyle.DUMB, null); + testLiveSyncModifyDrake(DummySyncStyle.DUMB, null); } @Test public void test835LiveSyncAddCorsairsDumbAny() throws Exception { - testLiveSyncAddCorsairs("test835LiveSyncAddCorsairsDumbAny", DummySyncStyle.DUMB, null, true); + testLiveSyncAddCorsairs(DummySyncStyle.DUMB, null, true); } @Test public void test837LiveSyncDeleteCorsairsDumbAny() throws Exception { - testLiveSyncDeleteCorsairs("test837LiveSyncDeleteCorsairsDumbAny", DummySyncStyle.DUMB, null, true); + testLiveSyncDeleteCorsairs(DummySyncStyle.DUMB, null, true); } @Test public void test839LiveSyncDeleteDrakeDumbAny() throws Exception { - testLiveSyncDeleteDrake("test839LiveSyncDeleteDrakeDumbAny", DummySyncStyle.DUMB, null); + testLiveSyncDeleteDrake(DummySyncStyle.DUMB, null); } @Test public void test840LiveSyncAddDrakeSmartAny() throws Exception { - testLiveSyncAddDrake("test840LiveSyncAddDrakeSmartAny", DummySyncStyle.SMART, null); + testLiveSyncAddDrake(DummySyncStyle.SMART, null); } @Test public void test842LiveSyncModifyDrakeSmartAny() throws Exception { - testLiveSyncModifyDrake("test842LiveSyncModifyDrakeSmartAny", DummySyncStyle.SMART, null); + testLiveSyncModifyDrake(DummySyncStyle.SMART, null); } @Test public void test845LiveSyncAddCorsairsSmartAny() throws Exception { - testLiveSyncAddCorsairs("test845LiveSyncAddCorsairsSmartAny", DummySyncStyle.SMART, null, true); + testLiveSyncAddCorsairs(DummySyncStyle.SMART, null, true); } @Test public void test847LiveSyncDeleteCorsairsSmartAny() throws Exception { - testLiveSyncDeleteCorsairs("test847LiveSyncDeleteCorsairsSmartAny", DummySyncStyle.SMART, null, true); + testLiveSyncDeleteCorsairs(DummySyncStyle.SMART, null, true); } @Test public void test849LiveSyncDeleteDrakeSmartAny() throws Exception { - testLiveSyncDeleteDrake("test849LiveSyncDeleteDrakeSmartAny", DummySyncStyle.SMART, null); + testLiveSyncDeleteDrake(DummySyncStyle.SMART, null); } - public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { + public void testLiveSyncAddDrake(DummySyncStyle syncStyle, QName objectClass) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4449,10 +4306,9 @@ public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyl assertSteadyResource(); } - public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { + public void testLiveSyncModifyDrake(DummySyncStyle syncStyle, QName objectClass) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4506,10 +4362,10 @@ public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncS assertSteadyResource(); } - public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { + public void testLiveSyncAddCorsairs( + DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4581,10 +4437,10 @@ public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncS assertSteadyResource(); } - public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { + public void testLiveSyncDeleteCorsairs( + DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4647,10 +4503,10 @@ public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle sy assertSteadyResource(); } - public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { + private void testLiveSyncDeleteDrake( + DummySyncStyle syncStyle, QName objectClass) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4707,9 +4563,8 @@ public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncS @Test public void test890LiveSyncModifyProtectedAccount() throws Exception { - final String TEST_NAME = "test890LiveSyncModifyProtectedAccount"; // GIVEN - Task syncTask = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task syncTask = getTestTask(); OperationResult result = syncTask.getResult(); syncServiceMock.reset(); @@ -4741,10 +4596,8 @@ public void test890LiveSyncModifyProtectedAccount() throws Exception { @Test public void test901FailResourceNotFound() throws Exception { - final String TEST_NAME = "test901FailResourceNotFound"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN try { diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java index 7d1a9fc67c0..76fadf84594 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java @@ -6,15 +6,11 @@ */ package com.evolveum.midpoint.provisioning.impl.dummy; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.Collection; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; import org.springframework.test.annotation.DirtiesContext; @@ -41,22 +37,13 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CachingMetadataType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsStorageTypeType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** * Almost the same as TestDummy but this is using a caching configuration. * * @author Radovan Semancik - * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -94,9 +81,8 @@ protected ItemComparisonResult getExpectedPasswordComparisonResultMismatch() { @Test @Override public void test107AGetModifiedAccountFromCacheMax() throws Exception { - final String TEST_NAME = "test107AGetModifiedAccountFromCacheMax"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -122,8 +108,6 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); @@ -161,9 +145,8 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { @Test @Override public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception { - final String TEST_NAME = "test107BGetModifiedAccountFromCacheHighStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -186,8 +169,6 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); @@ -222,9 +203,8 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception */ @Test public void test107CSkipCachingForIncompleteAttributes() throws Exception { - final String TEST_NAME = "test107CSkipCachingForIncompleteAttributes"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -248,8 +228,6 @@ public void test107CSkipCachingForIncompleteAttributes() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); @@ -294,10 +272,8 @@ public void test107CSkipCachingForIncompleteAttributes() throws Exception { @Test @Override public void test119SearchAllAccountsMaxStaleness() throws Exception { - final String TEST_NAME = "test119SearchAllAccountsMaxStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -322,13 +298,13 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - for (PrismObject shadow: allShadows) { + for (PrismObject shadow : allShadows) { display("Found shadow", shadow); ShadowType shadowType = shadow.asObjectable(); OperationResultType fetchResult = shadowType.getFetchResult(); if (fetchResult != null) { - display("fetchResult",fetchResult); - assertEquals("Wrong fetch result status in "+shadow, OperationResultStatusType.SUCCESS, fetchResult.getStatus()); + display("fetchResult", fetchResult); + assertEquals("Wrong fetch result status in " + shadow, OperationResultStatusType.SUCCESS, fetchResult.getStatus()); } assertCachingMetadata(shadow, true, null, startTs); @@ -361,25 +337,25 @@ protected void checkRepoAccountShadowWill(PrismObject shadowRepo, XM @Override protected void assertRepoShadowCacheActivation(PrismObject shadowRepo, ActivationStatusType expectedAdministrativeStatus) { ActivationType activationType = shadowRepo.asObjectable().getActivation(); - assertNotNull("No activation in repo shadow "+shadowRepo, activationType); + assertNotNull("No activation in repo shadow " + shadowRepo, activationType); ActivationStatusType administrativeStatus = activationType.getAdministrativeStatus(); - assertEquals("Wrong activation administrativeStatus in repo shadow "+shadowRepo, expectedAdministrativeStatus, administrativeStatus); + assertEquals("Wrong activation administrativeStatus in repo shadow " + shadowRepo, expectedAdministrativeStatus, administrativeStatus); } @Override protected void assertRepoShadowPasswordValue(PrismObject shadowRepo, PasswordType passwordType, String expectedPassword) throws SchemaException, EncryptionException { ProtectedStringType protectedStringType = passwordType.getValue(); - assertNotNull("No password value in repo shadow "+shadowRepo, protectedStringType); - assertProtectedString("Wrong password value in repo shadow "+shadowRepo, expectedPassword, protectedStringType, CredentialsStorageTypeType.HASHING); + assertNotNull("No password value in repo shadow " + shadowRepo, protectedStringType); + assertProtectedString("Wrong password value in repo shadow " + shadowRepo, expectedPassword, protectedStringType, CredentialsStorageTypeType.HASHING); } @Override protected void assertRepoCachingMetadata(PrismObject shadowFromRepo, XMLGregorianCalendar start, XMLGregorianCalendar end) { CachingMetadataType cachingMetadata = shadowFromRepo.asObjectable().getCachingMetadata(); - assertNotNull("No caching metadata in "+shadowFromRepo, cachingMetadata); + assertNotNull("No caching metadata in " + shadowFromRepo, cachingMetadata); - TestUtil.assertBetween("Wrong retrieval timestamp in caching metadata in "+shadowFromRepo, + TestUtil.assertBetween("Wrong retrieval timestamp in caching metadata in " + shadowFromRepo, start, end, cachingMetadata.getRetrievalTimestamp()); } @@ -387,14 +363,13 @@ protected void assertRepoCachingMetadata(PrismObject shadowFromRepo, protected void assertCachingMetadata(PrismObject shadow, boolean expectedCached, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) { CachingMetadataType cachingMetadata = shadow.asObjectable().getCachingMetadata(); if (expectedCached) { - assertNotNull("No caching metadata in "+shadow, cachingMetadata); - TestUtil.assertBetween("Wrong retrievalTimestamp in caching metadata in "+shadow, startTs, endTs, cachingMetadata.getRetrievalTimestamp()); + assertNotNull("No caching metadata in " + shadow, cachingMetadata); + TestUtil.assertBetween("Wrong retrievalTimestamp in caching metadata in " + shadow, startTs, endTs, cachingMetadata.getRetrievalTimestamp()); } else { super.assertCachingMetadata(shadow, expectedCached, startTs, endTs); } } - @Override protected void checkRepoAccountShadow(PrismObject repoShadow) { ProvisioningTestUtil.checkRepoShadow(repoShadow, ShadowKindType.ACCOUNT, null); @@ -406,10 +381,10 @@ protected void checkRepoEntitlementShadow(PrismObject repoShadow) { } @Override - protected void assertRepoShadowAttributes(Collection> attributes, int expectedNumberOfIdentifiers) { + protected void assertRepoShadowAttributes(Collection> attributes, int expectedNumberOfIdentifiers) { // We can only assert that there are at least the identifiers. But we do not know how many attributes should be there - assertTrue("Unexpected number of attributes in repo shadow, expected at least "+ - expectedNumberOfIdentifiers+", but was "+attributes.size(), attributes.size() >= expectedNumberOfIdentifiers); + assertTrue("Unexpected number of attributes in repo shadow, expected at least " + + expectedNumberOfIdentifiers + ", but was " + attributes.size(), attributes.size() >= expectedNumberOfIdentifiers); } @Override @@ -418,13 +393,15 @@ protected void assertSyncOldShadow(PrismObject oldShadow, } @Override - protected void assertRepoShadowCachedAttributeValue(PrismObject shadowRepo, String attrName, T... attrValues) { + protected void assertRepoShadowCachedAttributeValue( + PrismObject shadowRepo, String attrName, T... attrValues) { assertAttribute(shadowRepo, attrName, attrValues); } @Override - protected void checkCachedAccountShadow(PrismObject shadow, OperationResult parentResult, boolean fullShadow, XMLGregorianCalendar startTs, - XMLGregorianCalendar endTs) throws SchemaException { + protected void checkCachedAccountShadow( + PrismObject shadow, OperationResult parentResult, boolean fullShadow, + XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) throws SchemaException { super.checkAccountShadow(shadow, parentResult, fullShadow); if (fullShadow) { assertCachingMetadata(shadow, true, startTs, endTs); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java index efc65c67e37..fb4b2738b3e 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java @@ -105,7 +105,6 @@ public void test000Integrity() throws Exception { */ @Test public void test050AddAccountWill() throws Exception { - final String TEST_NAME = "test050AddAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -164,7 +163,6 @@ public void test050AddAccountWill() throws Exception { @Test public void test100AddAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test100AddAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -229,7 +227,6 @@ public void test102GetAccountMorganRecovery() throws Exception { */ @Test public void test104RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test104RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -260,7 +257,6 @@ public void test104RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test105GetForceRefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test105GetForceRefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -299,7 +295,6 @@ public void test105GetForceRefreshAccountMorganCommunicationFailure() throws Exc */ @Test public void test106RefreshAccountMorganCommunicationFailureRetry() throws Exception { - final String TEST_NAME = "test106RefreshAccountMorganCommunicationFailureRetry"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -338,7 +333,6 @@ public void test106RefreshAccountMorganCommunicationFailureRetry() throws Except */ @Test public void test108RefreshAccountMorganCommunicationFailureRetryAgain() throws Exception { - final String TEST_NAME = "test108RefreshAccountMorganCommunicationFailureRetryAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -465,7 +459,6 @@ private void assertMorganDead() throws Exception { */ @Test public void test109RefreshAccountMorganDead() throws Exception { - final String TEST_NAME = "test109RefreshAccountMorganDead"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -496,7 +489,6 @@ public void test109RefreshAccountMorganDead() throws Exception { */ @Test public void test110AddAccountMorganAgainCommunicationFailure() throws Exception { - final String TEST_NAME = "test110AddAccountMorganAgainCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -536,7 +528,6 @@ public void test110AddAccountMorganAgainCommunicationFailure() throws Exception */ @Test public void test114RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test114RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -569,7 +560,6 @@ public void test114RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test116RefreshAccountMorganRetrySuccess() throws Exception { - final String TEST_NAME = "test116RefreshAccountMorganRetrySuccess"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -604,8 +594,6 @@ public void test116RefreshAccountMorganRetrySuccess() throws Exception { @Test public void test120ModifyMorganFullNameCommunicationFailure() throws Exception { - final String TEST_NAME = "test120ModifyMorganFullNameCommunicationFailure"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -641,7 +629,6 @@ public void test120ModifyMorganFullNameCommunicationFailure() throws Exception { */ @Test public void test124RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test124RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -672,7 +659,6 @@ public void test124RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test126RefreshAccountMorganCommunicationFailureRetry() throws Exception { - final String TEST_NAME = "test126RefreshAccountMorganCommunicationFailureRetry"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -711,7 +697,6 @@ public void test126RefreshAccountMorganCommunicationFailureRetry() throws Except */ @Test public void test128RefreshAccountMorganCommunicationFailureRetryAgain() throws Exception { - final String TEST_NAME = "test128RefreshAccountMorganCommunicationFailureRetryAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -747,7 +732,6 @@ public void test128RefreshAccountMorganCommunicationFailureRetryAgain() throws E */ @Test public void test129RefreshAccountMorganFailed() throws Exception { - final String TEST_NAME = "test129RefreshAccountMorganFailed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -775,8 +759,6 @@ public void test129RefreshAccountMorganFailed() throws Exception { @Test public void test130ModifyMorganFullNameAgainCommunicationFailure() throws Exception { - final String TEST_NAME = "test130ModifyMorganFullNameAgainCommunicationFailure"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -813,7 +795,6 @@ public void test130ModifyMorganFullNameAgainCommunicationFailure() throws Except */ @Test public void test132GetAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test132GetAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -848,7 +829,6 @@ public void test132GetAccountMorganCommunicationFailure() throws Exception { */ @Test(enabled = false) // MID-4796 public void test133GetAccountMorganStalenessZeroCommunicationFailure() throws Exception { - final String TEST_NAME = "test133GetAccountMorganStalenessZeroCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -888,7 +868,6 @@ public void test133GetAccountMorganStalenessZeroCommunicationFailure() throws Ex */ @Test public void test134GetAccountMorganForceRefreshRetryCommunicationFailure() throws Exception { - final String TEST_NAME = "test134GetAccountMorganForceRefreshRetryCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -922,7 +901,6 @@ public void test134GetAccountMorganForceRefreshRetryCommunicationFailure() throw */ @Test public void test136RefreshAccountMorganRetrySuccess() throws Exception { - final String TEST_NAME = "test136RefreshAccountMorganRetrySuccess"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -957,8 +935,6 @@ public void test136RefreshAccountMorganRetrySuccess() throws Exception { @Test public void test170DeleteMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test170DeleteMorganCommunicationFailure"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -993,7 +969,6 @@ public void test170DeleteMorganCommunicationFailure() throws Exception { */ @Test public void test174RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test174RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1024,7 +999,6 @@ public void test174RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test176RefreshAccountMorganCommunicationFailureRetry() throws Exception { - final String TEST_NAME = "test176RefreshAccountMorganCommunicationFailureRetry"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1063,7 +1037,6 @@ public void test176RefreshAccountMorganCommunicationFailureRetry() throws Except */ @Test public void test178RefreshAccountMorganCommunicationFailureRetryAgain() throws Exception { - final String TEST_NAME = "test178RefreshAccountMorganCommunicationFailureRetryAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1098,7 +1071,6 @@ public void test178RefreshAccountMorganCommunicationFailureRetryAgain() throws E */ @Test public void test179RefreshAccountMorganFailed() throws Exception { - final String TEST_NAME = "test179RefreshAccountMorganFailed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1126,8 +1098,6 @@ public void test179RefreshAccountMorganFailed() throws Exception { @Test public void test180DeleteMorganCommunicationFailureAgain() throws Exception { - final String TEST_NAME = "test180DeleteMorganCommunicationFailureAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1163,7 +1133,6 @@ public void test180DeleteMorganCommunicationFailureAgain() throws Exception { */ @Test public void test186RefreshAccountMorganRetrySuccess() throws Exception { - final String TEST_NAME = "test186RefreshAccountMorganRetrySuccess"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1205,7 +1174,6 @@ public void test186RefreshAccountMorganRetrySuccess() throws Exception { */ @Test public void test190AccountMorganDeadExpireOperation() throws Exception { - final String TEST_NAME = "test190AccountMorganDeadExpireOperation"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1290,7 +1258,6 @@ public void test190AccountMorganDeadExpireOperation() throws Exception { */ @Test public void test192AccountMorganSecondDeadExpireOperation() throws Exception { - final String TEST_NAME = "test192AccountMorganSecondDeadExpireOperation"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1359,7 +1326,6 @@ public void test192AccountMorganSecondDeadExpireOperation() throws Exception { */ @Test public void test194AccountMorganDeadExpireShadow() throws Exception { - final String TEST_NAME = "test194AccountMorganDeadExpireShadow"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1395,7 +1361,6 @@ public void test194AccountMorganDeadExpireShadow() throws Exception { */ @Test public void test196AccountMorganSecondDeadExpireShadow() throws Exception { - final String TEST_NAME = "test196AccountMorganSecondDeadExpireShadow"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1432,7 +1397,6 @@ public void test196AccountMorganSecondDeadExpireShadow() throws Exception { */ @Test public void test800AddAccountMorganAlreadyExists() throws Exception { - final String TEST_NAME = "test800AddAccountMorganAlreadyExists"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1513,7 +1477,6 @@ public void test800AddAccountMorganAlreadyExists() throws Exception { */ @Test public void test802AddAccountMorganAlreadyExistsAgain() throws Exception { - final String TEST_NAME = "test802AddAccountMorganAlreadyExistsAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1599,7 +1562,6 @@ public void test802AddAccountMorganAlreadyExistsAgain() throws Exception { @Test public void test804AddAccountElizabeth() throws Exception { - final String TEST_NAME = "test804AddAccountElizabeth"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1632,7 +1594,6 @@ public void test804AddAccountElizabeth() throws Exception { */ @Test public void test806RenameAccountElizabethAlreadyExists() throws Exception { - final String TEST_NAME = "test806RenameAccountElizabethAlreadyExists"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1713,7 +1674,6 @@ public void test806RenameAccountElizabethAlreadyExists() throws Exception { */ @Test public void test808RenameAccountElizabethAlreadyExistsAgain() throws Exception { - final String TEST_NAME = "test808RenameAccountElizabethAlreadyExistsAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1807,7 +1767,6 @@ public void test808RenameAccountElizabethAlreadyExistsAgain() throws Exception { */ @Test public void test810GetAccountMorganNotFound() throws Exception { - final String TEST_NAME = "test810GetAccountMorganNotFound"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1875,7 +1834,6 @@ public void test810GetAccountMorganNotFound() throws Exception { */ @Test public void test812ModifyAccountWillNotFound() throws Exception { - final String TEST_NAME = "test812ModifyAccountWillNotFound"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1949,7 +1907,6 @@ public void test812ModifyAccountWillNotFound() throws Exception { */ @Test public void test814DeleteAccountElizabethNotFound() throws Exception { - final String TEST_NAME = "test814DeleteAccountElizabethNotFound"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2014,7 +1971,6 @@ public void test814DeleteAccountElizabethNotFound() throws Exception { */ @Test public void test816AddAccountElizabethAfterDeathAlreadyExists() throws Exception { - final String TEST_NAME = "test816AddAccountElizabethAfterDeathAlreadyExists"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2083,7 +2039,6 @@ public void test816AddAccountElizabethAfterDeathAlreadyExists() throws Exception */ @Test public void test900GetAccountMurrayPending() throws Exception { - final String TEST_NAME = "test900GetAccountMurrayPending"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2694,7 +2649,7 @@ private void assertMorganDeleteFailed() throws Exception { assertNotNull("Shadow was not created in the repository", repoShadow); // @formatter:off - ShadowAsserter shadowAsserter = ShadowAsserter.forShadow(repoShadow, "repository"); + ShadowAsserter shadowAsserter = ShadowAsserter.forShadow(repoShadow, "repository"); shadowAsserter .display() .pendingOperations() @@ -2793,7 +2748,7 @@ private void assertMorganDeleteFailed() throws Exception { .assertPassword(ACCOUNT_MORGAN_PASSWORD); } - private void assertDeletedMorgan(int expectedAttemptNumber, int expectenNumberOfPendingOperations) throws Exception { + private void assertDeletedMorgan(int expectedAttemptNumber, int expectedNumberOfPendingOperations) throws Exception { PrismObject repoShadow = getShadowRepo(shadowMorganOid); assertNotNull("Shadow was not created in the repository", repoShadow); @@ -2803,7 +2758,7 @@ private void assertDeletedMorgan(int expectedAttemptNumber, int expectenNumberOf shadowAsserter .display() .pendingOperations() - .assertOperations(expectenNumberOfPendingOperations) + .assertOperations(expectedNumberOfPendingOperations) .by() .executionStatus(PendingOperationExecutionStatusType.COMPLETED) .resultStatus(OperationResultStatusType.SUCCESS) @@ -2837,7 +2792,7 @@ private void assertDeletedMorgan(int expectedAttemptNumber, int expectenNumberOf .assertSize(2) .end() .pendingOperations() - .assertOperations(expectenNumberOfPendingOperations) + .assertOperations(expectedNumberOfPendingOperations) .by() .executionStatus(PendingOperationExecutionStatusType.COMPLETED) .resultStatus(OperationResultStatusType.SUCCESS) diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java index 60e2e3e4daf..276c7a11652 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java @@ -90,7 +90,7 @@ protected void assertSchemaSanity(ResourceSchema resourceSchema, ResourceType re Collection associationDefinitions = accountRDef.getAssociationDefinitions(); assertEquals("Wrong number of association defs", 3, associationDefinitions.size()); RefinedAssociationDefinition crewAssociationDef = accountRDef.findAssociationDefinition(ASSOCIATION_CREW_NAME); - assertNotNull("No definitin for crew assocation", crewAssociationDef); + assertNotNull("No definition for crew association", crewAssociationDef); } @Override @@ -104,7 +104,6 @@ protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCr @Test public void test400AddAccountElizabeth() throws Exception { - final String TEST_NAME = "test400AddAccountElizabeth"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -115,8 +114,6 @@ public void test400AddAccountElizabeth() throws Exception { display("Adding shadow", account); - XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); String addedObjectOid = provisioningService.addObject(account, null, null, task, result); @@ -125,8 +122,6 @@ public void test400AddAccountElizabeth() throws Exception { then(); assertSuccess(result); - XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); - assertEquals(ACCOUNT_ELIZABETH_OID, addedObjectOid); account.checkConsistence(); @@ -136,8 +131,6 @@ public void test400AddAccountElizabeth() throws Exception { PrismObject accountProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_ELIZABETH_OID, null, task, result); - XMLGregorianCalendar tsAfterRead = clock.currentTimeXMLGregorianCalendar(); - display("Account will from provisioning", accountProvisioning); DummyAccount dummyAccount = getDummyAccountAssert(ACCOUNT_ELIZABETH_USERNAME, ACCOUNT_ELIZABETH_USERNAME); @@ -238,7 +231,6 @@ public void test419DisassociateCrewWillElizabeth() throws Exception { @Test public void test499DeleteAccountElizabeth() throws Exception { - final String TEST_NAME = "test499DeleteAccountElizabeth"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java index 5aace10768e..5c4f77679b5 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java @@ -98,7 +98,6 @@ public void testGetResourceBrokenSchema(BreakMode breakMode) throws Exception { @Test public void test190GetResource() throws Exception { - final String TEST_NAME = "test190GetResource"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -119,7 +118,6 @@ public void test190GetResource() throws Exception { @Test public void test200AddAccountNullAttributes() throws Exception { - final String TEST_NAME = "test200AddAccountNullAttributes"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -175,7 +173,7 @@ public void test201AddAccountEmptyAttributes() throws Exception { } @Test - public void test210AddAccountNoObjectclass() throws Exception { + public void test210AddAccountNoObjectClass() throws Exception { // GIVEN Task task =getTestTask(); OperationResult result = getTestOperationResult(); @@ -206,10 +204,8 @@ public void test210AddAccountNoObjectclass() throws Exception { @Test public void test220AddAccountNoResourceRef() throws Exception { - final String TEST_NAME = "test220AddAccountNoResourceRef"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -231,16 +227,14 @@ public void test220AddAccountNoResourceRef() throws Exception { display("Expected exception", e); } - //FIXME: not sure, if this check is needed..if the reosurce is not specified, provisioning probably will be not called. + //FIXME: not sure, if this check is needed..if the resource is not specified, provisioning probably will be not called. // syncServiceMock.assertNotifyFailureOnly(); } @Test public void test221DeleteAccountResourceNotFound() throws Exception { - final String TEST_NAME = "test221DeleteAccountResourceNotFound"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -273,10 +267,8 @@ public void test221DeleteAccountResourceNotFound() throws Exception { */ @Test public void test230GetAccountDeletedShadow() throws Exception { - final String TEST_NAME = "test230GetAccountDeletedShadow"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_MORGAN_FILE); @@ -285,7 +277,7 @@ public void test230GetAccountDeletedShadow() throws Exception { repositoryService.deleteObject(ShadowType.class, shadowOid, result); // reset - task = taskManager.createTaskInstance(TestDummyNegative.class.getName() + "." + TEST_NAME); + task = createPlainTask(); result = task.getResult(); syncServiceMock.reset(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java index 605b7e58cbf..f06eeb893fb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java @@ -11,8 +11,6 @@ import java.util.ArrayList; import java.util.Collection; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; @@ -21,6 +19,10 @@ import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; @@ -33,21 +35,14 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** * The test of Provisioning service on the API level. It checks proper caching of resource and schemas. - * + *

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

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

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

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

* The original repository object does not have resource schema. The schema * should be generated from the resource on the first use. This is the test * that executes testResource and checks whether the schema was generated. @@ -565,12 +545,12 @@ public void test106GetObjectStaticSchema() throws Exception { private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { ResourceType resourceType = resourceStaticSchema.asObjectable(); - assertNotNull("No resource schema in "+resourceType, resorceSchema); + assertNotNull("No resource schema in " + resourceType, resorceSchema); QName objectClassQname = new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "AccountObjectClass"); ObjectClassComplexTypeDefinition accountDefinition = resorceSchema.findObjectClassDefinition(objectClassQname); - assertNotNull("No object class definition for "+objectClassQname+" in resource schema", accountDefinition); + assertNotNull("No object class definition for " + objectClassQname + " in resource schema", accountDefinition); ObjectClassComplexTypeDefinition accountDef1 = resorceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); - assertTrue("Mismatched account definition: "+accountDefinition+" <-> "+accountDef1, accountDefinition == accountDef1); + assertTrue("Mismatched account definition: " + accountDefinition + " <-> " + accountDef1, accountDefinition == accountDef1); assertNotNull("No object class definition " + objectClassQname, accountDefinition); assertEquals("Object class " + objectClassQname + " is not account", ShadowKindType.ACCOUNT, accountDefinition.getKind()); @@ -582,24 +562,23 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertNotNull("Null identifiers for " + objectClassQname, identifiers); assertFalse("Empty identifiers for " + objectClassQname, identifiers.isEmpty()); - ResourceAttributeDefinition uidAttributeDefinition = accountDefinition.findAttributeDefinition(SchemaTestConstants.ICFS_UID); - assertNotNull("No definition for attribute "+SchemaTestConstants.ICFS_UID, uidAttributeDefinition); - assertTrue("Attribute "+SchemaTestConstants.ICFS_UID+" in not an identifier",uidAttributeDefinition.isPrimaryIdentifier(accountDefinition)); - assertTrue("Attribute "+SchemaTestConstants.ICFS_UID+" in not in identifiers list",identifiers.contains(uidAttributeDefinition)); - assertEquals("Wrong displayName for attribute "+SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidAttributeDefinition.getDisplayName()); - assertEquals("Wrong displayOrder for attribute "+SchemaTestConstants.ICFS_UID, (Integer)100, uidAttributeDefinition.getDisplayOrder()); + assertNotNull("No definition for attribute " + SchemaTestConstants.ICFS_UID, uidAttributeDefinition); + assertTrue("Attribute " + SchemaTestConstants.ICFS_UID + " in not an identifier", uidAttributeDefinition.isPrimaryIdentifier(accountDefinition)); + assertTrue("Attribute " + SchemaTestConstants.ICFS_UID + " in not in identifiers list", identifiers.contains(uidAttributeDefinition)); + assertEquals("Wrong displayName for attribute " + SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidAttributeDefinition.getDisplayName()); + assertEquals("Wrong displayOrder for attribute " + SchemaTestConstants.ICFS_UID, (Integer) 100, uidAttributeDefinition.getDisplayOrder()); Collection secondaryIdentifiers = accountDefinition.getSecondaryIdentifiers(); assertNotNull("Null secondary identifiers for " + objectClassQname, secondaryIdentifiers); assertFalse("Empty secondary identifiers for " + objectClassQname, secondaryIdentifiers.isEmpty()); ResourceAttributeDefinition nameAttributeDefinition = accountDefinition.findAttributeDefinition(SchemaTestConstants.ICFS_NAME); - assertNotNull("No definition for attribute "+SchemaTestConstants.ICFS_NAME, nameAttributeDefinition); - assertTrue("Attribute "+SchemaTestConstants.ICFS_NAME+" in not an identifier",nameAttributeDefinition.isSecondaryIdentifier(accountDefinition)); - assertTrue("Attribute "+SchemaTestConstants.ICFS_NAME+" in not in identifiers list",secondaryIdentifiers.contains(nameAttributeDefinition)); - assertEquals("Wrong displayName for attribute "+SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameAttributeDefinition.getDisplayName()); - assertEquals("Wrong displayOrder for attribute "+SchemaTestConstants.ICFS_NAME, (Integer)110, nameAttributeDefinition.getDisplayOrder()); + assertNotNull("No definition for attribute " + SchemaTestConstants.ICFS_NAME, nameAttributeDefinition); + assertTrue("Attribute " + SchemaTestConstants.ICFS_NAME + " in not an identifier", nameAttributeDefinition.isSecondaryIdentifier(accountDefinition)); + assertTrue("Attribute " + SchemaTestConstants.ICFS_NAME + " in not in identifiers list", secondaryIdentifiers.contains(nameAttributeDefinition)); + assertEquals("Wrong displayName for attribute " + SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameAttributeDefinition.getDisplayName()); + assertEquals("Wrong displayOrder for attribute " + SchemaTestConstants.ICFS_NAME, (Integer) 110, nameAttributeDefinition.getDisplayOrder()); assertNotNull("Null identifiers in account", accountDef1.getPrimaryIdentifiers()); assertFalse("Empty identifiers in account", accountDef1.getPrimaryIdentifiers().isEmpty()); @@ -614,11 +593,11 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertEquals(0, uidDef.getMinOccurs()); assertFalse("No UID display name", StringUtils.isBlank(uidDef.getDisplayName())); assertFalse("UID has create", uidDef.canAdd()); - assertFalse("UID has update",uidDef.canModify()); - assertTrue("No UID read",uidDef.canRead()); + assertFalse("UID has update", uidDef.canModify()); + assertTrue("No UID read", uidDef.canRead()); assertTrue("UID definition not in identifiers", accountDef1.getPrimaryIdentifiers().contains(uidDef)); - assertEquals("Wrong refined displayName for attribute "+SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidDef.getDisplayName()); - assertEquals("Wrong refined displayOrder for attribute "+SchemaTestConstants.ICFS_UID, (Integer)100, uidDef.getDisplayOrder()); + assertEquals("Wrong refined displayName for attribute " + SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidDef.getDisplayName()); + assertEquals("Wrong refined displayOrder for attribute " + SchemaTestConstants.ICFS_UID, (Integer) 100, uidDef.getDisplayOrder()); ResourceAttributeDefinition nameDef = accountDef1 .findAttributeDefinition(SchemaTestConstants.ICFS_NAME); @@ -626,13 +605,13 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertEquals(1, nameDef.getMinOccurs()); assertFalse("No NAME displayName", StringUtils.isBlank(nameDef.getDisplayName())); assertTrue("No NAME create", nameDef.canAdd()); - assertTrue("No NAME update",nameDef.canModify()); - assertTrue("No NAME read",nameDef.canRead()); + assertTrue("No NAME update", nameDef.canModify()); + assertTrue("No NAME read", nameDef.canRead()); assertTrue("NAME definition not in identifiers", accountDef1.getSecondaryIdentifiers().contains(nameDef)); - assertEquals("Wrong refined displayName for attribute "+SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameDef.getDisplayName()); - assertEquals("Wrong refined displayOrder for attribute "+SchemaTestConstants.ICFS_NAME, (Integer)110, nameDef.getDisplayOrder()); + assertEquals("Wrong refined displayName for attribute " + SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameDef.getDisplayName()); + assertEquals("Wrong refined displayOrder for attribute " + SchemaTestConstants.ICFS_NAME, (Integer) 110, nameDef.getDisplayOrder()); - assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef1.findAttributeDefinition(new QName(SchemaTestConstants.NS_ICFS,"password"))); + assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef1.findAttributeDefinition(new QName(SchemaTestConstants.NS_ICFS, "password"))); // ACCOUNT ObjectClassComplexTypeDefinition accountDef = resorceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); @@ -645,7 +624,7 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertTrue("No fullname create", fullnameDef.canAdd()); assertTrue("No fullname update", fullnameDef.canModify()); assertTrue("No fullname read", fullnameDef.canRead()); - assertTrue("Wrong displayOrder for attribute fullName: "+fullnameDef.getDisplayOrder(), + assertTrue("Wrong displayOrder for attribute fullName: " + fullnameDef.getDisplayOrder(), fullnameDef.getDisplayOrder() == 200 || fullnameDef.getDisplayOrder() == 250 || fullnameDef.getDisplayOrder() == 260); // GROUP @@ -660,21 +639,19 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertTrue("No members update", membersDef.canModify()); assertTrue("No members read", membersDef.canRead()); - assertEquals("Unexpected number of schema definitions in "+dummyResourceSchemalessCtl.getName()+" dummy resource", dummyResourceStaticSchema.getNumberOfObjectclasses(), resorceSchema.getDefinitions().size()); + assertEquals("Unexpected number of schema definitions in " + dummyResourceSchemalessCtl.getName() + " dummy resource", dummyResourceStaticSchema.getNumberOfObjectclasses(), resorceSchema.getDefinitions().size()); - for (Definition def: resorceSchema.getDefinitions()) { + for (Definition def : resorceSchema.getDefinitions()) { if (def instanceof RefinedObjectClassDefinition) { - AssertJUnit.fail("Refined definition sneaked into resource schema of "+dummyResourceSchemalessCtl.getName()+" dummy resource: "+def); + AssertJUnit.fail("Refined definition sneaked into resource schema of " + dummyResourceSchemalessCtl.getName() + " dummy resource: " + def); } } } @Test public void test107Capabilities() throws Exception { - final String TEST_NAME = "test107Capabilities"; - // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN when(); @@ -753,19 +730,16 @@ public void test200AddAccount() throws Exception { ShadowType accountType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result) .asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong name", "will", accountType.getName()); -// assertEquals("will", accountType.getName()); ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, result).asObjectable(); display("account from provisioning", provisioningAccountType); PrismAsserts.assertEqualsPolyString("Wrong name", "will", provisioningAccountType.getName()); -// assertEquals("will", provisioningAccountType.getName()); assertNull("The _PASSSWORD_ attribute sneaked into shadow", ShadowUtil.getAttributeValues( provisioningAccountType, new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); // Check if the account was created in the dummy resource - DummyAccount dummyAccount = dummyResourceStaticSchema.getAccountByUsername("will"); assertNotNull("No dummy account", dummyAccount); assertEquals("Fullname is wrong", "Will Turner", dummyAccount.getAttributeValue("fullname")); @@ -779,7 +753,5 @@ public void test200AddAccount() throws Exception { display("Repository shadow", shadowFromRepo.debugDump()); ProvisioningTestUtil.checkRepoAccountShadow(shadowFromRepo); - } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java index a475d829cb6..bb6ad792bcf 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java @@ -332,7 +332,6 @@ public void test006Capabilities() throws Exception { @Test public void test100AddAccountWill() throws Exception { - final String TEST_NAME = "test100AddAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -404,7 +403,6 @@ public void test100AddAccountWill() throws Exception { @Test public void test102GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test102GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -438,7 +436,6 @@ public void test102GetAccountWillFuture() throws Exception { */ @Test public void test104RefreshAccountWill() throws Exception { - final String TEST_NAME = "test104RefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -492,7 +489,6 @@ protected void backingStoreAddWill() throws IOException { @Test public void test106AddToBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test106AddToBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -533,7 +529,6 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { @Test public void test108GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test108GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -576,7 +571,6 @@ public void test108GetAccountWillFuture() throws Exception { @Test public void test109GetAccountWillFutureNoFetch() throws Exception { - final String TEST_NAME = "test109GetAccountWillFutureNoFetch"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -617,7 +611,6 @@ public void test109GetAccountWillFutureNoFetch() throws Exception { */ @Test public void test110CloseCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test110CloseCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -679,7 +672,6 @@ public void test110CloseCaseAndRefreshAccountWill() throws Exception { */ @Test public void test120RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test120RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -731,7 +723,6 @@ public void test120RefreshAccountWillAfter5min() throws Exception { */ @Test public void test130RefreshAccountWillAfter16min() throws Exception { - final String TEST_NAME = "test130RefreshAccountWillAfter16min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -783,7 +774,6 @@ public void test130RefreshAccountWillAfter16min() throws Exception { */ @Test public void test132RefreshAccountWillAfter27min() throws Exception { - final String TEST_NAME = "test132RefreshAccountWillAfter27min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -822,7 +812,6 @@ public void test132RefreshAccountWillAfter27min() throws Exception { @Test public void test200ModifyAccountWillFullname() throws Exception { - final String TEST_NAME = "test200ModifyAccountWillFullname"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -904,7 +893,6 @@ public void test200ModifyAccountWillFullname() throws Exception { @Test public void test202RefreshAccountWill() throws Exception { - final String TEST_NAME = "test202RefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -984,7 +972,6 @@ public void test202RefreshAccountWill() throws Exception { */ @Test public void test204CloseCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test204CloseCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1077,7 +1064,6 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { */ @Test public void test210RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test210RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1145,7 +1131,6 @@ protected void backingStoreUpdateWill(String newFullName, ActivationStatusType n @Test public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test212UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1209,7 +1194,6 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test220ModifyAccountWillDisable() throws Exception { - final String TEST_NAME = "test220ModifyAccountWillDisable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1292,7 +1276,6 @@ public void test220ModifyAccountWillDisable() throws Exception { */ @Test public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { - final String TEST_NAME = "test230ModifyAccountWillChangePasswordAndEnable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1382,7 +1365,6 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { */ @Test public void test240CloseDisableCaseAndReadAccountWill() throws Exception { - final String TEST_NAME = "test240CloseDisableCaseAndReadAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1493,7 +1475,6 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { */ @Test public void test250RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test250RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1580,7 +1561,6 @@ public void test250RefreshAccountWillAfter5min() throws Exception { @Test public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test252UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1645,7 +1625,6 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test260ClosePasswordChangeCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1744,7 +1723,6 @@ public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Excepti */ @Test public void test270RefreshAccountWillAfter7min() throws Exception { - final String TEST_NAME = "test270RefreshAccountWillAfter7min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1842,7 +1820,6 @@ public void test270RefreshAccountWillAfter7min() throws Exception { */ @Test public void test271RefreshAccountWillAfter12min() throws Exception { - final String TEST_NAME = "test271RefreshAccountWillAfter12min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1937,7 +1914,6 @@ public void test271RefreshAccountWillAfter12min() throws Exception { @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2001,7 +1977,6 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test280RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test132RefreshAccountWillAfter10min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2089,7 +2064,6 @@ public void test280RefreshAccountWillAfter5min() throws Exception { */ @Test public void test290RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test134RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2154,7 +2128,6 @@ public void test290RefreshAccountWillAfter5min() throws Exception { @Test public void test300DeleteAccountWill() throws Exception { - final String TEST_NAME = "test300DeleteAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2223,7 +2196,6 @@ public void test300DeleteAccountWill() throws Exception { @Test public void test302GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test302GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2248,7 +2220,6 @@ public void test302GetAccountWillFuture() throws Exception { @Test public void test303GetAccountWillFutureNoFetch() throws Exception { - final String TEST_NAME = "test303GetAccountWillFutureNoFetch"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2280,7 +2251,6 @@ public void test303GetAccountWillFutureNoFetch() throws Exception { */ @Test public void test310CloseCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test310CloseCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2346,7 +2316,6 @@ public void test310CloseCaseAndRefreshAccountWill() throws Exception { */ @Test public void test320RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test320RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java index 46cc1db8b42..5a9472decfc 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java @@ -67,10 +67,11 @@ protected void assertTimestampType(String attrName, ResourceAttributeDefinition< protected void assertTimestamp(String attrName, Object timestampValue) { if (!(timestampValue instanceof String)) { fail("Wrong type of "+attrName+", expected String but was "+timestampValue.getClass()); + } else { + String str = (String) timestampValue; + assertTrue("Timestamp " + attrName + " does not start with 2: " + str, str.startsWith("2")); + assertTrue("Timestamp " + attrName + " does not end with Z: " + str, str.endsWith("Z")); } - String str = (String)timestampValue; - assertTrue("Timestamp "+attrName+" does not start with 2: "+str, str.startsWith("2")); - assertTrue("Timestamp "+attrName+" does not end with Z: "+str, str.endsWith("Z")); } /** @@ -79,8 +80,6 @@ protected void assertTimestamp(String attrName, Object timestampValue) { @Test @Override public void test489DeleteOuSuperWithSub() throws Exception { - final String TEST_NAME = "test489DeleteOuSuperWithSub"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java b/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java index 0604ec6ef91..adfeda3f929 100644 --- a/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java +++ b/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java @@ -163,11 +163,6 @@ public String toString() { + ", oldRepoShadow=" + oldRepoShadow + ", currentResourceObject=" + currentResourceObject + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java b/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java index 4ebe790b170..1ec5cf903c9 100644 --- a/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java +++ b/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java @@ -10,7 +10,6 @@ import java.io.FileNotFoundException; import java.lang.reflect.InvocationTargetException; import java.net.ConnectException; -import java.net.UnknownHostException; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import java.util.ArrayList; @@ -33,7 +32,6 @@ import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.LoggingUtils; -import org.identityconnectors.common.security.GuardedByteArray; import org.identityconnectors.common.security.GuardedString; import org.identityconnectors.framework.common.exceptions.*; import org.identityconnectors.framework.common.objects.Attribute; @@ -49,7 +47,6 @@ import com.evolveum.midpoint.prism.crypto.Protector; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; -import com.evolveum.midpoint.prism.xml.XsdTypeMapper; import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; @@ -59,7 +56,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.CommonException; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; @@ -68,7 +64,6 @@ import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedByteArrayType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import org.identityconnectors.framework.impl.api.remote.RemoteWrappedException; @@ -228,7 +223,7 @@ static Throwable processConnIdException(Throwable connIdException, String desc, } // Introspect the inner exceptions and look for known causes - knownCause = lookForKnownCause(connIdException, connIdException, connIdResult); + knownCause = lookForKnownCause(connIdException, connIdResult); if (knownCause != null) { // LOGGER.error("LOOK FOR KNOWN EXCEPTION: {} -> {}", connIdException.getClass().getName(), knownCause.getClass().getName()); connIdResult.recordFatalError(knownCause); @@ -313,7 +308,7 @@ private static Exception processConnectorException(ConnectorException connIdExce } else if (connIdException instanceof RetryableException) { Exception newEx = new CommunicationException(createMessageFromAllExceptions(null, connIdException)); - connIdResult.recordFatalError("Retryable errror: " + connIdException.getMessage(), newEx); + connIdResult.recordFatalError("Retryable error: " + connIdException.getMessage(), newEx); return newEx; } else if (connIdException instanceof ConnectorSecurityException) { @@ -335,9 +330,7 @@ private static Exception processConnectorException(ConnectorException connIdExce return null; } - private static Exception lookForKnownCause(Throwable ex, - Throwable originalException, OperationResult parentResult) { - + private static Exception lookForKnownCause(Throwable ex, OperationResult parentResult) { if (ex.getClass().getPackage().equals(SchemaException.class.getPackage())) { // Common midPoint exceptions, pass through // Those may get here from the inner calls of handle() methods from the connector. @@ -378,7 +371,7 @@ private static Exception lookForKnownCause(Throwable ex, // This is thrown by LDAP connector and may be also throw by similar // connectors javax.naming.directory.InvalidAttributeValueException e = (javax.naming.directory.InvalidAttributeValueException) ex; - Exception newEx = null; + Exception newEx; if (e.getExplanation().contains("unique attribute conflict")){ newEx = new ObjectAlreadyExistsException(createMessageFromAllExceptions("Invalid attribute", ex)); } else{ @@ -431,7 +424,7 @@ private static Exception lookForKnownCause(Throwable ex, return null; } else { // Otherwise go one level deeper ... - return lookForKnownCause(ex.getCause(), originalException, + return lookForKnownCause(ex.getCause(), parentResult); } } @@ -666,14 +659,11 @@ public static GuardedString toGuardedString(ProtectedStringType ps, Protector pr if (ps.getClearValue() == null) { return null; } -// LOGGER.warn("Using cleartext value for {}", propertyName); return new GuardedString(ps.getClearValue().toCharArray()); } try { return new GuardedString(protector.decryptString(ps).toCharArray()); } catch (EncryptionException e) { -// LOGGER.error("Unable to decrypt value of element {}: {}", -// new Object[] { propertyName, e.getMessage(), e }); throw new SystemException("Unable to decrypt value of element " + propertyName + ": " + e.getMessage(), e); } diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java index 0718fa3317e..183f79d2887 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java @@ -7,10 +7,8 @@ package com.evolveum.midpoint.provisioning.ucf.impl.connid; import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.BeforeClass; @@ -19,6 +17,7 @@ import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorFactory; @@ -27,9 +26,9 @@ import com.evolveum.midpoint.schema.SchemaConstantsGenerated; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ResourceSchema; -import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; @@ -39,13 +38,14 @@ * Simple UCF tests. No real resource, just basic setup and sanity. * * @author Radovan Semancik - * + *

* This is an UCF test. It shold not need repository or other things from the midPoint spring context * except from the provisioning beans. But due to a general issue with spring context initialization * this is a lesser evil for now (MID-392) */ @ContextConfiguration(locations = { "classpath:ctx-ucf-connid-test.xml" }) -public abstract class AbstractUcfDummyTest extends AbstractSpringTest { +public abstract class AbstractUcfDummyTest extends AbstractSpringTest + implements OperationResultTestMixin { protected static final File RESOURCE_DUMMY_FILE = new File(UcfTestUtil.TEST_DIR, "resource-dummy.xml"); protected static final File CONNECTOR_DUMMY_FILE = new File(UcfTestUtil.TEST_DIR, "connector-dummy.xml"); @@ -85,10 +85,6 @@ public void setup() throws Exception { connectorType = connector.asObjectable(); } - protected OperationResult createResult() { - return new OperationResult(contextName()); - } - protected void assertPropertyDefinition(PrismContainer container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java index 8e373e22e30..b97f1c616e4 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java @@ -122,7 +122,7 @@ public void test002ConnectorSchema() throws Exception { */ @Test public void test010ListConnectors() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); Set connectors = connectorFactory.listConnectors(null, result); System.out.println("---------------------------------------------------------------------"); @@ -149,8 +149,9 @@ public void test020CreateConfiguredConnector() throws Exception { "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - OperationResult result = createResult(); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + OperationResult result = createOperationResult(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); // WHEN @@ -171,7 +172,7 @@ public void test022ConnectorStatsConfigured() throws Exception { assertNotNull("null operational status", operationalStatus); assertEquals("Wrong connectorClassName", DummyConnector.class.getName(), operationalStatus.getConnectorClassName()); - assertEquals("Wrong poolConfigMinSize", null, operationalStatus.getPoolConfigMinSize()); + assertNull("Wrong poolConfigMinSize", operationalStatus.getPoolConfigMinSize()); assertEquals("Wrong poolConfigMaxSize", (Integer) 10, operationalStatus.getPoolConfigMaxSize()); assertEquals("Wrong poolConfigMinIdle", (Integer) 1, operationalStatus.getPoolConfigMinIdle()); assertEquals("Wrong poolConfigMaxIdle", (Integer) 10, operationalStatus.getPoolConfigMaxIdle()); @@ -183,14 +184,15 @@ public void test022ConnectorStatsConfigured() throws Exception { @Test public void test030ResourceSchema() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); cc = connectorFactory.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType), "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); //ResourceTypeUtil.getSchemaGenerationConstraints(resourceType) cc.configure(configContainer, null, result); @@ -219,14 +221,15 @@ public void test030ResourceSchema() throws Exception { @Test public void test031ResourceSchemaAccountObjectClass() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); cc = connectorFactory.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType), "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); List objectClassesToGenerate = new ArrayList<>(); QName accountObjectClass = new QName(resource.asObjectable().getNamespace(), "AccountObjectClass"); @@ -256,7 +259,7 @@ public void test033ConnectorStatsInitialized() throws Exception { assertNotNull("null operational status", operationalStatus); assertEquals("Wrong connectorClassName", DummyConnector.class.getName(), operationalStatus.getConnectorClassName()); - assertEquals("Wrong poolConfigMinSize", null, operationalStatus.getPoolConfigMinSize()); + assertNull("Wrong poolConfigMinSize", operationalStatus.getPoolConfigMinSize()); assertEquals("Wrong poolConfigMaxSize", (Integer) 10, operationalStatus.getPoolConfigMaxSize()); assertEquals("Wrong poolConfigMinIdle", (Integer) 1, operationalStatus.getPoolConfigMinIdle()); assertEquals("Wrong poolConfigMaxIdle", (Integer) 10, operationalStatus.getPoolConfigMaxIdle()); @@ -268,9 +271,7 @@ public void test033ConnectorStatsInitialized() throws Exception { @Test public void test040AddAccount() throws Exception { - final String TEST_NAME = "test040AddAccount"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition defaultAccountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); ShadowType shadowType = new ShadowType(); @@ -315,7 +316,7 @@ public boolean handle(PrismObject shadow) { } }; - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // WHEN cc.search(accountDefinition, null, handler, null, null, null, null, result); @@ -334,10 +335,9 @@ private void checkUcfShadow(PrismObject shadow, ObjectClassComplexTy @Test public void test100FetchEmptyChanges() throws Exception { - final String TEST_NAME = "test100FetchEmptyChanges"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); - ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); + OperationResult result = createOperationResult(); + ObjectClassComplexTypeDefinition accountDefinition = + resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // WHEN PrismProperty lastToken = cc.fetchCurrentToken(accountDefinition, null, result); @@ -361,9 +361,7 @@ public void test100FetchEmptyChanges() throws Exception { @Test public void test101FetchAddChange() throws Exception { - final String TEST_NAME = "test101FetchAddChange"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); PrismProperty lastToken = cc.fetchCurrentToken(accountDefinition, null, result); @@ -396,10 +394,8 @@ public void test101FetchAddChange() throws Exception { @Test public void test500SelfTest() { - final String TEST_NAME = "test500SelfTest"; - // GIVEN - OperationResult testResult = new OperationResult(TestUcfDummy.class + "." + TEST_NAME); + OperationResult testResult = createOperationResult(); // WHEN connectorFactoryIcfImpl.selfTest(testResult); @@ -409,5 +405,4 @@ public void test500SelfTest() { IntegrationTestTools.display(testResult); TestUtil.assertSuccess(testResult); } - } diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java index 850f23a3d15..7c555ba8a4f 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java @@ -70,8 +70,9 @@ public void test020CreateConfiguredConnector() throws Exception { "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - OperationResult result = createResult(); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + OperationResult result = createOperationResult(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); // WHEN @@ -87,9 +88,7 @@ public void test020CreateConfiguredConnector() throws Exception { @Test public void test100AddAccount() throws Exception { - final String TEST_NAME = "test100AddAccount"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition defaultAccountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); ShadowType shadowType = new ShadowType(); @@ -134,7 +133,7 @@ public boolean handle(PrismObject shadow) { } }; - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // WHEN cc.search(accountDefinition, null, handler, null, null, null, null, result); @@ -152,7 +151,7 @@ public boolean handle(PrismObject shadow) { public void test200BlockingSearch() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); final ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // Determine object class from the schema @@ -222,7 +221,7 @@ public void test210TwoBlockingSearches() throws Exception { final ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // Determine object class from the schema - OperationResult result1 = createResult(); + OperationResult result1 = createOperationResult(); final List> searchResults1 = new ArrayList<>(); final ShadowResultHandler handler1 = new ShadowResultHandler() { @Override @@ -233,7 +232,7 @@ public boolean handle(PrismObject shadow) { } }; - OperationResult result2 = createResult(); + OperationResult result2 = createOperationResult(); final List> searchResults2 = new ArrayList<>(); final ShadowResultHandler handler2 = new ShadowResultHandler() { @Override diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java index e4af410ee96..8d90cbe2dae 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java @@ -258,9 +258,7 @@ private Collection> addSampleResourceObject(String name, St @Test public void test100AddDeleteObject() throws Exception { - final String TEST_NAME = "test100AddDeleteObject"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); Collection> identifiers = addSampleResourceObject("john", "John", "Smith"); @@ -292,9 +290,7 @@ public void test100AddDeleteObject() throws Exception { @Test public void test110ChangeModifyObject() throws Exception { - final String TEST_NAME = "test110ChangeModifyObject"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); Collection> identifiers = addSampleResourceObject("john", "John", "Smith"); @@ -336,9 +332,7 @@ public void test110ChangeModifyObject() throws Exception { @Test public void test200FetchChanges() throws Exception { - final String TEST_NAME = "test200FetchChanges"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findObjectClassDefinition(OpenDJController.OBJECT_CLASS_INETORGPERSON_NAME); PrismProperty lastToken = cc.fetchCurrentToken(accountDefinition, null, result); @@ -445,9 +439,8 @@ public void test310TestConnectionNegative() throws Exception { AssertJUnit.assertNotNull(connectorConnectionResult); System.out.println("Test \"connector connection\" result: " + connectorConnectionResult + " (FAILURE EXPECTED)"); - AssertJUnit.assertTrue("Unexpected success of bad connector test", - !connectorConnectionResult.isSuccess()); - AssertJUnit.assertTrue(!result.isSuccess()); + assertFalse("Unexpected success of bad connector test", connectorConnectionResult.isSuccess()); + assertFalse(result.isSuccess()); } /** @@ -481,8 +474,9 @@ public void test400FetchResourceSchema() throws Exception { AssertJUnit.assertFalse("No identifiers for account object class ", accountDefinition .getPrimaryIdentifiers().isEmpty()); - PrismPropertyDefinition uidDefinition = accountDefinition.findAttributeDefinition( - new QName(ResourceTypeUtil.getResourceNamespace(resourceType), OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME)); + PrismPropertyDefinition uidDefinition = accountDefinition.findAttributeDefinition( + new QName(ResourceTypeUtil.getResourceNamespace(resourceType), + OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME)); AssertJUnit.assertNotNull(uidDefinition); for (Definition def : resourceSchema.getDefinitions()) { @@ -522,13 +516,11 @@ public void test410Capabilities() throws Exception { @Test public void test500FetchObject() throws Exception { - final String TEST_NAME = "test500FetchObject"; - // GIVEN ResourceAttributeContainer resourceObject = createResourceObject( "uid=Teell,ou=People,dc=example,dc=com", "Teell William", "Teell"); - OperationResult addResult = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult addResult = createOperationResult("addObject"); PrismObject shadow = wrapInShadow(ShadowType.class, resourceObject); // Add a testing object @@ -540,7 +532,7 @@ public void test500FetchObject() throws Exception { // Determine object class from the schema ResourceObjectIdentification identification = new ResourceObjectIdentification(accountDefinition, identifiers, null); - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult("fetchObject"); // WHEN PrismObject ro = cc.fetchObject(identification, null, null, result); @@ -556,7 +548,6 @@ public void test500FetchObject() throws Exception { @Test public void test510Search() throws Exception { - final String TEST_NAME = "test510Search"; // GIVEN ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findObjectClassDefinition(OpenDJController.OBJECT_CLASS_INETORGPERSON_NAME); @@ -570,7 +561,7 @@ public boolean handle(PrismObject object) { } }; - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN cc.search(accountDefinition, null, handler, null, null, null, null, result); @@ -581,18 +572,13 @@ public boolean handle(PrismObject object) { @Test public void test600CreateAccountWithPassword() throws Exception { - final String TEST_NAME = "test600CreateAccountWithPassword"; // GIVEN ResourceAttributeContainer resourceObject = createResourceObject( "uid=lechuck,ou=people,dc=example,dc=com", "Ghost Pirate LeChuck", "LeChuck"); ProtectedStringType ps = protector.encryptString("t4k30v3rTh3W0rld"); -// PasswordChangeOperation passOp = new PasswordChangeOperation(ps); -// additionalOperations.add(passOp); - - OperationResult addResult = new OperationResult(this.getClass().getName() - + "." + TEST_NAME); + OperationResult addResult = createOperationResult(); PrismObject shadow = wrapInShadow(ShadowType.class, resourceObject); CredentialsType credentials = new CredentialsType(); @@ -620,13 +606,12 @@ public void test600CreateAccountWithPassword() throws Exception { @Test public void test610ChangePassword() throws Exception { - final String TEST_NAME = "test610ChangePassword"; // GIVEN ResourceAttributeContainer resourceObject = createResourceObject( "uid=drake,ou=People,dc=example,dc=com", "Sir Francis Drake", "Drake"); PrismObject shadow = wrapInShadow(ShadowType.class, resourceObject); - OperationResult addResult = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult addResult = createOperationResult(); // Add a testing object cc.addObject(shadow, null, addResult); diff --git a/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java b/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java index 4106169c928..414b6f3d3b2 100644 --- a/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java +++ b/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java @@ -640,12 +640,6 @@ private String formatReference(PrismReferenceValue refVal) { return refVal.toString(); } - - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java b/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java index 4ded99677f2..da09b4f5eb1 100644 --- a/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java +++ b/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java @@ -10,6 +10,7 @@ import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import javax.xml.namespace.QName; @@ -55,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100PlainExecuteEcho() throws Exception { - final String TEST_NAME = "test100PlainExecuteEcho"; - if (!isOsUnix()) { displaySkip(); return; @@ -79,8 +78,6 @@ public void test100PlainExecuteEcho() throws Exception { @Test public void test110RedirExecuteEcho() throws Exception { - final String TEST_NAME = "test110RedirExecuteEcho"; - if (!isOsUnix()) { displaySkip(); return; @@ -104,7 +101,7 @@ public void test110RedirExecuteEcho() throws Exception { File targetFile = new File(MidPointTestConstants.TARGET_DIR_PATH, "echo-out"); assertTrue("Target file is not there", targetFile.exists()); - String targetFileContent = FileUtils.readFileToString(targetFile); + String targetFileContent = FileUtils.readFileToString(targetFile, StandardCharsets.UTF_8); assertEquals("Wrong target file content", "Hello World", targetFileContent); } @@ -112,5 +109,4 @@ private CommandLineScriptType getScript(File file) throws SchemaException, IOExc PrismObject report = parseObject(file); return report.asObjectable().getPostReportScript(); } - } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java index 8037824b992..5b7f35f8d5f 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java @@ -237,7 +237,7 @@ private void checkContainerValuesSize(QName parentName, PrismContainerValue n } } - private void checkContainersSize(PrismContainer newContainer, PrismContainer oldContainer) { + private void checkContainersSize(PrismContainer newContainer, PrismContainer oldContainer) { logger.info("checkContainersSize {} new {} old {}", newContainer.getElementName(), newContainer.size(), oldContainer.size()); AssertJUnit.assertEquals(newContainer.size(), oldContainer.size()); @@ -248,16 +248,14 @@ private void checkContainersSize(PrismContainer newContainer, PrismContainer old return; } List checked = new ArrayList<>(); - List newValues = newContainer.getValues(); - for (PrismContainerValue value : newValues) { + for (PrismContainerValue value : newContainer.getValues()) { PrismContainerValue oldValue = oldContainer.getValue(value.getId()); checkContainerValuesSize(newContainer.getElementName(), value, oldValue); checked.add(value.getId()); } - List oldValues = oldContainer.getValues(); - for (PrismContainerValue value : oldValues) { + for (PrismContainerValue value : oldContainer.getValues()) { if (checked.contains(value.getId())) { continue; } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java index 8ae7c739e92..8944c8cded1 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java @@ -35,7 +35,7 @@ /** * @author Radovan Semancik */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ResourceModifyTest extends BaseSQLRepoTest { @@ -59,11 +59,8 @@ public void initAnts() { @Test public void test010AddResource() throws Exception { - final String TEST_NAME = "test010AddResource"; - logger.info("===[ {} ]===", TEST_NAME); - // GIVEN - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); + OperationResult result = createOperationResult(); PrismObject resource = prismContext.parseObject(RESOURCE_OPENDJ_FILE); // WHEN @@ -81,33 +78,24 @@ public void test010AddResource() throws Exception { @Test public void test020SingleDescriptionModify() throws Exception { - final String TEST_NAME = "test020SingleDescriptionModify"; - logger.info("===[ {} ]===", TEST_NAME); - - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); + OperationResult result = createOperationResult(); singleModify(descriptionAnt, -1, result); } @Test public void test030DescriptionModifySequence() throws Exception { - final String TEST_NAME = "test030DescriptionModifySequence"; - logger.info("===[ {} ]===", TEST_NAME); - - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); + OperationResult result = createOperationResult(); - for(int i=0; i <= MAX_SEQUENCE_ITERATIONS; i++) { + for (int i = 0; i <= MAX_SEQUENCE_ITERATIONS; i++) { singleModify(descriptionAnt, i, result); } } @Test public void test040RadomModifySequence() throws Exception { - final String TEST_NAME = "test040RadomModifySequence"; - logger.info("===[ {} ]===", TEST_NAME); + OperationResult result = createOperationResult(); - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); - - for(int i=0; i <= MAX_RANDOM_SEQUENCE_ITERATIONS; i++) { + for (int i = 0; i <= MAX_RANDOM_SEQUENCE_ITERATIONS; i++) { singleRandomModify(i, result); } } @@ -121,8 +109,8 @@ private void singleRandomModify(int iteration, OperationResult result) throws Ob private void singleModify(CarefulAnt ant, int iteration, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { // GIVEN - ItemDelta itemDelta = ant.createDelta(iteration); - Collection> modifications = MiscSchemaUtil.createCollection(itemDelta); + ItemDelta itemDelta = ant.createDelta(iteration); + Collection> modifications = MiscSchemaUtil.createCollection(itemDelta); System.out.println("itemDelta: " + itemDelta.debugDump()); @@ -133,9 +121,8 @@ private void singleModify(CarefulAnt ant, int iteration, Operation PrismObject resourceAfter = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); SqlRepoTestUtil.assertVersionProgress(lastVersion, resourceAfter.getVersion()); lastVersion = resourceAfter.getVersion(); - System.out.println("Version: "+lastVersion); + System.out.println("Version: " + lastVersion); ant.assertModification(resourceAfter, iteration); } - } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java index 05a8eabf0c8..ec78f72b463 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java @@ -82,11 +82,6 @@ protected String dumpQName(QName qname) { return builder.toString(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java index 231cc2e54f7..b933cbd05b9 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java @@ -141,11 +141,6 @@ public static QueryDefinitionRegistry2 getInstance() { return registry; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder builder = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java index a2613f7a580..dbb872e4e47 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java @@ -94,11 +94,6 @@ public String toString() { protected abstract String getDebugDumpClassName(); - @Override - public String debugDump() { - return debugDump(0); - } - public String getShortInfo() { StringBuilder sb = new StringBuilder(); sb.append(getDebugDumpClassName()).append(':').append(getJpaClassName()); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java index 16320ef4cf9..59251b5d754 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java @@ -167,11 +167,6 @@ protected String getDebugDumpClassName() { return "Ent"; } - @Override - public String debugDump() { - return debugDump(0); - } - public boolean isAssignableFrom(JpaEntityDefinition specificEntityDefinition) { return getJpaClass().isAssignableFrom(specificEntityDefinition.getJpaClass()); } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java index d6fdbf3f05f..b0e010a2d5f 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java @@ -101,11 +101,6 @@ public void accept(Visitor visitor) { targetDefinition.accept(visitor); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java index e94eb415b59..811143ce3df 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java @@ -63,11 +63,6 @@ HqlDataInstance getParentItem() { return parentDataItem; } - @Override - public String debugDump() { - return debugDump(0); - } - @SuppressWarnings("unused") public String debugDumpNoParent() { return debugDump(0, false); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java index 809faa37691..694eebdc1bd 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java @@ -110,11 +110,6 @@ public ItemPathResolutionState nextState(ItemDefinition itemDefinition, boolean itemPathResolver); } - @Override - public String debugDump() { - return debugDump(0); - } - String debugDumpNoParent() { return debugDump(0, false); } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java index b63e8742194..36dd90e011b 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java @@ -82,7 +82,7 @@ private List> listAllPrismContainers(Visitable object) { return; } - PrismContainer container = (PrismContainer) visitable; + PrismContainer container = (PrismContainer) visitable; PrismContainerDefinition def = container.getDefinition(); if (def.isSingleValue()) { return; diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index 7222cc172ae..e7bcc01508a 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -1825,7 +1825,7 @@ protected void displaySkip() { */ @SuppressWarnings("unused") protected void displayHEREHERE() { - IntegrationTestTools.display("HEREHERE"); + display(contextName() + "HEREHERE"); } public static void display(String message, SearchResultEntry response) { diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java index f96d1eba889..77949025cd7 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java @@ -472,11 +472,6 @@ public String toString() { return "DummyAuditService(" + records + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java index 27804f85812..a47d322560a 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java @@ -322,7 +322,7 @@ public static void assertProvisioningAccountShadow(PrismObject accou public static void assertProvisioningShadow(PrismObject account, Class expectedAttributeDefinitionClass, QName objectClass) { // Check attribute definition - PrismContainer attributesContainer = account.findContainer(ShadowType.F_ATTRIBUTES); + PrismContainer attributesContainer = account.findContainer(ShadowType.F_ATTRIBUTES); PrismAsserts.assertClass("Wrong attributes container class", ResourceAttributeContainer.class, attributesContainer); ResourceAttributeContainer rAttributesContainer = (ResourceAttributeContainer) attributesContainer; PrismContainerDefinition attrsDef = attributesContainer.getDefinition(); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index 6176259d5a3..04b7c23d06d 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -36,6 +36,7 @@ import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.CommonException; @@ -44,7 +45,8 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -public class AbstractTaskManagerTest extends AbstractSpringTest { +public class AbstractTaskManagerTest extends AbstractSpringTest + implements OperationResultTestMixin { protected static final String CYCLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-task-handler"; protected static final String CYCLE_FINISHING_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-finishing-task-handler"; @@ -83,10 +85,6 @@ public class AbstractTaskManagerTest extends AbstractSpringTest { protected MockParallelTaskHandler parallelTaskHandler; protected MockLongTaskHandler longTaskHandler; - protected static OperationResult createResult(String test) { - return new OperationResult(TestQuartzTaskManagerContract.class.getName() + ".test" + test); - } - protected void initHandlers() { MockCycleTaskHandler cycleHandler = new MockCycleTaskHandler(false); // ordinary recurring task taskManager.registerHandler(CYCLE_TASK_HANDLER_URI, cycleHandler); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java index 0d6b0ec0fa2..5454d5f1cc7 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java @@ -46,16 +46,12 @@ public void initialize() throws Exception { DebugUtil.setPrettyPrintBeansAs(PrismContext.LANG_YAML); } - private static String taskFilename(String testName, String subId) { - return "src/test/resources/partitioning/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/partitioning/task-" + getTestNumber() + "-" + subId + ".xml"; } - private static String taskOid(String testName, String subId) { - return "44444444-2222-2222-8888-" + testNumber(testName) + subId + "00000000"; - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid(String subId) { + return "44444444-2222-2222-8888-" + getTestNumber() + subId + "00000000"; } @Test @@ -66,14 +62,13 @@ public void test000Integrity() { @Test public void test100DurableRecurring() throws Exception { - final String TEST_NAME = "test100DurableRecurring"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "m")); + addObjectFromFile(taskFilename("m")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "m"); + String masterTaskOid = taskOid("m"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java index dceefebe0d5..0654aeff1d2 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java @@ -55,11 +55,7 @@ import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -/** - * @author Radovan Semancik - */ - -@ContextConfiguration(locations = {"classpath:ctx-task-test.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestQuartzTaskManagerContract extends AbstractTaskManagerTest { @@ -68,16 +64,20 @@ public class TestQuartzTaskManagerContract extends AbstractTaskManagerTest { private static final String TASK_OWNER2_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; private static final String NS_WHATEVER = "http://myself.me/schemas/whatever"; - private static String taskFilename(String test) { - return "src/test/resources/basic/task-" + test.substring(4) + ".xml"; + private String taskFilename(String fileSuffix) { + return "src/test/resources/basic/task-" + getTestNameShort().substring(4) + fileSuffix + ".xml"; } - private static String taskOid(String test, String subId) { - return "91919191-76e0-59e2-86d6-55665566" + subId + test.substring(4, 7); + private String taskFilename() { + return taskFilename(""); } - private static String taskOid(String test) { - return taskOid(test, "0"); + private String taskOid(String subId) { + return "91919191-76e0-59e2-86d6-55665566" + subId + getTestNumber(); + } + + private String taskOid() { + return taskOid("0"); } @BeforeSuite @@ -108,22 +108,19 @@ public void test000Integrity() { @Test public void test003GetProgress() throws Exception { - String TEST_NAME = "test003GetProgress"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); logger.trace("Retrieving the task and getting its progress..."); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); AssertJUnit.assertEquals("Progress is not 0", 0, task.getProgress()); } - - @Test(enabled=false) // this is probably OK to fail, so do not enable it (at least for now) + @Test(enabled = false) // this is probably OK to fail, so do not enable it (at least for now) public void test004aTaskBigProperty() throws Exception { - String TEST_NAME = "test004aTaskBigProperty"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); String string300 = "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-" @@ -138,13 +135,14 @@ public void test004aTaskBigProperty() throws Exception { + "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-"; - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); // property definition ItemName bigStringQName = new ItemName("http://midpoint.evolveum.com/repo/test", "bigString"); - MutablePrismPropertyDefinition bigStringDefinition = prismContext.definitionFactory().createPropertyDefinition(bigStringQName, DOMUtil.XSD_STRING); + MutablePrismPropertyDefinition bigStringDefinition = prismContext.definitionFactory() + .createPropertyDefinition(bigStringQName, DOMUtil.XSD_STRING); bigStringDefinition.setIndexed(false); bigStringDefinition.setMinOccurs(0); bigStringDefinition.setMaxOccurs(1); @@ -160,7 +158,7 @@ public void test004aTaskBigProperty() throws Exception { logger.trace("Retrieving the task and comparing its properties..."); - Task task001 = getTask(taskOid(TEST_NAME), result); + Task task001 = getTask(taskOid(), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); PrismProperty bigString001 = task001.getExtensionPropertyOrClone(bigStringQName); @@ -177,7 +175,7 @@ public void test004aTaskBigProperty() throws Exception { System.out.println("2nd round: Task before save = " + task001.debugDump()); task001.flushPendingModifications(result); // however, this does not work, because 'modifyObject' in repo first reads object, overwriting any existing definitions ... - Task task002 = getTask(taskOid(TEST_NAME), result); + Task task002 = getTask(taskOid(), result); System.out.println("2nd round: Task from repo: " + task002.debugDump()); PrismProperty bigString002 = task002.getExtensionPropertyOrClone(bigStringQName); @@ -186,8 +184,7 @@ public void test004aTaskBigProperty() throws Exception { @Test public void test004bTaskBigProperty() throws Exception { - String TEST_NAME = "test004aTaskBigProperty"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); String string300 = "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-" @@ -202,13 +199,15 @@ public void test004bTaskBigProperty() throws Exception { + "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-"; - addObjectFromFile(taskFilename(TEST_NAME)); + // TODO inttest: TEST_NAME was set to "test004aTaskBigProperty"; WHY a and not b? it fails with B now. + // TODO fix B file or what, so we can have this here: addObjectFromFile(taskFilename()); + addObjectFromFile("src/test/resources/basic/task-004aTaskBigProperty.xml"); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); // property definition ItemName shipStateQName = new ItemName("http://myself.me/schemas/whatever", "shipState"); - PrismPropertyDefinition shipStateDefinition = prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName); + PrismPropertyDefinition shipStateDefinition = prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName); assertNotNull("Cannot find property definition for shipState", shipStateDefinition); PrismProperty shipStateProperty = (PrismProperty) shipStateDefinition.instantiate(); @@ -221,7 +220,7 @@ public void test004bTaskBigProperty() throws Exception { logger.trace("Retrieving the task and comparing its properties..."); - Task task001 = getTask(taskOid(TEST_NAME), result); + Task task001 = getTask(taskOid(), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); PrismProperty shipState001 = task001.getExtensionPropertyOrClone(shipStateQName); @@ -235,7 +234,7 @@ public void test004bTaskBigProperty() throws Exception { System.out.println("2nd round: Task before save = " + task001.debugDump()); task001.flushPendingModifications(result); - Task task002 = getTask(taskOid(TEST_NAME), result); + Task task002 = getTask(taskOid(), result); System.out.println("2nd round: Task from repo: " + task002.debugDump()); PrismProperty bigString002 = task002.getExtensionPropertyOrClone(shipStateQName); @@ -244,11 +243,10 @@ public void test004bTaskBigProperty() throws Exception { @Test(enabled = false) public void test004cReferenceInExtension() throws Exception { // ok to fail - String TEST_NAME = "test004cReferenceInExtension"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); System.out.println("Task extension = " + task.getExtensionOrClone()); @@ -266,16 +264,15 @@ public void test004cReferenceInExtension() throws Exception { // o @Test(enabled = false) public void test004TaskProperties() throws Exception { - String TEST_NAME = "test004TaskProperties"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); System.out.println("Task extension = " + task.getExtensionOrClone()); - PrismPropertyDefinition delayDefinition = prismContext.definitionFactory().createPropertyDefinition(SchemaConstants.NOOP_DELAY_QNAME, DOMUtil.XSD_INT); + PrismPropertyDefinition delayDefinition = prismContext.definitionFactory().createPropertyDefinition(SchemaConstants.NOOP_DELAY_QNAME, DOMUtil.XSD_INT); System.out.println("property definition = " + delayDefinition); PrismProperty property = (PrismProperty) delayDefinition.instantiate(); @@ -285,7 +282,7 @@ public void test004TaskProperties() throws Exception { //delta.addV(property.getValues()); delta.setValuesToReplace(PrismValueCollectionsUtil.cloneCollection(property.getValues())); - Collection> modifications = new ArrayList<>(1); + Collection> modifications = new ArrayList<>(1); modifications.add(delta); // TODO fix this code @@ -341,10 +338,6 @@ public void test004TaskProperties() throws Exception { task.setResult(result); - //PrismObject requestee = task.getOwner(); - //task.setRequesteeRef(requestee); does not work - //task.setRequesteeOid(requestee.getOid()); - ObjectReferenceType objectReferenceType = new ObjectReferenceType(); objectReferenceType.setType(UserType.COMPLEX_TYPE); String objectOid = "some-oid..."; @@ -357,12 +350,12 @@ public void test004TaskProperties() throws Exception { logger.trace("Retrieving the task (second time) and comparing its properties..."); - Task task001 = getTask(taskOid(TEST_NAME), result); + Task task001 = getTask(taskOid(), result); logger.trace("Task from repo: " + task001.debugDump()); AssertJUnit.assertEquals(TaskBinding.LOOSE, task001.getBinding()); PrismAsserts.assertEqualsPolyString("Name not", newname, task001.getName()); // AssertJUnit.assertEquals(newname, task001.getName()); - AssertJUnit.assertTrue(10 == task001.getProgress()); + assertEquals(task001.getProgress(), 10); AssertJUnit.assertNotNull(task001.getLastRunStartTimestamp()); AssertJUnit.assertEquals("Start time is not correct", (Long) (currentTime / 1000L), (Long) (task001.getLastRunStartTimestamp() / 1000L)); // e.g. MySQL cuts off millisecond information AssertJUnit.assertNotNull(task001.getLastRunFinishTimestamp()); @@ -431,37 +424,36 @@ public void test004TaskProperties() throws Exception { @Test public void test005Single() throws Exception { - final String TEST_NAME = "test005Single"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on the handler singleHandler1.resetHasRun(); // Add single task. This will get picked by task scanner and executed - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); logger.trace("Retrieving the task..."); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); - AssertJUnit.assertNotNull(task); - logger.trace("Task retrieval OK."); + AssertJUnit.assertNotNull(task); + logger.trace("Task retrieval OK."); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task - waitForTaskClose(taskOid(TEST_NAME), result, 10000, 1000); + waitForTaskClose(taskOid(), result, 10000, 1000); logger.info("... done"); // Check task status - Task task1 = getTask(taskOid(TEST_NAME), result); + Task task1 = getTask(taskOid(), result); AssertJUnit.assertNotNull(task1); System.out.println("getTask returned: " + task1.debugDump()); - PrismObject po = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject po = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println("getObject returned: " + po.debugDump()); // .. it should be closed @@ -508,11 +500,10 @@ public void test005Single() throws Exception { @Test public void test006Cycle() throws Exception { - final String TEST_NAME = "test006Cycle"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // But before that check sanity ... a known problem with xsi:type - PrismObject object = addObjectFromFile(taskFilename(TEST_NAME)); + PrismObject object = addObjectFromFile(taskFilename()); ObjectType objectType = object.asObjectable(); TaskType addedTask = (TaskType) objectType; @@ -534,16 +525,16 @@ public void test006Cycle() throws Exception { // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject t = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(t.debugDump()); // .. it should be running @@ -589,26 +580,25 @@ private void assertSuccessOrInProgress(Task task) { @Test public void test008MoreHandlers() throws Exception { - final String TEST_NAME = "test008MoreHandlers"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on handlers singleHandler1.resetHasRun(); singleHandler2.resetHasRun(); singleHandler3.resetHasRun(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskClose(taskOid(TEST_NAME), result, 15000, 2000); + waitForTaskClose(taskOid(), result, 15000, 2000); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject o = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject o = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(ObjectTypeUtil.dump(o.getValue().getValue())); // .. it should be closed @@ -645,24 +635,23 @@ public void test008MoreHandlers() throws Exception { @Test public void test009CycleLoose() throws Exception { - final String TEST_NAME = "test009CycleLoose"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this task - waitForTaskProgress(taskOid(TEST_NAME), result, 15000, 2000, 1); + waitForTaskProgress(taskOid(), result, 15000, 2000, 1); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject t = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(t.debugDump()); // .. it should be running @@ -690,21 +679,20 @@ public void test009CycleLoose() throws Exception { @Test public void test010CycleCronLoose() throws Exception { - final String TEST_NAME = "test010CycleCronLoose"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskProgress(taskOid(TEST_NAME), result, 15000, 2000, 2); + waitForTaskProgress(taskOid(), result, 15000, 2000, 2); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - TaskType t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result).getValue().getValue(); + TaskType t = repositoryService.getObject(TaskType.class, taskOid(), null, result).getValue().getValue(); System.out.println(ObjectTypeUtil.dump(t)); AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); @@ -728,26 +716,25 @@ public void test010CycleCronLoose() throws Exception { @Test public void test011MoreHandlersAndSchedules() throws Exception { - final String TEST_NAME = "test011MoreHandlersAndSchedules"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on handlers l1Handler.resetHasRun(); l2Handler.resetHasRun(); l3Handler.resetHasRun(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskClose(taskOid(TEST_NAME), result, 30000, 2000); + waitForTaskClose(taskOid(), result, 30000, 2000); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject o = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject o = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(ObjectTypeUtil.dump(o.getValue().getValue())); // .. it should be closed @@ -791,27 +778,26 @@ public void test011MoreHandlersAndSchedules() throws Exception { } /* - * Suspends a running task. - */ + * Suspends a running task. + */ @Test public void test012Suspend() throws Exception { - final String TEST_NAME = "test012Suspend"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); // check if we can read the extension (xsi:type issue) - Task taskTemp = getTask(taskOid(TEST_NAME), result); - PrismProperty delay = taskTemp.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); + Task taskTemp = getTask(taskOid(), result); + PrismProperty delay = taskTemp.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); AssertJUnit.assertEquals("Delay was not read correctly", 2000, delay.getRealValue()); - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); // Check task status (task is running 5 iterations where each takes 2000 ms) - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -842,24 +828,23 @@ public void test012Suspend() throws Exception { @Test public void test013ReleaseAndSuspendLooselyBound() throws Exception { - final String TEST_NAME = "test013ReleaseAndSuspendLooselyBound"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); // check if we can read the extension (xsi:type issue) - PrismProperty delay = task.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); + PrismProperty delay = task.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); AssertJUnit.assertEquals("Delay was not read correctly", 1000, delay.getRealValue()); // let us resume (i.e. start the task) taskManager.resumeTask(task, result); // task is executing for 1000 ms, so we need to wait slightly longer, in order for the execution to be done - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); task.refresh(result); @@ -899,15 +884,14 @@ public void test013ReleaseAndSuspendLooselyBound() throws Exception { @Test public void test014SuspendLongRunning() throws Exception { - final String TEST_NAME = "test014SuspendLongRunning"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); - waitForTaskStart(taskOid(TEST_NAME), result, 10000, 2000); + waitForTaskStart(taskOid(), result, 10000, 2000); task.refresh(result); @@ -958,11 +942,10 @@ public void test014SuspendLongRunning() throws Exception { @Test public void test015DeleteTaskFromRepo() throws Exception { - final String TEST_NAME = "test015DeleteTaskFromRepo"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); - String oid = taskOid(TEST_NAME); + addObjectFromFile(taskFilename()); + String oid = taskOid(); // is the task in Quartz? @@ -971,7 +954,7 @@ public void test015DeleteTaskFromRepo() throws Exception { // Remove task from repo - repositoryService.deleteObject(TaskType.class, taskOid(TEST_NAME), result); + repositoryService.deleteObject(TaskType.class, taskOid(), result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this task @@ -994,15 +977,14 @@ public void timeout() { @Test public void test016WaitForSubtasks() throws Exception { - final String TEST_NAME = "test016WaitForSubtasks"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); //taskManager.getClusterManager().startClusterManagerThread(); try { - Task rootTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME)), result); - Task firstChildTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME + "-child-1")), result); + Task rootTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); + Task firstChildTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename("-child-1")), result); Task firstReloaded = taskManager.getTaskByIdentifier(firstChildTask.getTaskIdentifier(), result); assertEquals("Didn't get correct task by identifier", firstChildTask.getOid(), firstReloaded.getOid()); @@ -1014,7 +996,8 @@ public void test016WaitForSubtasks() throws Exception { secondChildTask.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); // will resume it after root starts waiting for tasks taskManager.switchToBackground(secondChildTask, result); - Task firstPrerequisiteTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME + "-prerequisite-1")), result); + Task firstPrerequisiteTask = taskManager.createTaskInstance( + addObjectFromFile(taskFilename("-prerequisite-1")), result); List prerequisities = rootTask.listPrerequisiteTasks(result); assertEquals("Wrong # of prerequisite tasks", 1, prerequisities.size()); @@ -1055,7 +1038,7 @@ public void test016WaitForSubtasks() throws Exception { taskManager.resumeTask(secondChildTask, result); taskManager.resumeTask(secondPrerequisiteTask, result); - final String rootOid = taskOid(TEST_NAME); + final String rootOid = taskOid(); waitForTaskClose(rootOid, result, 60000, 3000); @@ -1076,15 +1059,15 @@ public void test016WaitForSubtasks() throws Exception { @Test public void test017WaitForSubtasksEmpty() throws Exception { - final String TEST_NAME = "test017WaitForSubtasksEmpty"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.getClusterManager().startClusterManagerThread(); try { - Task rootTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME)), result); + Task rootTask = taskManager.createTaskInstance( + addObjectFromFile(taskFilename()), result); display("root task", rootTask); - waitForTaskClose(taskOid(TEST_NAME), result, 40000, 3000); + waitForTaskClose(taskOid(), result, 40000, 3000); } finally { taskManager.getClusterManager().stopClusterManagerThread(10000L, result); } @@ -1092,8 +1075,7 @@ public void test017WaitForSubtasksEmpty() throws Exception { @Test public void test018TaskResult() throws Exception { - final String TEST_NAME = "test018RefreshingResult"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); Task task = taskManager.createTaskInstance(); task.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); @@ -1119,24 +1101,23 @@ public void test018TaskResult() throws Exception { @Test public void test019FinishedHandler() throws Exception { - final String TEST_NAME = "test019FinishedHandler"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on handlers singleHandler1.resetHasRun(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskClose(taskOid(TEST_NAME), result, 15000, 2000); + waitForTaskClose(taskOid(), result, 15000, 2000); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject o = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject o = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(ObjectTypeUtil.dump(o.getValue().getValue())); // .. it should be closed @@ -1168,10 +1149,9 @@ public void test019FinishedHandler() throws Exception { @Test public void test020QueryByExecutionStatus() throws Exception { - final String TEST_NAME = "test020QueryByExecutionStatus"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME)), result); + taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); ObjectFilter filter1 = prismContext.queryFor(TaskType.class).item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.WAITING).buildFilter(); ObjectFilter filter2 = prismContext.queryFor(TaskType.class).item(TaskType.F_WAITING_REASON).eq(TaskWaitingReasonType.OTHER).buildFilter(); @@ -1188,12 +1168,11 @@ public void test020QueryByExecutionStatus() throws Exception { @Test public void test021DeleteTaskTree() throws Exception { - final String TEST_NAME = "test021DeleteTaskTree"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - PrismObject parentTaskPrism = addObjectFromFile(taskFilename(TEST_NAME)); - PrismObject childTask1Prism = addObjectFromFile(taskFilename(TEST_NAME+"-child1")); - PrismObject childTask2Prism = addObjectFromFile(taskFilename(TEST_NAME+"-child2")); + PrismObject parentTaskPrism = addObjectFromFile(taskFilename()); + PrismObject childTask1Prism = addObjectFromFile(taskFilename("-child1")); + PrismObject childTask2Prism = addObjectFromFile(taskFilename("-child2")); AssertJUnit.assertEquals(TaskExecutionStatusType.WAITING, parentTaskPrism.asObjectable().getExecutionStatus()); AssertJUnit.assertEquals(TaskExecutionStatusType.SUSPENDED, childTask1Prism.asObjectable().getExecutionStatus()); @@ -1220,35 +1199,33 @@ public void test021DeleteTaskTree() throws Exception { try { repositoryService.getObject(TaskType.class, childTask1.getOid(), null, result); - assertTrue("Task " + childTask1 + " was not deleted from the repository", false); + fail("Task " + childTask1 + " was not deleted from the repository"); } catch (ObjectNotFoundException e) { // ok! } try { repositoryService.getObject(TaskType.class, childTask2.getOid(), null, result); - assertTrue("Task " + childTask2 + " was not deleted from the repository", false); + fail("Task " + childTask2 + " was not deleted from the repository"); } catch (ObjectNotFoundException e) { // ok! } try { repositoryService.getObject(TaskType.class, parentTask.getOid(), null, result); - assertTrue("Task " + parentTask + " was not deleted from the repository", false); + fail("Task " + parentTask + " was not deleted from the repository"); } catch (ObjectNotFoundException e) { // ok! } - } @Test public void test022ExecuteRecurringOnDemand() throws Exception { - final String TEST_NAME = "test022ExecuteRecurringOnDemand"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); System.out.println("Waiting to see if the task would not start..."); @@ -1266,7 +1243,7 @@ public void test022ExecuteRecurringOnDemand() throws Exception { taskManager.scheduleRunnableTaskNow(task, result); // task is executing for 1000 ms, so we need to wait slightly longer, in order for the execution to be done - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); task.refresh(result); System.out.println("After refresh: " + task.debugDump()); @@ -1288,12 +1265,11 @@ public void test022ExecuteRecurringOnDemand() throws Exception { @Test public void test100LightweightSubtasks() throws Exception { - final String TEST_NAME = "test100LightweightSubtasks"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - String taskOid = taskOid(TEST_NAME); + String taskOid = taskOid(); Task task = getTask(taskOid, result); System.out.println("After setup: " + task.debugDump()); @@ -1324,7 +1300,7 @@ private void checkTaskStateRepeatedly(String taskOid, OperationResult result, in OperationStatsType stats = task.getOperationStats(); Integer totalSuccessCount = stats != null && stats.getIterativeTaskInformation() != null ? stats.getIterativeTaskInformation().getTotalSuccessCount() : null; - System.out.println((System.currentTimeMillis()-start) + ": subtasks: " + task.getSubtaskRef().size() + + System.out.println((System.currentTimeMillis() - start) + ": subtasks: " + task.getSubtaskRef().size() + ", progress = " + task.getProgress() + ", objects = " + totalSuccessCount); if (task.getExecutionStatus() != TaskExecutionStatusType.RUNNABLE) { System.out.println("Done. Status = " + task.getExecutionStatus()); @@ -1336,15 +1312,14 @@ private void checkTaskStateRepeatedly(String taskOid, OperationResult result, in @Test public void test105LightweightSubtasksSuspension() throws Exception { - final String TEST_NAME = "test105LightweightSubtasksSuspension"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); - waitForTaskStart(taskOid(TEST_NAME), result, 15000, 500); + waitForTaskStart(taskOid(), result, 15000, 500); task.refresh(result); System.out.println("After refresh (task was started; and it should run now): " + task.debugDump()); @@ -1385,14 +1360,13 @@ public void test105LightweightSubtasksSuspension() throws Exception { @Test public void test108SecondaryGroupLimit() throws Exception { - final String TEST_NAME = "test108SecondaryGroupLimit"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - TaskType task1 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task1 = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); waitForTaskStart(task1.getOid(), result, 10000, 500); // import second task with the same group (expensive) - TaskType task2 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME + "-2")).asObjectable(); + TaskType task2 = (TaskType) addObjectFromFile(taskFilename("-2")).asObjectable(); Thread.sleep(10000); task1 = getTaskType(task1.getOid(), result); @@ -1410,7 +1384,7 @@ public void test108SecondaryGroupLimit() throws Exception { waitForTaskStart(task2Oid, result, 10000, 500); // import third task that has another collision (large-ram) with the second one - TaskType task3 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME + "-3")).asObjectable(); + TaskType task3 = (TaskType) addObjectFromFile(taskFilename("-3")).asObjectable(); Thread.sleep(10000); task2 = getTaskType(task2Oid, result); @@ -1444,16 +1418,15 @@ protected void assertNextRetryTimeSet(TaskType task, OperationResult result) @Test public void test110GroupLimit() throws Exception { - final String TEST_NAME = "test110GroupLimit"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.getExecutionManager().setLocalExecutionLimitations((TaskExecutionLimitationsType) null); - TaskType task1 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task1 = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); waitForTaskStart(task1.getOid(), result, 10000, 500); // import second task with the same group - TaskType task2 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME + "-2")).asObjectable(); + TaskType task2 = (TaskType) addObjectFromFile(taskFilename("-2")).asObjectable(); Thread.sleep(10000); task1 = getTaskType(task1.getOid(), result); @@ -1483,8 +1456,7 @@ private TaskType getTaskType(String oid, OperationResult result) throws SchemaEx @Test public void test120NodeAllowed() throws Exception { - final String TEST_NAME = "test120NodeAllowed"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.getExecutionManager().setLocalExecutionLimitations( new TaskExecutionLimitationsType() @@ -1492,7 +1464,7 @@ public void test120NodeAllowed() throws Exception { .groupLimitation(new TaskGroupExecutionLimitationType().groupName(null)) .groupLimitation(new TaskGroupExecutionLimitationType().groupName(TaskConstants.LIMIT_FOR_OTHER_GROUPS).limit(0))); - TaskType task = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); waitForTaskStart(task.getOid(), result, 10000, 500); task = getTaskType(task.getOid(), result); assertNotNull("Task was not started even if it should be", task.getLastRunStartTimestamp()); @@ -1500,10 +1472,9 @@ public void test120NodeAllowed() throws Exception { @Test public void test130NodeNotAllowed() throws Exception { - final String TEST_NAME = "test130NodeNotAllowed"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - TaskType task = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); Thread.sleep(10000); task = getTaskType(task.getOid(), result); assertNull("Task was started even if it shouldn't be", task.getLastRunStartTimestamp()); @@ -1512,36 +1483,35 @@ public void test130NodeNotAllowed() throws Exception { @Test public void test999CheckingLeftovers() throws Exception { - String TEST_NAME = "test999CheckingLeftovers"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); ArrayList leftovers = new ArrayList<>(); - checkLeftover(leftovers, "test005", result); - checkLeftover(leftovers, "test006", result); - checkLeftover(leftovers, "test008", result); - checkLeftover(leftovers, "test009", result); - checkLeftover(leftovers, "test010", result); - checkLeftover(leftovers, "test011", result); - checkLeftover(leftovers, "test012", result); - checkLeftover(leftovers, "test013", result); - checkLeftover(leftovers, "test014", result); - checkLeftover(leftovers, "test015", result); - checkLeftover(leftovers, "test016", result); - checkLeftover(leftovers, "test017", result); - checkLeftover(leftovers, "test019", result); - checkLeftover(leftovers, "test021", result); - checkLeftover(leftovers, "test021", "1", result); - checkLeftover(leftovers, "test021", "2", result); - checkLeftover(leftovers, "test022", result); - checkLeftover(leftovers, "test100", result); - checkLeftover(leftovers, "test105", result); - checkLeftover(leftovers, "test108", result); - checkLeftover(leftovers, "test108", "a", result); - checkLeftover(leftovers, "test108", "b", result); - checkLeftover(leftovers, "test110", result); - checkLeftover(leftovers, "test110", "a", result); - checkLeftover(leftovers, "test120", result); - checkLeftover(leftovers, "test130", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, "1", result); + checkLeftover(leftovers, "2", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, "a", result); + checkLeftover(leftovers, "b", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, "a", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); StringBuilder message = new StringBuilder("Leftover task(s) found:"); for (String leftover : leftovers) { @@ -1551,12 +1521,12 @@ public void test999CheckingLeftovers() throws Exception { AssertJUnit.assertTrue(message.toString(), leftovers.isEmpty()); } - private void checkLeftover(ArrayList leftovers, String testNumber, OperationResult result) throws Exception { - checkLeftover(leftovers, testNumber, "0", result); + private void checkLeftover(ArrayList leftovers, OperationResult result) throws Exception { + checkLeftover(leftovers, "0", result); } - private void checkLeftover(ArrayList leftovers, String testNumber, String subId, OperationResult result) throws Exception { - String oid = taskOid(testNumber, subId); + private void checkLeftover(ArrayList leftovers, String subId, OperationResult result) throws Exception { + String oid = taskOid(subId); Task t; try { t = getTask(oid, result); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java index 446e9ca3d10..655eddb9907 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java @@ -48,48 +48,44 @@ public class TestWorkBucketStrategies extends AbstractTaskManagerTest { @Autowired private WorkStateManager workStateManager; @Autowired private WorkSegmentationStrategyFactory strategyFactory; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/work-buckets/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/work-buckets/task-" + getTestNumber() + "-" + subId + ".xml"; } - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private String taskFilename() { + return taskFilename("0"); } - private static String taskOid(String testName, String subId) { - return "44444444-0000-0000-0000-" + testNumber(testName) + subId + "00000000"; + private String taskOid(String subId) { + return "44444444-0000-0000-0000-" + getTestNumber() + subId + "00000000"; } - private static String taskOid(String test) { - return taskOid(test, "0"); - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid() { + return taskOid("0"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); + protected String workerTaskFilename() { + return taskFilename("w"); } @SuppressWarnings("unused") @NotNull - protected String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); + protected String coordinatorTaskFilename() { + return taskFilename("c"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); + protected String workerTaskOid() { + return taskOid("w"); } @SuppressWarnings("unused") @NotNull - protected String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); + protected String coordinatorTaskOid() { + return taskOid("c"); } @PostConstruct @@ -107,11 +103,10 @@ public void test000Integrity() { @Test public void test100NumericExplicitBuckets() throws Exception { - final String TEST_NAME = "test100NumericExplicitBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkBucketType bucket = workStateManager.getWorkBucket(task.getOid(), 0, null, null, result); @@ -188,11 +183,10 @@ public void test100NumericExplicitBuckets() throws Exception { @Test public void test110FilterExplicitBuckets() throws Exception { - final String TEST_NAME = "test110FilterExplicitBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -276,11 +270,10 @@ public void test110FilterExplicitBuckets() throws Exception { @Test public void test120StringPrefixBuckets() throws Exception { - final String TEST_NAME = "test120StringPrefixBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -332,11 +325,10 @@ public void test120StringPrefixBuckets() throws Exception { @Test public void test125StringExactValueBuckets() throws Exception { - final String TEST_NAME = "test125StringExactValueBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -388,11 +380,10 @@ public void test125StringExactValueBuckets() throws Exception { @Test public void test130StringIntervalBuckets() throws Exception { - final String TEST_NAME = "test130StringIntervalBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -438,11 +429,10 @@ public void test130StringIntervalBuckets() throws Exception { @Test public void test140OidBuckets() throws Exception { - final String TEST_NAME = "test140OidBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -457,11 +447,10 @@ public void test140OidBuckets() throws Exception { @Test public void test150OidBucketsTwice() throws Exception { - final String TEST_NAME = "test150OidBucketsTwice"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java index 85ecd80bf57..d9e3fcc6956 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java @@ -59,44 +59,40 @@ public class TestWorkDistribution extends AbstractTaskManagerTest { @Autowired private WorkStateManager workStateManager; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/work/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/work/task-" + getTestNumber() + "-" + subId + ".xml"; } - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private String taskFilename() { + return taskFilename("0"); } - private static String taskOid(String testName, String subId) { - return "44444444-2222-2222-2222-" + testNumber(testName) + subId + "00000000"; + private String taskOid(String subId) { + return "44444444-2222-2222-2222-" + getTestNumber() + subId + "00000000"; } - private static String taskOid(String test) { - return taskOid(test, "0"); - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid() { + return taskOid("0"); } @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); + protected String workerTaskFilename() { + return taskFilename("w"); } @NotNull - protected String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); + protected String coordinatorTaskFilename() { + return taskFilename("c"); } @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); + protected String workerTaskOid() { + return taskOid("w"); } @NotNull - protected String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); + protected String coordinatorTaskOid() { + return taskOid("c"); } @PostConstruct @@ -114,20 +110,19 @@ public void test000Integrity() { @Test public void test100AllocateBucket() throws Exception { - final String TEST_NAME = "test100AllocateBucket"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(workerTaskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(workerTaskFilename()); try { - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(TEST_NAME), result); + TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); // WHEN WorkBucketType bucket = workStateManager.getWorkBucket(worker.getOid(), 0, null, null, result); // THEN display("allocated bucket", bucket); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid(), result); TaskQuartzImpl workerAfter = taskManager.getTask(worker.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker task after", workerAfter); @@ -141,17 +136,16 @@ public void test100AllocateBucket() throws Exception { assertOptimizedCompletedBuckets(coordinatorAfter); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test105AllocateBucketStandalone() throws Exception { - final String TEST_NAME = "test105AllocateBucketStandalone"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); try { // WHEN @@ -174,11 +168,10 @@ public void test105AllocateBucketStandalone() throws Exception { @Test public void test107AllocateBucketStandaloneBatched() throws Exception { - final String TEST_NAME = "test107AllocateBucketStandaloneBatched"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); try { // WHEN @@ -200,12 +193,10 @@ public void test107AllocateBucketStandaloneBatched() throws Exception { @Test public void test110AllocateTwoBucketsStandalone() throws Exception { - final String TEST_NAME = "test110AllocateTwoBucketsStandalone"; - - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); try { // WHEN @@ -268,11 +259,10 @@ public void test110AllocateTwoBucketsStandalone() throws Exception { @Test public void test120UnspecifiedBuckets() throws Exception { - final String TEST_NAME = "test120UnspecifiedBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN + THEN try { @@ -285,21 +275,20 @@ public void test120UnspecifiedBuckets() throws Exception { @Test public void test130AllocateReleaseCompleteSequence() throws Exception { - final String TEST_NAME = "test130AllocateReleaseCompleteSequence"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); - addObjectFromFile(taskFilename(TEST_NAME, "4")); - addObjectFromFile(taskFilename(TEST_NAME, "5")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); + addObjectFromFile(taskFilename("4")); + addObjectFromFile(taskFilename("5")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); - TaskQuartzImpl worker4 = taskManager.getTask(taskOid(TEST_NAME, "4"), result); - TaskQuartzImpl worker5 = taskManager.getTask(taskOid(TEST_NAME, "5"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); + TaskQuartzImpl worker4 = taskManager.getTask(taskOid("4"), result); + TaskQuartzImpl worker5 = taskManager.getTask(taskOid("5"), result); // WHEN WorkBucketType bucket1 = workStateManager.getWorkBucket(worker1.getOid(), 0, null, null, result); @@ -319,7 +308,7 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { worker2 = taskManager.getTask(worker2.getOid(), result); worker3 = taskManager.getTask(worker3.getOid(), result); worker4 = taskManager.getTask(worker4.getOid(), result); - Task coordinator = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + Task coordinator = taskManager.getTask(coordinatorTaskOid(), result); display("coordinator task after 4+1x allocation", coordinator); display("worker1 task after 4+1x allocation", worker1); display("worker2 task after 4+1x allocation", worker2); @@ -507,25 +496,24 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { assertNoWorkBuckets(worker1.getWorkState()); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test200OneWorkerTask() throws Exception { - final String TEST_NAME = "test200OneWorkerTask"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(workerTaskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(workerTaskFilename()); - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(TEST_NAME), result); + TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); try { // WHEN taskManager.resumeTask(worker, result); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); @@ -535,23 +523,22 @@ public void test200OneWorkerTask() throws Exception { assertTotalSuccessCount(30, singleton(workerAfter)); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test210ThreeWorkersTask() throws Exception { - final String TEST_NAME = "test210ThreeWorkersTask"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); workBucketsTaskHandler.setDelayProcessor(50); @@ -561,7 +548,7 @@ public void test210ThreeWorkersTask() throws Exception { taskManager.resumeTask(worker3, result); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); @@ -587,22 +574,21 @@ public void test210ThreeWorkersTask() throws Exception { // TODO other asserts } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test220WorkerSuspend() throws Exception { - final String TEST_NAME = "test220WorkerSuspend"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); Holder suspensionVictim = new Holder<>(); workBucketsTaskHandler.setProcessor((task, bucket, index) -> { @@ -628,7 +614,7 @@ public void test220WorkerSuspend() throws Exception { // THEN then(); - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitFor("waiting for all items to be processed", () -> getTotalItemsProcessed(coordinatorTaskOid) == 107 - 6, DEFAULT_TIMEOUT, 500); @@ -676,22 +662,21 @@ public void test220WorkerSuspend() throws Exception { // this does not work as processed items from deleted subtask are missing //assertTotalSuccessCount(107 - 6 + 10, coordinatorAfter.listSubtasks(result)); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test230WorkerException() throws Exception { - final String TEST_NAME = "test230WorkerException"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); Holder exceptionVictim = new Holder<>(); workBucketsTaskHandler.setProcessor((task, bucket, index) -> { @@ -713,7 +698,7 @@ public void test230WorkerException() throws Exception { // THEN then(); - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitFor("waiting for all items to be processed", () -> getTotalItemsProcessed(coordinatorTaskOid) == 107 - 6, DEFAULT_TIMEOUT, 500); @@ -769,29 +754,28 @@ public void test230WorkerException() throws Exception { assertOptimizedCompletedBuckets(coordinatorAfter); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test300NarrowQueryOneWorkerTask() throws Exception { - final String TEST_NAME = "test300NarrowQueryOneWorkerTask"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(workerTaskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(workerTaskFilename()); workBucketsTaskHandler.resetBeforeTest(); workBucketsTaskHandler.setDefaultQuery(prismContext.queryFactory().createQuery()); try { - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(TEST_NAME), result); + TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); // WHEN taskManager.resumeTask(worker, result); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); @@ -820,7 +804,7 @@ public void test300NarrowQueryOneWorkerTask() throws Exception { PrismAsserts.assertQueriesEquivalent("Wrong query #2", q2, qe.get(1)); PrismAsserts.assertQueriesEquivalent("Wrong query #3", q3, qe.get(2)); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java index 1b3a2913d9a..3f64363305a 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java @@ -9,8 +9,6 @@ import static java.util.Collections.singleton; import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.util.List; import javax.annotation.PostConstruct; import javax.xml.namespace.QName; @@ -48,48 +46,44 @@ public class TestWorkersManagement extends AbstractTaskManagerTest { @Autowired private WorkStateManager workStateManager; @Autowired private CacheConfigurationManager cacheConfigurationManager; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/workers/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/workers/task-" + getTestNumber() + "-" + subId + ".xml"; } @SuppressWarnings("unused") - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private String taskFilename() { + return taskFilename("0"); } - private static String taskOid(String testName, String subId) { - return "44444444-2222-2222-2223-" + testNumber(testName) + subId + "00000000"; + private String taskOid(String subId) { + return "44444444-2222-2222-2223-" + getTestNumber() + subId + "00000000"; } @SuppressWarnings("unused") - private static String taskOid(String test) { - return taskOid(test, "0"); - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid() { + return taskOid("0"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); + protected String workerTaskFilename() { + return taskFilename("w"); } @NotNull - private String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); + private String coordinatorTaskFilename() { + return taskFilename("c"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); + protected String workerTaskOid() { + return taskOid("w"); } @NotNull - private String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); + private String coordinatorTaskOid() { + return taskOid("c"); } @PostConstruct @@ -110,21 +104,20 @@ public void test000Integrity() { @Test public void test100CreateWorkersSingle() throws Exception { - final String TEST_NAME = "test100CreateWorkersSingle"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); workBucketsTaskHandler.resetBeforeTest(); workBucketsTaskHandler.setDelayProcessor(DEFAULT_SLEEP_INTERVAL); // WHEN - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); + addObjectFromFile(coordinatorTaskFilename()); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); try { waitForTaskProgress(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); List workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -148,7 +141,7 @@ public void test100CreateWorkersSingle() throws Exception { // THEN waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -171,23 +164,22 @@ private void displayBucketOpStatistics(String label, Task task) throws SchemaExc @Test public void test110CreateWorkersRecurring() throws Exception { - final String TEST_NAME = "test110CreateWorkersRecurring"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); workBucketsTaskHandler.resetBeforeTest(); workBucketsTaskHandler.setDelayProcessor(DEFAULT_SLEEP_INTERVAL); // (1) ------------------------------------------------------------------------------------ WHEN (import task) when("1: import task"); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + addObjectFromFile(coordinatorTaskFilename()); + String coordinatorTaskOid = coordinatorTaskOid(); try { // THEN (worker is created and executed) then("1: import task"); waitForTaskProgress(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); List workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -208,7 +200,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (worker is still present and executed) then("2: wait for coordinator next run"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -225,7 +217,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("3: suspend the tree while work is done"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); Task worker = workers.get(0); @@ -250,7 +242,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are resumed) then("4: resume the tree"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -272,7 +264,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("5: suspend the tree while worker is executing"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -297,7 +289,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("6: resume after 2nd suspend"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -321,18 +313,17 @@ public void test110CreateWorkersRecurring() throws Exception { @Test public void test200SimplePartitioning() throws Exception { - final String TEST_NAME = "test200SimplePartitioning"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); partitionedWorkBucketsTaskHandler.resetBeforeTest(); partitionedWorkBucketsTaskHandler.setEnsureSingleRunner(true); partitionedWorkBucketsTaskHandler.setDelayProcessor(1000L); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "r")); + addObjectFromFile(taskFilename("r")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "r"); + String masterTaskOid = taskOid("r"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); @@ -371,18 +362,17 @@ public void test200SimplePartitioning() throws Exception { @Test public void test210PartitioningToWorkersSingleBucket() throws Exception { - final String TEST_NAME = "test210PartitioningToWorkersSingleBucket"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); partitionedWorkBucketsTaskHandler.resetBeforeTest(); partitionedWorkBucketsTaskHandler.setEnsureSingleRunner(true); partitionedWorkBucketsTaskHandler.setDelayProcessor(1000L); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "r")); + addObjectFromFile(taskFilename("r")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "r"); + String masterTaskOid = taskOid("r"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); @@ -436,17 +426,16 @@ public void test210PartitioningToWorkersSingleBucket() throws Exception { @Test public void test220PartitioningToWorkersMoreBuckets() throws Exception { - final String TEST_NAME = "test220PartitioningToWorkersMoreBuckets"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); partitionedWorkBucketsTaskHandler.resetBeforeTest(); partitionedWorkBucketsTaskHandler.setDelayProcessor(50L); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "r")); + addObjectFromFile(taskFilename("r")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "r"); + String masterTaskOid = taskOid("r"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java index cda56d91940..514bf27c05c 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java @@ -28,6 +28,9 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; +/** + * Mixin providing common methods/utilities for Active Directory (AD) related tests. + */ public interface AdTestMixin extends MidpointTestMixin { String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java index 222f11d87f7..7bfdded0f3a 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java @@ -8,8 +8,6 @@ import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.io.File; import java.util.ArrayList; import java.util.List; @@ -19,15 +17,12 @@ import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.task.api.Task; - import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; import org.apache.cxf.jaxrs.client.WebClient; import org.testng.AssertJUnit; import org.testng.annotations.Test; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.Referencable; import com.evolveum.midpoint.prism.crypto.EncryptionException; @@ -39,6 +34,7 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; +import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; @@ -54,18 +50,18 @@ public abstract class TestAbstractRestService extends RestServiceInitializer { -// protected static final File BASE_DIR = new File("src/test/resources"); + // protected static final File BASE_DIR = new File("src/test/resources"); protected static final File BASE_REQ_DIR = new File("src/test/resources/req/"); // REST, reader and adder authorization - public static final String USER_DARTHADDER_FILE = "user-darthadder"; - public static final String USER_DARTHADDER_OID = "1696229e-d90a-11e4-9ce6-001e8c717e5b"; - public static final String USER_DARTHADDER_USERNAME = "darthadder"; - public static final String USER_DARTHADDER_PASSWORD = "Iamy0urUncle"; + public static final String USER_DARTHADDER_FILE = "user-darthadder"; + public static final String USER_DARTHADDER_OID = "1696229e-d90a-11e4-9ce6-001e8c717e5b"; + public static final String USER_DARTHADDER_USERNAME = "darthadder"; + public static final String USER_DARTHADDER_PASSWORD = "Iamy0urUncle"; - // Authorizations, but no password - public static final String USER_NOPASSWORD_FILE = "user-nopassword"; - public static final String USER_NOPASSWORD_USERNAME = "nopassword"; + // Authorizations, but no password + public static final String USER_NOPASSWORD_FILE = "user-nopassword"; + public static final String USER_NOPASSWORD_USERNAME = "nopassword"; public static final String ROLE_ADDER_FILE = "role-adder"; @@ -123,23 +119,18 @@ public abstract class TestAbstractRestService extends RestServiceInitializer { private static final String MODIFICATION_FORCE_PASSWORD_CHANGE = "modification-force-password-change"; private static final String EXECUTE_CREDENTIAL_RESET = "execute-credential-reset"; - protected abstract File getRepoFile(String fileBaseName); protected abstract File getRequestFile(String fileBaseName); private static final String NS_SECURITY_QUESTION_ANSWER = "http://midpoint.evolveum.com/xml/ns/public/security/question-2"; public static final String QUESTION_ID = QNameUtil.qNameToUri(new QName(NS_SECURITY_QUESTION_ANSWER, "q001")); - - public TestAbstractRestService() { super(); } @Test public void test001GetUserAdministrator() { - final String TEST_NAME = "test001GetUserAdministrator"; - WebClient client = prepareClient(); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -161,8 +152,6 @@ public void test001GetUserAdministrator() { @Test public void test002GetNonExistingUser() { - final String TEST_NAME = "test002GetNonExistingUser"; - WebClient client = prepareClient(); client.path("/users/12345"); @@ -185,8 +174,6 @@ public void test002GetNonExistingUser() { @Test public void test003GetNoAuthHeaders() { - final String TEST_NAME = "test003GetNoAuthHeaders"; - WebClient client = prepareClient(null, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -205,8 +192,6 @@ public void test003GetNoAuthHeaders() { @Test public void test004GetAuthBadUsernameNullPassword() { - final String TEST_NAME = "test004GetAuthBadUsernameNullPassword"; - WebClient client = prepareClient("NoSUCHuser", null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -225,8 +210,6 @@ public void test004GetAuthBadUsernameNullPassword() { @Test public void test005GetAuthBadUsernameEmptyPassword() { - final String TEST_NAME = "test005GetAuthBadUsernameEmptyPassword"; - WebClient client = prepareClient("NoSUCHuser", ""); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -245,8 +228,6 @@ public void test005GetAuthBadUsernameEmptyPassword() { @Test public void test006GetAuthBadUsernameBadPassword() { - final String TEST_NAME = "test006GetAuthBadUsernameBadPassword"; - WebClient client = prepareClient("NoSUCHuser", "NoSuchPassword"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -265,8 +246,6 @@ public void test006GetAuthBadUsernameBadPassword() { @Test public void test007GetAuthNoPassword() { - final String TEST_NAME = "test007GetAuthNoPassword"; - WebClient client = prepareClient(USER_ADMINISTRATOR_USERNAME, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -285,8 +264,6 @@ public void test007GetAuthNoPassword() { @Test public void test016GetAuthBadPassword() { - final String TEST_NAME = "test016GetAuthBadPassword"; - WebClient client = prepareClient(USER_ADMINISTRATOR_USERNAME, "forgot"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -305,8 +282,6 @@ public void test016GetAuthBadPassword() { @Test public void test017GetUnauthorizedUser() { - final String TEST_NAME = "test017GetUnauthorizedUser"; - WebClient client = prepareClient(USER_NOBODY_USERNAME, USER_NOBODY_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -325,8 +300,6 @@ public void test017GetUnauthorizedUser() { @Test public void test018GetUserAdministratorByCyclops() { - final String TEST_NAME = "test018GetUserAdministratorByCyclops"; - WebClient client = prepareClient(USER_CYCLOPS_USERNAME, USER_CYCLOPS_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -345,8 +318,6 @@ public void test018GetUserAdministratorByCyclops() { @Test public void test019GetUserAdministratorBySomebody() { - final String TEST_NAME = "test019GetUserAdministratorBySomebody"; - WebClient client = prepareClient(USER_SOMEBODY_USERNAME, USER_SOMEBODY_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -369,9 +340,7 @@ public void test019GetUserAdministratorBySomebody() { } @Test - public void test102AddUserTemplate() throws Exception { - final String TEST_NAME = "test102AddUserTemplate"; - + public void test102AddUserTemplate() { WebClient client = prepareClient(); client.path("/objectTemplates/"); @@ -392,9 +361,7 @@ public void test102AddUserTemplate() throws Exception { } @Test - public void test103AddUserBadTargetCollection() throws Exception { - final String TEST_NAME = "test103AddUserBadTargetCollection"; - + public void test103AddUserBadTargetCollection() { WebClient client = prepareClient(); client.path("/objectTemplates"); @@ -419,8 +386,6 @@ public void test103AddUserBadTargetCollection() throws Exception { @Test public void test104AddAccountRawResourceDoesNotExist() throws Exception { - final String TEST_NAME = "test104AddAccountRaw"; - WebClient client = prepareClient(); client.path("/shadows"); client.query("options", "raw"); @@ -437,7 +402,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { assertStatus(response, 240); OperationResult addResult = traceResponse(response); assertNotNull("Expected operation result in the response, but nothing in the body", addResult); - assertEquals("Unexpected status of the operation result. Expected "+ OperationResultStatus.HANDLED_ERROR + ", but was " + addResult.getStatus(), addResult.getStatus(), OperationResultStatus.HANDLED_ERROR); + assertEquals("Unexpected status of the operation result. Expected " + OperationResultStatus.HANDLED_ERROR + ", but was " + addResult.getStatus(), addResult.getStatus(), OperationResultStatus.HANDLED_ERROR); OperationResult parentResult = new OperationResult("get"); try { @@ -458,9 +423,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { } @Test - public void test120AddRoleAdder() throws Exception { - final String TEST_NAME = "test120AddRoleAdder"; - + public void test120AddRoleAdder() { WebClient client = prepareClient(); client.path("/roles"); @@ -480,9 +443,7 @@ public void test120AddRoleAdder() throws Exception { } @Test - public void test121AddUserDarthAdder() throws Exception { - final String TEST_NAME = "test121AddUserDarthAdder"; - + public void test121AddUserDarthAdder() { WebClient client = prepareClient(); client.path("/users"); @@ -502,9 +463,7 @@ public void test121AddUserDarthAdder() throws Exception { } @Test - public void test122AddRoleModifierAsDarthAdder() throws Exception { - final String TEST_NAME = "test122AddRoleModifierAsDarthAdder"; - + public void test122AddRoleModifierAsDarthAdder() { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/roles"); @@ -525,10 +484,8 @@ public void test122AddRoleModifierAsDarthAdder() throws Exception { @Test public void test123DarthAdderAssignModifierHimself() throws Exception { - final String TEST_NAME = "test123DarthAdderAssignModifierHimself"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -551,10 +508,8 @@ public void test123DarthAdderAssignModifierHimself() throws Exception { @Test public void test124DarthAdderAssignModifierByAdministrator() throws Exception { - final String TEST_NAME = "test124DarthAdderAssignModifierByAdministrator"; - WebClient client = prepareClient(); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -577,10 +532,8 @@ public void test124DarthAdderAssignModifierByAdministrator() throws Exception { @Test public void test130DarthAdderDisableHimself() throws Exception { - final String TEST_NAME = "test130DarthAdderDisableHimself"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -603,8 +556,6 @@ public void test130DarthAdderDisableHimself() throws Exception { @Test public void test131GetUserAdministratorByDarthAdder() { - final String TEST_NAME = "test131GetUserAdministratorByDarthAdder"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -624,10 +575,8 @@ public void test131GetUserAdministratorByDarthAdder() { @Test public void test132DarthAdderEnableByAdministrator() throws Exception { - final String TEST_NAME = "test132DarthAdderEnableByAdministrator"; - WebClient client = prepareClient(); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -650,8 +599,6 @@ public void test132DarthAdderEnableByAdministrator() throws Exception { @Test public void test133GetUserAdministratorByDarthAdder() { - final String TEST_NAME = "test133GetUserAdministratorByDarthAdder"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -672,9 +619,7 @@ public void test133GetUserAdministratorByDarthAdder() { } @Test - public void test135AddUserNopasswordAsDarthAdder() throws Exception { - final String TEST_NAME = "test135AddUserNopasswordAsDarthAdder"; - + public void test135AddUserNopasswordAsDarthAdder() { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users"); @@ -695,8 +640,6 @@ public void test135AddUserNopasswordAsDarthAdder() throws Exception { @Test public void test140GetUserAdministratorByNopassword() { - final String TEST_NAME = "test140GetUserAdministratorByNopassword"; - WebClient client = prepareClient(USER_NOPASSWORD_USERNAME, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -716,8 +659,6 @@ public void test140GetUserAdministratorByNopassword() { @Test public void test141GetUserAdministratorByNopasswordBadPassword() { - final String TEST_NAME = "test140GetUserAdministratorByNopassword"; - WebClient client = prepareClient(USER_NOPASSWORD_USERNAME, "bad"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -737,8 +678,6 @@ public void test141GetUserAdministratorByNopasswordBadPassword() { @Test public void test200searchAllUsers() { - final String TEST_NAME = "test200searchAllUsers"; - WebClient client = prepareClient(); client.path("/users/search"); @@ -758,9 +697,7 @@ public void test200searchAllUsers() { } @Test - public void test401AddUserTemplateOverwrite() throws Exception { - final String TEST_NAME = "test401AddUserTemplateOverwrite"; - + public void test401AddUserTemplateOverwrite() { WebClient client = prepareClient(); client.path("/objectTemplates"); client.query("options", "overwrite"); @@ -792,9 +729,7 @@ public void test401AddUserTemplateOverwrite() throws Exception { * MID-4899 */ @Test - public void test410AddFunctionLibraryHello() throws Exception { - final String TEST_NAME = "test410AddFunctionLibraryHello"; - + public void test410AddFunctionLibraryHello() { WebClient client = prepareClient(); client.path("/functionLibraries"); client.query("options", "overwrite"); @@ -824,8 +759,6 @@ public void test410AddFunctionLibraryHello() throws Exception { @Test public void test412GetFunctionLibraryHello() { - final String TEST_NAME = "test412GetFunctionLibraryHello"; - WebClient client = prepareClient(); client.path("/functionLibraries/" + FUNCTION_LIBRARY_HELLO_OID); @@ -852,9 +785,7 @@ public void test412GetFunctionLibraryHello() { } @Test - public void test501generateValue() throws Exception { - final String TEST_NAME = "test501generateValue"; - + public void test501generateValue() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -876,9 +807,7 @@ public void test501generateValue() throws Exception { } @Test - public void test502generateValueBadPath() throws Exception { - final String TEST_NAME = "test502generateValueBadPath"; - + public void test502generateValueBadPath() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -898,9 +827,7 @@ public void test502generateValueBadPath() throws Exception { } @Test - public void test503generateValueExecute() throws Exception { - final String TEST_NAME = "test503generateValueExecute"; - + public void test503generateValueExecute() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -925,11 +852,9 @@ public void test503generateValueExecute() throws Exception { } @Test - public void test504checkGeneratedValue() throws Exception { - final String TEST_NAME = "test503generateValueExecute"; - + public void test504checkGeneratedValue() { WebClient client = prepareClient(); - client.path("/users/" + USER_DARTHADDER_OID ); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -946,9 +871,7 @@ public void test504checkGeneratedValue() throws Exception { } @Test - public void test505generatePasswordExecute() throws Exception { - final String TEST_NAME = "test505generatePasswordExecute"; - + public void test505generatePasswordExecute() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -972,9 +895,7 @@ public void test505generatePasswordExecute() throws Exception { } @Test - public void test506generateHonorificPrefixNameExecute() throws Exception { - final String TEST_NAME = "test506generateHonorificPrefixNameExecute"; - + public void test506generateHonorificPrefixNameExecute() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -998,11 +919,11 @@ public void test506generateHonorificPrefixNameExecute() throws Exception { //TODO assert changed items } - private OperationResult traceResponse(Response response) throws SchemaException { + private OperationResult traceResponse(Response response) { return traceResponse(response, false); } - private OperationResult traceResponse(Response response, boolean assertMessages) throws SchemaException { + private OperationResult traceResponse(Response response, boolean assertMessages) { if (response.getStatus() != 200 && response.getStatus() != 201 && response.getStatus() != 204) { LOGGER.info("coverting result"); OperationResultType result = response.readEntity(OperationResultType.class); @@ -1036,11 +957,8 @@ private void assertLocalizableMessage(LocalizableMessageType localizableMessage) LOGGER.info("localizable message: " + localizableMessage); } - @Test - public void test510validateValueExplicit() throws Exception { - final String TEST_NAME = "test510validateValueExplicit"; - + public void test510validateValueExplicit() { WebClient client = prepareClient(); client.path("/rpc/validate"); @@ -1062,9 +980,7 @@ public void test510validateValueExplicit() throws Exception { } @Test - public void test511validateValueExplicitConflict() throws Exception { - final String TEST_NAME = "test511validateValueExplicitConflict"; - + public void test511validateValueExplicitConflict() { WebClient client = prepareClient(); client.path("/rpc/validate"); @@ -1079,16 +995,13 @@ public void test511validateValueExplicitConflict() throws Exception { assertEquals("Expected 409 but got " + response.getStatus(), 409, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @Test - public void test512validateValueImplicitSingle() throws Exception { - final String TEST_NAME = "test512validateValueImplicitSingle"; - + public void test512validateValueImplicitSingle() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1102,16 +1015,13 @@ public void test512validateValueImplicitSingle() throws Exception { assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @Test - public void test513validateValueImplicitMulti() throws Exception { - final String TEST_NAME = "test513validateValueImplicitMulti"; - + public void test513validateValueImplicitMulti() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1132,9 +1042,7 @@ public void test513validateValueImplicitMulti() throws Exception { } @Test - public void test514validateValueImplicitMultiConflict() throws Exception { - final String TEST_NAME = "test514validateValueImplicitMultiConflict"; - + public void test514validateValueImplicitMultiConflict() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1154,11 +1062,8 @@ public void test514validateValueImplicitMultiConflict() throws Exception { getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - @Test - public void test515validatePasswordHistoryConflict() throws Exception { - final String TEST_NAME = "test515validatePasswordHistoryConflict"; - + public void test515validatePasswordHistoryConflict() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1180,9 +1085,7 @@ public void test515validatePasswordHistoryConflict() throws Exception { } @Test - public void test516validateValueExplicitNoValuePolicy() throws Exception { - final String TEST_NAME = "test516validateValueExplicitNoValuePolicy"; - + public void test516validateValueExplicitNoValuePolicy() { WebClient client = prepareClient(); client.path("/rpc/validate"); @@ -1204,9 +1107,7 @@ public void test516validateValueExplicitNoValuePolicy() throws Exception { } @Test - public void test517generateValueExplicit() throws Exception { - final String TEST_NAME = "test517generateValueExplicit"; - + public void test517generateValueExplicit() { WebClient client = prepareClient(); client.path("/rpc/generate"); @@ -1229,8 +1130,6 @@ public void test517generateValueExplicit() throws Exception { @Test public void test518validateValueImplicitPassword() throws Exception { - final String TEST_NAME = "test518validateValueImplicitPassword"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject secPolicyNoHistory = parseObject(SECURITY_POLICY_NO_HISTORY); @@ -1253,8 +1152,6 @@ public void test518validateValueImplicitPassword() throws Exception { display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - }catch (Exception ex) { - throw ex; } finally { PrismObject secPolicy = parseObject(SECURITY_POLICY); addObject(secPolicy, ModelExecuteOptions.createOverwrite(), task, result); @@ -1263,8 +1160,6 @@ public void test518validateValueImplicitPassword() throws Exception { @Test public void test520GeneratePasswordsUsingScripting() throws Exception { - final String TEST_NAME = "test520GeneratePasswordsUsingScripting"; - WebClient client = prepareClient(); client.path("/rpc/executeScript"); @@ -1317,8 +1212,6 @@ public void test520GeneratePasswordsUsingScripting() throws Exception { @Test public void test530ModifyValidToUsingScripting() throws Exception { - final String TEST_NAME = "test530ModifyValidToUsingScripting"; - WebClient client = prepareClient(); client.path("/rpc/executeScript"); @@ -1449,8 +1342,6 @@ private List> extractI */ @Test public void test600ModifySecurityQuestionReplaceAnswerId1Existing() throws Exception { - final String TEST_NAME = "test600ModifySecurityQuestionReplaceAnswerId1Existing"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1493,8 +1384,6 @@ private UserType getUserRest(String oid) { */ @Test public void test602ModifySecurityQuestionReplaceTwoAnswersExisting() throws Exception { - final String TEST_NAME = "test602ModifySecurityQuestionReplaceTwoAnswersExisting"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1529,8 +1418,6 @@ public void test602ModifySecurityQuestionReplaceTwoAnswersExisting() throws Exce */ @Test public void test604ModifySecurityQuestionReplaceNoAnswer() throws Exception { - final String TEST_NAME = "test604ModifySecurityQuestionReplaceNoAnswer"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1565,8 +1452,6 @@ public void test604ModifySecurityQuestionReplaceNoAnswer() throws Exception { */ @Test public void test606ModifySecurityQuestionReplaceAnswer() throws Exception { - final String TEST_NAME = "test606ModifySecurityQuestionReplaceAnswer"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1597,9 +1482,7 @@ public void test606ModifySecurityQuestionReplaceAnswer() throws Exception { } @Test - public void test607validateSecurityAnswerCheckExpressionFail() throws Exception { - final String TEST_NAME = "test607validateSecurityAnswerCheckExpressionFail"; - + public void test607validateSecurityAnswerCheckExpressionFail() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1614,16 +1497,13 @@ public void test607validateSecurityAnswerCheckExpressionFail() throws Exception assertEquals("Expected 409 but got " + response.getStatus(), 409, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @Test - public void test608validateSecurityAnswerCheckExpression() throws Exception { - final String TEST_NAME = "test607validateSecurityAnswerCheckExpression"; - + public void test608validateSecurityAnswerCheckExpression() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1637,7 +1517,6 @@ public void test608validateSecurityAnswerCheckExpression() throws Exception { assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -1671,7 +1550,7 @@ private void assertSecurityQuestionAnswers(UserType userType, String expectedAns assertEquals("Unexpected security question 001 answer in " + userType, expectedAnswer001, decrypted); } - private void assertSecurityQuestionNoAnswer(UserType userType) throws EncryptionException { + private void assertSecurityQuestionNoAnswer(UserType userType) { CredentialsType credentials = userType.getCredentials(); assertNotNull("No credentials in user. Something is wrong.", credentials); SecurityQuestionsCredentialsType securityQuestions = credentials.getSecurityQuestions(); @@ -1682,21 +1561,19 @@ private void assertSecurityQuestionNoAnswer(UserType userType) throws Encryption private void assertSecurityQuestionAnswer(List secQuestionAnswers, String anwerUriLocalPart, String expectedAnswer) throws EncryptionException { - for (SecurityQuestionAnswerType secQuestionAnswer: secQuestionAnswers) { + for (SecurityQuestionAnswerType secQuestionAnswer : secQuestionAnswers) { if (secQuestionAnswer.getQuestionIdentifier().equals(QNameUtil.qNameToUri( new QName(NS_SECURITY_QUESTION_ANSWER, anwerUriLocalPart)))) { String decrypted = getPrismContext().getDefaultProtector().decryptString(secQuestionAnswer.getQuestionAnswer()); - assertEquals("Unexpected security question "+anwerUriLocalPart+" answer", expectedAnswer, decrypted); + assertEquals("Unexpected security question " + anwerUriLocalPart + " answer", expectedAnswer, decrypted); return; } } - AssertJUnit.fail("Security question answer "+anwerUriLocalPart+" not found"); + AssertJUnit.fail("Security question answer " + anwerUriLocalPart + " not found"); } @Test - public void test610ModifyPasswordForceChange() throws Exception { - final String TEST_NAME = "test610ModifyPasswordForceChange"; - + public void test610ModifyPasswordForceChange() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1711,7 +1588,6 @@ public void test610ModifyPasswordForceChange() throws Exception { assertEquals("Expected 204 but got " + response.getStatus(), 204, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -1735,8 +1611,6 @@ public void test610ModifyPasswordForceChange() throws Exception { @Test public void test612ResetPassword() throws Exception { - final String TEST_NAME = "test612ResetPassword"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/credential"); @@ -1754,7 +1628,6 @@ public void test612ResetPassword() throws Exception { assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -1782,8 +1655,6 @@ public void test612ResetPassword() throws Exception { @Test // MID-4928 public void test650SuspendNonExistingTask() { - final String TEST_NAME = "test650SuspendNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456/suspend"); @@ -1798,8 +1669,6 @@ public void test650SuspendNonExistingTask() { @Test // MID-4928 public void test652SuspendWrongObject() { - final String TEST_NAME = "test652SuspendWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002/suspend"); @@ -1814,8 +1683,6 @@ public void test652SuspendWrongObject() { @Test // MID-4928 public void test660ResumeNonExistingTask() { - final String TEST_NAME = "test660ResumeNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456/resume"); @@ -1830,8 +1697,6 @@ public void test660ResumeNonExistingTask() { @Test // MID-4928 public void test662ResumeWrongObject() { - final String TEST_NAME = "test662ResumeWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002/resume"); @@ -1846,8 +1711,6 @@ public void test662ResumeWrongObject() { @Test // MID-4928 public void test670ScheduleNonExistingTask() { - final String TEST_NAME = "test670ScheduleNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456/run"); @@ -1862,8 +1725,6 @@ public void test670ScheduleNonExistingTask() { @Test // MID-4928 public void test672ScheduleWrongObject() { - final String TEST_NAME = "test672ScheduleWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002/run"); @@ -1878,8 +1739,6 @@ public void test672ScheduleWrongObject() { @Test // MID-4928 public void test680DeleteNonExistingTask() { - final String TEST_NAME = "test680DeleteNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456"); @@ -1894,8 +1753,6 @@ public void test680DeleteNonExistingTask() { @Test // MID-4928 public void test682DeleteWrongObject() { - final String TEST_NAME = "test682DeleteWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002"); @@ -1908,18 +1765,10 @@ public void test682DeleteWrongObject() { assertEquals("Expected 400 but got " + response.getStatus(), 400, response.getStatus()); } - - - private WebClient prepareClient() { return prepareClient(USER_ADMINISTRATOR_USERNAME, USER_ADMINISTRATOR_PASSWORD); } - private void assertNoEmptyResponse(Response response) { - String respBody = response.readEntity(String.class); - assertTrue("Unexpected reposponse: "+respBody, StringUtils.isBlank(respBody)); - } - private void displayResponse(Response response) { LOGGER.info("response : {} ", response.getStatus()); LOGGER.info("response : {} ", response.getStatusInfo().getReasonPhrase()); diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java index 9eaa647129a..565ce45d9e7 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java @@ -68,8 +68,6 @@ public void initSystem(Task initTask, OperationResult result) throws Exception { @Test public void test001getUserSelfBySomebody() { - final String TEST_NAME = "test001getUserSelfBySomebody"; - WebClient client = prepareClient(USER_SOMEBODY_OID); client.path("/self/"); @@ -91,8 +89,6 @@ public void test001getUserSelfBySomebody() { @Test public void test002getUserSelfByEgoist() { - final String TEST_NAME = "test002getUserSelfByEgoist"; - WebClient client = prepareClient(USER_EGOIST_OID); client.path("/self/"); @@ -118,8 +114,6 @@ public void test002getUserSelfByEgoist() { */ @Test public void test003getUserAdministratorByEgoist() { - final String TEST_NAME = "test003getUserAdministratorByEgoist"; - WebClient client = prepareClient(USER_EGOIST_OID); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -141,8 +135,6 @@ public void test003getUserAdministratorByEgoist() { */ @Test public void test004getUserSelfByHead() { - final String TEST_NAME = "test004getUserSelfByHead"; - WebClient client = prepareClient(null); client.path("/self"); @@ -168,8 +160,6 @@ public void test004getUserSelfByHead() { */ @Test public void test005getUserSelfByProxyHead() { - final String TEST_NAME = "test005getUserSelfByProxyHead"; - WebClient client = prepareClient(USER_HEAD_OID); client.path("/self"); diff --git a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java index 6bbdc33cff3..e1d51dcf131 100644 --- a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java +++ b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java @@ -340,7 +340,6 @@ public static void stopResources() throws Exception { */ @Test public void test000Integrity() throws Exception { - final String TEST_NAME = "test000Integrity"; assertNotNull(modelWeb); assertNotNull(modelService); assertNotNull(repositoryService); @@ -380,11 +379,9 @@ public void test000Integrity() throws Exception { * Repeat self-test when we have all the dependencies on the classpath. */ @Test - public void test001SelfTests() throws Exception { - final String TEST_NAME = "test001SelfTests"; - + public void test001SelfTests() { // GIVEN - Task task = taskManager.createTaskInstance(TestSanity.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); // WHEN OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task); @@ -409,8 +406,6 @@ public void test001SelfTests() throws Exception { */ @Test public void test001TestConnectionOpenDJ() throws Exception { - final String TEST_NAME = "test001TestConnectionOpenDJ"; - // GIVEN try { assertNoRepoCache(); @@ -469,8 +464,6 @@ private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaExc /** * Checks if the resource is internally consistent, if it has everything it should have. - * - * @throws SchemaException */ private void checkOpenDjResource(ResourceType resource, String source) throws SchemaException { assertNotNull("Resource from " + source + " is null", resource); @@ -584,10 +577,8 @@ private void checkOpenResourceConfiguration(PrismObject resource, @Test public void test002AddDerbyResource() throws Exception { - final String TEST_NAME = "test002AddDerbyResource"; - // GIVEN - OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); checkRepoOpenDjResource(); assertNoRepoCache(); @@ -737,7 +728,7 @@ public void test003TestConnectionDerby() throws Exception { @Test public void test004Capabilities() - throws ObjectNotFoundException, CommunicationException, SchemaException, FaultMessage { + throws ObjectNotFoundException, SchemaException, FaultMessage { // GIVEN checkRepoOpenDjResource(); @@ -842,8 +833,7 @@ public void test006reimportResourceDummy() throws Exception { fail("Expected object already exists exception, but haven't got one."); } catch (FaultMessage ex) { - logger.info("fault {}", ex.getFaultInfo()); - logger.info("fault {}", ex.getCause()); + logger.info("fault {}", ex.getFaultInfo(), ex.getCause()); if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) { // this is OK, we expect this } else { @@ -864,8 +854,6 @@ public void test006reimportResourceDummy() throws Exception { */ @Test public void test010AddUser() throws Exception { - final String TEST_NAME = "test010AddUser"; - // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); @@ -915,7 +903,6 @@ public void test010AddUser() throws Exception { */ @Test public void test013AddOpenDjAccountToUser() throws Exception { - final String TEST_NAME = "test013AddOpenDjAccountToUser"; try { // GIVEN checkRepoOpenDjResource(); @@ -1033,7 +1020,7 @@ public void test013AddOpenDjAccountToUser() throws Exception { assertNotNull("Activation is null (model)", modelShadow.getActivation()); assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); } catch (Exception ex) { - logger.info("ERROR: {}", ex); + logger.info("ERROR", ex); throw ex; } @@ -1160,7 +1147,7 @@ public void test014AddDerbyAccountToUser() throws IOException, JAXBException, Fa } @Test - public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException, JAXBException { + public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException { // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); @@ -1244,7 +1231,6 @@ public boolean handle(PrismObject prismObject, OperationResult paren */ @Test public void test020ModifyUser() throws Exception { - final String TEST_NAME = "test020ModifyUser"; // GIVEN assertNoRepoCache(); @@ -1341,7 +1327,6 @@ private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) */ @Test public void test022ChangeUserPassword() throws Exception { - final String TEST_NAME = "test022ChangeUserPassword"; // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -1362,8 +1347,6 @@ public void test022ChangeUserPassword() throws Exception { */ @Test public void test023ChangeUserPasswordJAXB() throws Exception { - final String TEST_NAME = "test023ChangeUserPasswordJAXB"; - // GIVEN final String NEW_PASSWORD = "abandonSHIP"; Document doc = ModelClientUtil.getDocumnent(); @@ -1391,7 +1374,7 @@ public void test023ChangeUserPasswordJAXB() throws Exception { assertUserPasswordChange(NEW_PASSWORD, result); } - private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { + private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); @@ -1444,17 +1427,15 @@ private void assertUserPasswordChange(String expectedUserPassword, OperationResu @Test public void test027ModifyAccountDj() throws Exception { - final String TEST_NAME = "test027ModifyAccountDj"; - testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck"); + testModifyAccountDjRoomNumber(REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck"); } @Test public void test028ModifyAccountDjExplicitType() throws Exception { - final String TEST_NAME = "test028ModifyAccountDjExplicitType"; - testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck"); + testModifyAccountDjRoomNumber(REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck"); } - public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, String expectedVal) throws Exception { + public void testModifyAccountDjRoomNumber(File reqFile, String expectedVal) throws Exception { // GIVEN assertNoRepoCache(); @@ -1489,7 +1470,6 @@ public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, @Test public void test029ModifyAccountDjBadPath() throws Exception { - final String TEST_NAME = "test029ModifyAccountDjBadPath"; // GIVEN assertNoRepoCache(); @@ -1537,9 +1517,7 @@ public void test029ModifyAccountDjBadPath() throws Exception { */ @Test public void test030DisableUser() throws Exception { - final String TEST_NAME = "test030DisableUser"; // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class); @@ -1649,9 +1627,7 @@ public void test030DisableUser() throws Exception { */ @Test public void test031EnableUser() throws Exception { - final String TEST_NAME = "test031EnableUser"; // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class); assertNoRepoCache(); @@ -1848,9 +1824,7 @@ private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) @Test public void test047RenameUser() throws Exception { - final String TEST_NAME = "test047RenameUser"; // GIVEN - assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -1906,13 +1880,9 @@ public void test047RenameUser() throws Exception { /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). - * - * @throws DirectoryException */ @Test public void test048ModifyUserRemoveGivenName() throws Exception { - final String TEST_NAME = "test048ModifyUserRemoveGivenName"; - // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -1967,8 +1937,6 @@ public void test048ModifyUserRemoveGivenName() throws Exception { /** * The user should have an account now. Let's try to delete the user. The * account should be gone as well. - * - * @throws JAXBException */ @Test public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryException { @@ -2015,8 +1983,6 @@ public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryE @Test public void test100AssignRolePirate() throws Exception { - final String TEST_NAME = "test100AssignRolePirate"; - // GIVEN // IMPORTANT! Assignment enforcement is FULL now @@ -2110,8 +2076,6 @@ public void test100AssignRolePirate() throws Exception { @Test public void test101AccountOwnerAfterRole() throws Exception { - final String TEST_NAME = "test101AccountOwnerAfterRole"; - // GIVEN assertNoRepoCache(); @@ -2135,8 +2099,6 @@ public void test101AccountOwnerAfterRole() throws Exception { @Test public void test102AssignRoleCaptain() throws Exception { - final String TEST_NAME = "test102AssignRoleCaptain"; - // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -2215,8 +2177,6 @@ public void test102AssignRoleCaptain() throws Exception { */ @Test public void test103AssignRoleCaptainAgain() throws Exception { - final String TEST_NAME = "test103AssignRoleCaptainAgain"; - // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -2292,10 +2252,7 @@ public void test103AssignRoleCaptainAgain() throws Exception { @Test public void test105ModifyAccount() throws Exception { - final String TEST_NAME = "test105ModifyAccount"; - // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidGuybrushOpendj); @@ -2304,7 +2261,7 @@ public void test105ModifyAccount() throws Exception { OperationResultType result = modifyObjectViaModelWS(objectChange); Task task = taskManager.createTaskInstance(); - OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify"); + OperationResult parentResult = createOperationResult("get after first modify"); PrismObject shadow = modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); assertNotNull("shadow must not be null", shadow); @@ -2375,10 +2332,7 @@ public void test105ModifyAccount() throws Exception { */ @Test public void test104AssignRoleJudge() throws Exception { - final String TEST_NAME = "test104AssignRoleJudge"; - // GIVEN - OperationResultType result = new OperationResultType(); Holder resultHolder = new Holder<>(result); Holder oidHolder = new Holder<>(); @@ -2418,18 +2372,14 @@ public void test104AssignRoleJudge() throws Exception { @Test public void test107UnassignRolePirate() throws Exception { - final String TEST_NAME = "test107UnassignRolePirate"; - // GIVEN - - OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), - result = modifyObjectViaModelWS(objectChange); + OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); @@ -2498,18 +2448,14 @@ public void test107UnassignRolePirate() throws Exception { @Test public void test108UnassignRoleCaptain() throws Exception { - final String TEST_NAME = "test108UnassignRoleCaptain"; - // GIVEN - - OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), - result = modifyObjectViaModelWS(objectChange); + OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); @@ -2583,18 +2529,15 @@ public void test108UnassignRoleCaptain() throws Exception { */ @Test public void test109UnassignRoleCaptainAgain() throws Exception { - final String TEST_NAME = "test109UnassignRoleCaptainAgain"; - // GIVEN - OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), - result = modifyObjectViaModelWS(objectChange); + OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); @@ -2606,7 +2549,6 @@ public void test109UnassignRoleCaptainAgain() throws Exception { // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); - PropertyReferenceListType resolve = new PropertyReferenceListType(); PrismObject repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); @@ -2648,7 +2590,6 @@ public void test109UnassignRoleCaptainAgain() throws Exception { */ @Test public void test300LiveSyncInit() throws Exception { - final String TEST_NAME = "test300LiveSyncInit"; // Now it is the right time to add task definition to the repository // We don't want it there any sooner, as it may interfere with the // previous tests @@ -2660,8 +2601,7 @@ public void test300LiveSyncInit() throws Exception { // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result); @@ -2757,12 +2697,10 @@ public void timeout() { */ @Test public void test301LiveSyncCreate() throws Exception { - final String TEST_NAME = "test301LiveSyncCreate"; // Sync task should be running (tested in previous test), so just create // new LDAP object. - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2796,10 +2734,7 @@ public void test301LiveSyncCreate() throws Exception { @Test public void test302LiveSyncModify() throws Exception { - final String TEST_NAME = "test302LiveSyncModify"; - - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2828,8 +2763,6 @@ public void test302LiveSyncModify() throws Exception { @Test public void test303LiveSyncLink() throws Exception { - final String TEST_NAME = "test303LiveSyncLink"; - // GIVEN assertNoRepoCache(); PrismObject user = PrismTestUtil.parseObject(USER_E_LINK_ACTION_FILE); @@ -2853,8 +2786,7 @@ public void test303LiveSyncLink() throws Exception { when(); //create account for e which should be correlated - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2893,12 +2825,10 @@ public void test303LiveSyncLink() throws Exception { */ @Test public void test304LiveSyncCreateNoLocation() throws Exception { - final String TEST_NAME = "test304LiveSyncCreateNoLocation"; // Sync task should be running (tested in previous test), so just create // new LDAP object. - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2966,9 +2896,7 @@ private Object findSyncTokenObject(Task syncCycle) { */ @Test public void test399LiveSyncCleanup() throws Exception { - final String TEST_NAME = "test399LiveSyncCleanup"; - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.deleteTask(TASK_OPENDJ_SYNC_OID, result); @@ -2977,13 +2905,11 @@ public void test399LiveSyncCleanup() throws Exception { @Test public void test400ImportFromResource() throws Exception { - final String TEST_NAME = "test400ImportFromResource"; // GIVEN checkAllShadows(); assertNoRepoCache(); - OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // Make sure Mr. Gibbs has "l" attribute set to the same value as an outbound expression is setting ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_GIBBS_MODIFY_FILE); @@ -3192,11 +3118,9 @@ private String getUserLocality(UserType user) { @Test public void test420RecomputeUsers() throws Exception { - final String TEST_NAME = "test420RecomputeUsers"; // GIVEN - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); // Assign role to a user, but we do this using a repository instead of model. // The role assignment will not be executed and this created an inconsistent state. @@ -3332,11 +3256,9 @@ public void timeout() { @Test public void test440ReconcileResourceOpenDj() throws Exception { - final String TEST_NAME = "test440ReconcileResourceOpenDj"; // GIVEN - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); // Create LDAP account without an owner. The liveSync is off, so it will not be picked up @@ -3550,7 +3472,6 @@ public void timeout() { @Test public void test480ListResources() throws Exception { - final String TEST_NAME = "test480ListResources"; // GIVEN OperationResultType result = new OperationResultType(); Holder resultHolder = new Holder<>(result); @@ -3672,9 +3593,6 @@ public void test500NotifyChangeCreateAccount() throws Exception { @Test public void test501NotifyChangeModifyAccount() throws Exception { - final String TEST_NAME = "test501NotifyChangeModifyAccount"; - - OperationResult parentResult = createOperationResult(); PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3728,8 +3646,6 @@ public void test501NotifyChangeModifyAccount() throws Exception { @Test public void test502NotifyChangeModifyAccountPassword() throws Exception { - final String TEST_NAME = "test502NotifyChangeModifyAccountPassword"; - PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3784,8 +3700,6 @@ public void test502NotifyChangeModifyAccountPassword() throws Exception { @Test public void test503NotifyChangeDeleteAccount() throws Exception { - final String TEST_NAME = "test503NotifyChangeDeleteAccount"; - PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3978,7 +3892,7 @@ private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnfor assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement); } - private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { + private void checkAllShadows() throws SchemaException { logger.trace("Checking all shadows"); System.out.println("Checking all shadows"); ObjectChecker checker = null; diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java index 65a2d3a6cd0..cc0e25a7b0d 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java @@ -80,8 +80,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ImportAccount() throws Exception { - final String TEST_NAME = "test100ImportAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -104,8 +102,6 @@ public void test100ImportAccount() throws Exception { @Test public void test110AssignJackPirate() throws Exception { - String TEST_NAME = "test110AssignJackPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -164,8 +160,6 @@ public void test110AssignJackPirate() throws Exception { @Test public void test112ModifyActivationJack() throws Exception { - String TEST_NAME = "test112ModifyActivationJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java index 1f95834e186..a111fc2782a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java @@ -90,21 +90,18 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { private static final String SYSTEM_CONFIGURATION_FILENAME = TEST_DIR + "system-configuration.xml"; private static final String ROLE_SUPERUSER_FILENAME = TEST_DIR + "role-superuser.xml"; - private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; private static final String ROLE_LDAP_ADMINS_FILENAME = TEST_DIR + "role-admins.xml"; private static final String ROLE_LDAP_ADMINS_OID = "88888888-8888-8888-8888-000000000009"; private static final String ROLE_LDAP_ADMINS_DN = "cn=admins,ou=groups,dc=example,dc=com"; private static final String SAMPLE_CONFIGURATION_OBJECT_FILENAME = TEST_DIR + "sample-configuration-object.xml"; - private static final String SAMPLE_CONFIGURATION_OBJECT_OID = "c0c010c0-d34d-b33f-f00d-999111111111"; private static final String RESOURCE_OPENDJ_FILENAME = TEST_DIR + "resource-opendj.xml"; private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; private static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "inetOrgPerson"); private static final QName RESOURCE_OPENDJ_GROUP_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "groupOfUniqueNames"); - private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; private static final QName RESOURCE_OPENDJ_SECONDARY_IDENTIFIER = new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME); @@ -232,7 +229,6 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { private static final QName LDAP_ATTRIBUTE_EMPLOYEE_TYPE = new ItemName(MidPointConstants.NS_RI, "employeeType"); private static ResourceType resourceTypeOpenDjrepo; - private static String accountShadowOidOpendj; private String aliceAccountDn; // This will get called from the superclass to init the repository @@ -330,8 +326,6 @@ public void test000Integrity() throws Exception { */ @Test public void test001TestConnectionOpenDJ() throws Exception { - final String TEST_NAME = "test001TestConnectionOpenDJ"; - Task task = taskManager.createTaskInstance(); // GIVEN @@ -348,8 +342,7 @@ public void test001TestConnectionOpenDJ() throws Exception { TestUtil.assertSuccess("testResource has failed", result); - OperationResult opResult = new OperationResult(TestConsistencyMechanism.class.getName() - + "." + TEST_NAME); + OperationResult opResult = createOperationResult(); PrismObject resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult); @@ -390,9 +383,7 @@ public void test001TestConnectionOpenDJ() throws Exception { */ @Test public void test100AddUser() throws Exception { - final String TEST_NAME = "test100AddUser"; - - UserType userType = testAddUserToRepo(TEST_NAME, USER_JACK_FILENAME, USER_JACK_OID); + UserType userType = testAddUserToRepo(USER_JACK_FILENAME); OperationResult repoResult = new OperationResult("getObject"); @@ -428,8 +419,6 @@ public void test110PrepareOpenDjWithJackieAccounts() throws Exception { ReferenceDelta linkRefDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.class, UserType.F_LINK_REF, ObjectTypeUtil.createObjectRef(jackieAccount, SchemaConstants.ORG_DEFAULT).asReferenceValue()); repositoryService.modifyObject(UserType.class, USER_JACK_OID, Arrays.asList(linkRefDelta), parentResult); - OperationResult repoResult = new OperationResult("getObject"); - // Check if user object was modified in the repo assertUserOneAccountRef(USER_JACK_OID); @@ -579,8 +568,8 @@ public void test122AddAccountAlreadyExistUnlinked() throws Exception { String dn = searchResult.getDN().toString(); assertEquals("DN attribute " + dn + " not equals", dn, "uid=wturner,ou=People,dc=example,dc=com"); - testAddUserToRepo("test122AddAccountAlreadyExistUnlinked", USER_WILL_FILENAME, - USER_WILL_OID); + testAddUserToRepo(USER_WILL_FILENAME + ); assertUserNoAccountRef(USER_WILL_OID, parentResult); Task task = taskManager.createTaskInstance(); @@ -744,7 +733,6 @@ public void test130DeleteObjectNotFound() throws Exception { *

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

* HR system has enabled/disabled status. We want to synchronize that status to midPoint, * but we want the information to be delayed by one day. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestDelayedEnable extends AbstractStoryTest { @@ -109,8 +99,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100AddUserMancomb() throws Exception { - final String TEST_NAME = "test100AddUserMancomb"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -139,7 +127,6 @@ public void test100AddUserMancomb() throws Exception { */ @Test public void test102UserMancombTriggerScannerAgain() throws Exception { - final String TEST_NAME = "test102UserMancombTriggerScannerAgain"; displayCurrentTime(); // WHEN @@ -161,8 +148,6 @@ public void test102UserMancombTriggerScannerAgain() throws Exception { */ @Test public void test104UserMancombRecompute() throws Exception { - final String TEST_NAME = "test104UserMancombRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); displayCurrentTime(); @@ -183,20 +168,20 @@ public void test104UserMancombRecompute() throws Exception { private void assertMancombCreated() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D"); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D"); } /** @@ -205,8 +190,6 @@ private void assertMancombCreated() throws Exception { */ @Test public void test110UserMancombRunTriggerScannerDay1() throws Exception { - final String TEST_NAME = "test110UserMancombRunTriggerScannerDay1"; - clockForward("P1D"); // WHEN @@ -228,8 +211,6 @@ public void test110UserMancombRunTriggerScannerDay1() throws Exception { */ @Test public void test112UserMancombRecomputeDay1() throws Exception { - final String TEST_NAME = "test112UserMancombRecomputeDay1"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -251,24 +232,22 @@ public void test112UserMancombRecomputeDay1() throws Exception { private void assertMancombEnabled() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED) .end() - .triggers() + .triggers() .assertNone(); } @Test public void test114UserMancombRunTriggerScannerDay1Again() throws Exception { - final String TEST_NAME = "test114UserMancombRunTriggerScannerDay1Again"; - // WHEN when(); @@ -287,8 +266,6 @@ public void test114UserMancombRunTriggerScannerDay1Again() throws Exception { */ @Test public void test116UserMancombRecomputeDay1Again() throws Exception { - final String TEST_NAME = "test116UserMancombRecomputeDay1Again"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -312,8 +289,6 @@ public void test116UserMancombRecomputeDay1Again() throws Exception { */ @Test public void test120UserMancombHrDisable() throws Exception { - final String TEST_NAME = "test120UserMancombHrDisable"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -337,13 +312,13 @@ public void test120UserMancombHrDisable() throws Exception { private void assertMancombHalfDisabled() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED); } @@ -353,8 +328,6 @@ private void assertMancombHalfDisabled() throws Exception { */ @Test public void test122UserMancombRecompute() throws Exception { - final String TEST_NAME = "test122UserMancombRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -374,8 +347,6 @@ public void test122UserMancombRecompute() throws Exception { @Test public void test124UserMancombDay1TriggerScanner() throws Exception { - final String TEST_NAME = "test124UserMancombDay1TriggerScanner"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -399,8 +370,6 @@ public void test124UserMancombDay1TriggerScanner() throws Exception { */ @Test public void test130UserMancombTriggerScannerDay2() throws Exception { - final String TEST_NAME = "test130UserMancombTriggerScannerDay2"; - clockForward("P1D"); Task task = getTestTask(); @@ -422,13 +391,13 @@ public void test130UserMancombTriggerScannerDay2() throws Exception { private void assertMancombDisabled() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED); } @@ -439,8 +408,6 @@ private void assertMancombDisabled() throws Exception { */ @Test public void test132UserMancombRecomputeDay2() throws Exception { - final String TEST_NAME = "test132UserMancombRecomputeDay2"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -460,8 +427,6 @@ public void test132UserMancombRecomputeDay2() throws Exception { @Test public void test132UserMancombRecomputeDay2Again() throws Exception { - final String TEST_NAME = "test132UserMancombRecomputeDay2Again"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -485,8 +450,6 @@ public void test132UserMancombRecomputeDay2Again() throws Exception { */ @Test public void test140UserMancombRecomputeDay3() throws Exception { - final String TEST_NAME = "test140UserMancombRecomputeDay3"; - clockForward("P1D"); Task task = getTestTask(); @@ -510,8 +473,6 @@ public void test140UserMancombRecomputeDay3() throws Exception { @Test public void test200HrLivesyncTask() throws Exception { - final String TEST_NAME = "test200HrLivesyncTask"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -521,18 +482,16 @@ public void test200HrLivesyncTask() throws Exception { addObject(TASK_DUMMY_HR_FILE, task, result); // THEN - then(); - assertSuccess(result); + then(); + assertSuccess(result); - waitForTaskStart(TASK_DUMMY_HR_OID, true); + waitForTaskStart(TASK_DUMMY_HR_OID, true); - assertCounterIncrement(InternalCounters.TRIGGER_FIRED_COUNT, 0); + assertCounterIncrement(InternalCounters.TRIGGER_FIRED_COUNT, 0); } @Test public void test210HrAddUserGuybrush() throws Exception { - final String TEST_NAME = "test210HrAddUserGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -564,8 +523,6 @@ public void test210HrAddUserGuybrush() throws Exception { @Test public void test212HrUserGuybrushSyncAgain() throws Exception { - final String TEST_NAME = "test212HrUserGuybrushSyncAgain"; - clockForward("PT1H"); Task task = getTestTask(); @@ -587,8 +544,6 @@ public void test212HrUserGuybrushSyncAgain() throws Exception { @Test public void test214HrUserGuybrushRunTriggers() throws Exception { - final String TEST_NAME = "test214HrUserGuybrushRunTriggers"; - clockForward("PT1H"); Task task = getTestTask(); @@ -610,8 +565,6 @@ public void test214HrUserGuybrushRunTriggers() throws Exception { @Test public void test216HrUserGuybrushRecompute() throws Exception { - final String TEST_NAME = "test216HrUserGuybrushRecompute"; - clockForward("PT1H"); Task task = getTestTask(); @@ -633,8 +586,6 @@ public void test216HrUserGuybrushRecompute() throws Exception { @Test public void test218HrUserGuybrushReconcile() throws Exception { - final String TEST_NAME = "test218HrUserGuybrushReconcile"; - clockForward("PT1H"); Task task = getTestTask(); @@ -654,29 +605,27 @@ public void test218HrUserGuybrushReconcile() throws Exception { assertCounterIncrement(InternalCounters.TRIGGER_FIRED_COUNT, 0); } - private UserAsserter assertGuybrushCreated(UserAsserter userAsserter) throws Exception { + private UserAsserter assertGuybrushCreated(UserAsserter userAsserter) { return userAsserter - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D") - .end() + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D") + .end() .end(); } @Test public void test220HrUserGuybrushDay1() throws Exception { - final String TEST_NAME = "test220HrUserGuybrushDay1"; - clockForward("P1D"); // WHEN @@ -694,8 +643,6 @@ public void test220HrUserGuybrushDay1() throws Exception { @Test public void test222HrUserGuybrushDay1SyncAgain() throws Exception { - final String TEST_NAME = "test222HrUserGuybrushDay1SyncAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -715,8 +662,6 @@ public void test222HrUserGuybrushDay1SyncAgain() throws Exception { @Test public void test224HrUserGuybrushDay1TriggerScanAgain() throws Exception { - final String TEST_NAME = "test224HrUserGuybrushDay1TriggerScanAgain"; - clockForward("PT1H"); Task task = getTestTask(); @@ -738,8 +683,6 @@ public void test224HrUserGuybrushDay1TriggerScanAgain() throws Exception { @Test public void test226HrUserGuybrushDay1Recompute() throws Exception { - final String TEST_NAME = "test226HrUserGuybrushDay1Recompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -759,8 +702,6 @@ public void test226HrUserGuybrushDay1Recompute() throws Exception { @Test public void test228HrUserGuybrushDay1Reconcile() throws Exception { - final String TEST_NAME = "test228HrUserGuybrushDay1Reconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -780,25 +721,23 @@ public void test228HrUserGuybrushDay1Reconcile() throws Exception { private void assertGuybrushEnabled() throws Exception { assertUserAfter(userGuybrushOid) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED) .end() - .triggers() + .triggers() .assertNone(); } @Test public void test230HrDisableGuybrush() throws Exception { - final String TEST_NAME = "test230HrDisableGuybrush"; - getDummyResourceHr() - .getAccountByUsername(ACCOUNT_GUYBRUSH_USERNAME) + .getAccountByUsername(ACCOUNT_GUYBRUSH_USERNAME) .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, EXT_HR_STATUS_DISABLED); hrModifyTsStart = clock.currentTimeXMLGregorianCalendar(); @@ -820,8 +759,6 @@ public void test230HrDisableGuybrush() throws Exception { @Test public void test232GuybrushHrSyncAgain() throws Exception { - final String TEST_NAME = "test232GuybrushHrSyncAgain"; - // WHEN when(); @@ -837,8 +774,6 @@ public void test232GuybrushHrSyncAgain() throws Exception { @Test public void test234GuybrushRecompute() throws Exception { - final String TEST_NAME = "test232GuybrushHrSyncAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -858,8 +793,6 @@ public void test234GuybrushRecompute() throws Exception { @Test public void test236GuybrushReconcile() throws Exception { - final String TEST_NAME = "test236GuybrushReconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -879,8 +812,6 @@ public void test236GuybrushReconcile() throws Exception { @Test public void test238GuybrushrunTriggersAgain() throws Exception { - final String TEST_NAME = "test238GuybrushrunTriggersAgain"; - clockForward("PT1H"); // WHEN @@ -898,25 +829,23 @@ public void test238GuybrushrunTriggersAgain() throws Exception { private void assertGuybrushHalfDisabled() throws Exception { assertUserAfter(userGuybrushOid) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFutureBetween(hrModifyTsStart, hrModifyTsEnd, "P1D"); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFutureBetween(hrModifyTsStart, hrModifyTsEnd, "P1D"); } @Test public void test240HrUserGuybrushDay2() throws Exception { - final String TEST_NAME = "test240HrUserGuybrushDay2"; - clockForward("P1D"); // WHEN @@ -934,8 +863,6 @@ public void test240HrUserGuybrushDay2() throws Exception { @Test public void test242GuybrushRecompute() throws Exception { - final String TEST_NAME = "test242GuybrushRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -955,8 +882,6 @@ public void test242GuybrushRecompute() throws Exception { @Test public void test244GuybrushHrSyncAgain() throws Exception { - final String TEST_NAME = "test244GuybrushHrSyncAgain"; - // WHEN when(); @@ -972,8 +897,6 @@ public void test244GuybrushHrSyncAgain() throws Exception { @Test public void test246GuybrushReconcile() throws Exception { - final String TEST_NAME = "test246GuybrushReconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -993,16 +916,16 @@ public void test246GuybrushReconcile() throws Exception { private void assertGuybrushDisabled() throws Exception { assertUserAfter(userGuybrushOid) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED) .end() - .triggers() + .triggers() .assertNone(); } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java index cf89687ba03..851a47337c9 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java @@ -42,7 +42,6 @@ public class TestDependencyRename extends AbstractStoryTest { protected static final File RESOURCE_DUMMY_PHONEBOOK_FILE = new File(TEST_DIR, "resource-dummy-phonebook.xml"); protected static final String RESOURCE_DUMMY_PHONEBOOK_ID = "phonebook"; protected static final String RESOURCE_DUMMY_PHONEBOOK_OID = "10000000-0000-0000-0000-000000000001"; - protected static final String RESOURCE_DUMMY_PHONEBOOK_NAMESPACE = MidPointConstants.NS_RI; protected static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; @@ -76,7 +75,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -102,8 +101,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_PHONEBOOK_OID, task); TestUtil.assertSuccess(testResultHr); @@ -116,8 +114,7 @@ public void test000Sanity() throws Exception { @Test public void test100AddUserHerman() throws Exception { - final String TEST_NAME = "test100AddUserHerman"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUserDefinition().instantiate(); @@ -146,8 +143,7 @@ public void test100AddUserHerman() throws Exception { @Test public void test110HermanAssignRoleBasic() throws Exception { - final String TEST_NAME = "test110HermanAssignRoleBasic"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java index d9f3d2ad58f..b18af1cb09a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java @@ -450,7 +450,7 @@ private void assertLdapObject(PrismObject org, ShadowKindType kind, Str if (LDAP_OU_VIP_INTENT.equals(intent)) search = "ou="+orgName+"-vip"; } Entry objEntry = openDJController.searchSingle(search); - assertNotNull("No LDAP entry for "+orgName, objEntry);; + assertNotNull("No LDAP entry for "+orgName, objEntry); display("LDAP entry kind " +kind + " inten " + intent +" ldapObj", objEntry); if (kind.equals(ShadowKindType.ENTITLEMENT)){ diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java index 63c7327a3f1..fb7bbe5c91b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java @@ -10,7 +10,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; @@ -77,9 +76,6 @@ public class TestLdapVirtualGroup extends AbstractLdapTest { public static final File TEST_DIR = new File(LDAP_TEST_DIR, "virtualgroup"); private static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; - private static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - /// private static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new - /// QName(RESOURCE_OPENDJ_NAMESPACE, "group"); public static final String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; @@ -101,20 +97,10 @@ public class TestLdapVirtualGroup extends AbstractLdapTest { private static final String USER_2_NAME = "User2"; private static final String USER_3_NAME = "User3"; - private static String user0Oid; - private static String user1Oid; - private static String user2Oid; - private static String user3Oid; - - private static final String ORG_TYPE_FUNCTIONAL = "functional"; - private static final String LDAP_INTENT_DEFAULT = "default"; private static final String LDAP_INTENT_VIRTUALSTATIC = "virtualstatic"; private static final String LDAP_INTENT_DYNAMIC = "dynamic"; - private ResourceType resourceOpenDjType; - private PrismObject resourceOpenDj; - @Override protected String getLdapResourceOid() { return RESOURCE_OPENDJ_OID; @@ -161,7 +147,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -170,9 +156,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); // Resources - resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, + PrismObject resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, initTask, initResult); - resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); // Org @@ -233,8 +218,7 @@ public void test090AddItRoleHR() throws Exception { @Test public void test100AddItDevRole() throws Exception { - final String TEST_NAME = "test100AddItDevRole"; - Task task = taskManager.createTaskInstance(TestLdapVirtualGroup.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject roleBefore = createLdapRole(ROLE_IT_DEV_NAME); @@ -463,23 +447,6 @@ public void test240AssignJobRoleMultiJobToUser3() throws Exception { } - private PrismObject createOrg(String name, String parentOrgOid) throws SchemaException { - PrismObject org = prismContext.getSchemaRegistry() - .findObjectDefinitionByCompileTimeClass(OrgType.class).instantiate(); - OrgType orgType = org.asObjectable(); - orgType.setName(new PolyStringType(name)); - orgType.getOrgType().add(ORG_TYPE_FUNCTIONAL); - if (parentOrgOid != null) { - AssignmentType parentAssignment = new AssignmentType(); - ObjectReferenceType parentAssignmentTargetRef = new ObjectReferenceType(); - parentAssignmentTargetRef.setOid(parentOrgOid); - parentAssignmentTargetRef.setType(OrgType.COMPLEX_TYPE); - parentAssignment.setTargetRef(parentAssignmentTargetRef); - orgType.getAssignment().add(parentAssignment); - } - return org; - } - private PrismObject createLdapRole(String name) throws SchemaException { PrismObject role = prismContext.getSchemaRegistry() .findObjectDefinitionByCompileTimeClass(RoleType.class).instantiate(); @@ -512,7 +479,6 @@ private void assertLdapUserObject(PrismObject user, ShadowKindType kin } Entry objEntry = openDJController.searchSingle(search); assertNotNull("No LDAP entry for " + userName + ", kind " + kind + ", intent " + intent, objEntry); - ; display("LDAP entry kind " + kind + " inten " + intent + " ldapObj", objEntry); } @@ -538,13 +504,13 @@ private void assertLdapObject(PrismObject role, ShadowKindType kind, S } Entry objEntry = openDJController.searchSingle(search); assertNotNull("No LDAP entry for " + roleName + ", kind " + kind + ", intent " + intent, objEntry); - ; display("LDAP entry kind " + kind + " inten " + intent + " ldapObj", objEntry); } - private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, String intent, String attribute, - String... values) throws SchemaException, ObjectNotFoundException, SecurityViolationException, - CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { + private void assertShadowAttribute(PrismObject focus, + ShadowKindType kind, String intent, String attribute, String... values) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { String focusName = focus.getName().toString(); display("assert focus " + focus.getCompileTimeClass(), focusName); @@ -552,7 +518,7 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin PrismObject objShadow = getShadowModel(objOid); display("Focus " + focusName + " kind " + kind + " intent " + intent + " shadow", objShadow); - List valuesList = new ArrayList(Arrays.asList(values)); + List valuesList = new ArrayList<>(Arrays.asList(values)); for (Object att : objShadow.asObjectable().getAttributes().asPrismContainerValue().getItems()) { if (att instanceof ResourceAttribute) { @@ -560,7 +526,7 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin if (attribute.equals(((ResourceAttribute) att).getNativeAttributeName())) { - List propValsString = new ArrayList(propVals.size()); + List propValsString = new ArrayList<>(propVals.size()); for (Object pval : propVals) { propValsString.add(pval.toString()); } @@ -569,21 +535,11 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin Collections.sort(valuesList); assertEquals(propValsString, valuesList); - } } } } - protected PrismObject getRoleByNameX(String roleName) throws SchemaException, ObjectNotFoundException, - SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - PrismObject role = findObjectByName(RoleType.class, roleName); - assertNotNull("The role " + roleName + " is missing!", role); - display("Role " + roleName, role); - PrismAsserts.assertPropertyValue(role, RoleType.F_NAME, PrismTestUtil.createPolyString(roleName)); - return role; - } - protected PrismObject getObjectByName( Class clazz, String name) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -593,5 +549,4 @@ protected org.jetbrains annotations + + org.apache.commons + commons-lang3 + diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java index e3756b522db..2425d4f606c 100644 --- a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java @@ -8,6 +8,7 @@ import java.util.Objects; +import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -69,6 +70,24 @@ default String getTestNameLong() { return testContext().getTestNameLong(); } + /** + * Returns the number of the test derived from the method name in form "testXxxDescription". + * Number is returned as a string with all leading zeroes preserved. + * Fails if the method name does not conform to the "testXxx" prefix to prevent invalid usage. + * Also fails if test-method context is not available. + */ + default String getTestNumber() { + String methodName = testContext().getTestMethodName(); + if (methodName.startsWith("test") && methodName.length() >= 7) { + String testNumber = methodName.substring(4, 7); + if (StringUtils.isNumeric(testNumber)) { + return testNumber; + } + } + throw new IllegalArgumentException( + "Test method name doesn't start with \"testXxx\" (Xxx = test number)."); + } + /** * Returns test class logger. */