Search in sources :

Example 11 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class TestPolicyDrivenRoleLifecycle method test050ActivateCorrectRole.

/**
 * Now let's try to activate the `role-correct` again.
 */
@Test
public void test050ActivateCorrectRole() throws Exception {
    given();
    Task task = getTestTask();
    task.setOwner(userAdministrator.asPrismObject());
    OperationResult result = task.getResult();
    Holder<LensContext<?>> contextHolder = new Holder<>();
    when();
    activateRole(ROLE_CORRECT.oid, contextHolder, task, result);
    then();
    dumpRules(contextHolder);
    var roleAfter = assertRoleAfter(ROLE_CORRECT.oid).assertLifecycleState(// should be unchanged
    SchemaConstants.LIFECYCLE_DRAFT).assertPolicySituations().assertNoTriggeredPolicyRules().getObjectable();
    List<PrismObject<CaseType>> cases = getCasesForObject(ROLE_CORRECT.oid, RoleType.COMPLEX_TYPE, null, task, result);
    display("cases for role", cases);
    assertEquals("Wrong # of approval cases for role", 2, cases.size());
    CaseType approvalCase = getApprovalCase(cases);
    CaseType rootCase = getRootCase(cases);
    ApprovalContextType wfc = approvalCase.getApprovalContext();
    assertEquals("wrong # of work items", 1, approvalCase.getWorkItem().size());
    CaseWorkItemType workItem = approvalCase.getWorkItem().get(0);
    assertEquals("wrong # of approval stages", 1, wfc.getApprovalSchema().getStage().size());
    assertEquals("wrong # of attached policy rules", 1, wfc.getPolicyRules().getEntry().size());
    EvaluatedPolicyRuleType rule = wfc.getPolicyRules().getEntry().get(0).getRule();
    List<EvaluatedPolicyRuleTriggerType> triggers = rule.getTrigger();
    // TODO check trigger
    caseService.completeWorkItem(WorkItemId.of(workItem), ApprovalUtils.createApproveOutput(prismContext), task, result);
    waitForCaseClose(rootCase, 60000);
    PrismObject<RoleType> roleAfterApproval = getRole(ROLE_CORRECT.oid);
    display("role after approval", roleAfterApproval);
    assertEquals("Wrong (unchanged) lifecycle state", SchemaConstants.LIFECYCLE_ACTIVE, roleAfterApproval.asObjectable().getLifecycleState());
    assertEquals("Wrong policy situation", emptyList(), roleAfter.getPolicySituation());
    assertEquals("Wrong triggered policy rules", emptyList(), roleAfter.getTriggeredPolicyRule());
}
Also used : Task(com.evolveum.midpoint.task.api.Task) Holder(com.evolveum.midpoint.util.Holder) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) PrismObject(com.evolveum.midpoint.prism.PrismObject) Test(org.testng.annotations.Test) AbstractUninitializedCertificationTest(com.evolveum.midpoint.certification.test.AbstractUninitializedCertificationTest)

Example 12 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class TestPolicyDrivenRoleLifecycle method test070ActivateCorrectHighRiskRole.

@Test
public void test070ActivateCorrectHighRiskRole() throws Exception {
    // GIVEN
    Task task = getTestTask();
    task.setOwner(userAdministrator.asPrismObject());
    OperationResult result = task.getResult();
    // WHEN
    when();
    Holder<LensContext<?>> contextHolder = new Holder<>();
    activateRole(roleCorrectHighRiskOid, contextHolder, task, result);
    // THEN
    then();
    PrismObject<RoleType> roleAfter = getRole(roleCorrectHighRiskOid);
    display("role after", roleAfter);
    assertEquals("Wrong (changed) lifecycle state", SchemaConstants.LIFECYCLE_DRAFT, roleAfter.asObjectable().getLifecycleState());
    dumpRules(contextHolder);
    assertEquals("Wrong policy situation", emptyList(), roleAfter.asObjectable().getPolicySituation());
    assertEquals("Wrong triggered policy rules", emptyList(), roleAfter.asObjectable().getTriggeredPolicyRule());
    Collection<SelectorOptions<GetOperationOptions>> options = schemaService.getOperationOptionsBuilder().build();
    List<PrismObject<CaseType>> cases = getCasesForObject(roleCorrectHighRiskOid, RoleType.COMPLEX_TYPE, options, task, result);
    display("cases for role", cases);
    assertEquals("Wrong # of approval cases for role", 2, cases.size());
    CaseType approvalCase = getApprovalCase(cases);
    ApprovalContextType wfc = approvalCase.getApprovalContext();
    // assertEquals("Modification of correct-high-risk", wfc.getProcessInstanceName());             // MID-4200
    assertEquals("wrong # of work items", 1, approvalCase.getWorkItem().size());
    CaseWorkItemType workItem = approvalCase.getWorkItem().get(0);
    assertEquals("wrong # of approval stages", 2, wfc.getApprovalSchema().getStage().size());
    assertEquals("wrong # of attached policy rules", 2, wfc.getPolicyRules().getEntry().size());
    caseService.completeWorkItem(WorkItemId.of(workItem), ApprovalUtils.createApproveOutput(prismContext), task, result);
    approvalCase = modelService.getObject(CaseType.class, approvalCase.getOid(), options, task, result).asObjectable();
    List<CaseWorkItemType> openWorkItems = approvalCase.getWorkItem().stream().filter(i -> i.getCloseTimestamp() == null).collect(Collectors.toList());
    assertEquals("wrong # of open work items", 1, openWorkItems.size());
    workItem = openWorkItems.get(0);
    caseService.completeWorkItem(WorkItemId.of(workItem), ApprovalUtils.createApproveOutput(prismContext), task, result);
    CaseType rootCase = getRootCase(cases);
    waitForCaseClose(rootCase, 60000);
    PrismObject<RoleType> roleAfterApproval = getRole(roleCorrectHighRiskOid);
    display("role after approval", roleAfterApproval);
    assertEquals("Wrong (unchanged) lifecycle state", SchemaConstants.LIFECYCLE_ACTIVE, roleAfterApproval.asObjectable().getLifecycleState());
    assertEquals("Wrong policy situation", singletonList(SITUATION_ACTIVE_ROLE_WITH_NO_IDENTIFIER), roleAfterApproval.asObjectable().getPolicySituation());
    // recording rules = none
    assertEquals("Wrong triggered policy rules", emptyList(), roleAfterApproval.asObjectable().getTriggeredPolicyRule());
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Autowired(org.springframework.beans.factory.annotation.Autowired) Test(org.testng.annotations.Test) DebugUtil(com.evolveum.midpoint.util.DebugUtil) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) AbstractUninitializedCertificationTest(com.evolveum.midpoint.certification.test.AbstractUninitializedCertificationTest) Collections.singletonList(java.util.Collections.singletonList) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) Collections.singleton(java.util.Collections.singleton) PrismContext(com.evolveum.midpoint.prism.PrismContext) ModelExecuteOptions(com.evolveum.midpoint.model.api.ModelExecuteOptions) ApprovalUtils(com.evolveum.midpoint.schema.util.cases.ApprovalUtils) CaseService(com.evolveum.midpoint.model.api.CaseService) RecordingProgressListener(com.evolveum.midpoint.model.impl.util.RecordingProgressListener) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) Holder(com.evolveum.midpoint.util.Holder) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) PrismObject(com.evolveum.midpoint.prism.PrismObject) Task(com.evolveum.midpoint.task.api.Task) Collectors(java.util.stream.Collectors) WorkItemId(com.evolveum.midpoint.schema.util.WorkItemId) File(java.io.File) TestResource(com.evolveum.midpoint.test.TestResource) List(java.util.List) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) ContextConfiguration(org.springframework.test.context.ContextConfiguration) NotNull(org.jetbrains.annotations.NotNull) AssertJUnit.assertEquals(org.testng.AssertJUnit.assertEquals) SKIP(com.evolveum.midpoint.xml.ns._public.common.common_3.PartialProcessingTypeType.SKIP) Task(com.evolveum.midpoint.task.api.Task) Holder(com.evolveum.midpoint.util.Holder) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) PrismObject(com.evolveum.midpoint.prism.PrismObject) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) Test(org.testng.annotations.Test) AbstractUninitializedCertificationTest(com.evolveum.midpoint.certification.test.AbstractUninitializedCertificationTest)

Example 13 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class TestPolicyDrivenRoleLifecycle method test010AttemptToActivateIncompleteRoleC1345.

/**
 * Trying to activate role that cannot be activated e.g. because of rule R1.
 * (Among others.)
 */
@Test
public void test010AttemptToActivateIncompleteRoleC1345() throws Exception {
    given();
    Task task = getTestTask();
    task.setOwner(userAdministrator.asPrismObject());
    OperationResult result = task.getResult();
    Holder<LensContext<?>> contextHolder = new Holder<>();
    when();
    then();
    activateRoleAssertFailure(ROLE_EMPTY.oid, contextHolder, result, task);
    dumpRules(contextHolder);
    assertRoleAfter(ROLE_EMPTY.oid).assertPolicySituations(// see rule RE1
    SITUATION_INCOMPLETE_ROLE);
}
Also used : Task(com.evolveum.midpoint.task.api.Task) Holder(com.evolveum.midpoint.util.Holder) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) Test(org.testng.annotations.Test) AbstractUninitializedCertificationTest(com.evolveum.midpoint.certification.test.AbstractUninitializedCertificationTest)

Example 14 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class TestResources method test767ModifyConfigurationDiffExpressionRawValidatorParse.

/**
 * This is what GUI "Repository objects" page really does with XML.
 */
@Test
public void test767ModifyConfigurationDiffExpressionRawValidatorParse() throws Exception {
    modifyConfigurationDiffExpressionRaw(xml -> {
        final Holder<PrismObject<ResourceType>> objectHolder = new Holder<>();
        EventHandler<ResourceType> handler = new EventHandler<>() {

            @Override
            public EventResult preMarshall(Element objectElement, Node postValidationTree, OperationResult objectResult) {
                return EventResult.cont();
            }

            @Override
            public EventResult postMarshall(ResourceType object, Element objectElement, OperationResult objectResult) {
                objectHolder.setValue(object.asPrismObject());
                return EventResult.cont();
            }

            @Override
            public void handleGlobalError(OperationResult currentResult) {
            }
        };
        LegacyValidator<ResourceType> validator = new LegacyValidator<>(prismContext, handler);
        validator.setVerbose(true);
        validator.setValidateSchema(false);
        OperationResult result = createOperationResult("validator");
        validator.validateObject(xml, result);
        return objectHolder.getValue();
    });
}
Also used : LegacyValidator(com.evolveum.midpoint.common.validator.LegacyValidator) Holder(com.evolveum.midpoint.util.Holder) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) EventHandler(com.evolveum.midpoint.common.validator.EventHandler) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Test(org.testng.annotations.Test)

Example 15 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class ReportManagerImpl method getReportDataStream.

@Override
public InputStream getReportDataStream(String reportDataOid, OperationResult parentResult) throws CommonException, IOException {
    Task task = taskManager.createTaskInstance(REPORT_OUTPUT_DATA);
    OperationResult result = parentResult.createSubresult(REPORT_OUTPUT_DATA);
    result.addParam("oid", reportDataOid);
    try {
        // MID-7219: We need report type in case of cluster to look for file in correct remote folders
        String reportType = null;
        ReportDataType reportData = modelService.getObject(ReportDataType.class, reportDataOid, null, task, result).asObjectable();
        // Extra safety check: traces can be retrieved only when special authorization is present
        if (ObjectTypeUtil.hasArchetype(reportData, SystemObjectsType.ARCHETYPE_TRACE.value())) {
            securityEnforcer.authorize(ModelAuthorizationAction.READ_TRACE.getUrl(), null, AuthorizationParameters.EMPTY, null, task, result);
            reportType = "trace";
        }
        String filePath = reportData.getFilePath();
        if (StringUtils.isEmpty(filePath)) {
            result.recordFatalError("Report output file path is not defined.");
            return null;
        }
        File file = new File(filePath);
        if (file.exists()) {
            return FileUtils.openInputStream(file);
        } else {
            String fileName = remoteFileName(reportData, reportType, file, task, result);
            if (fileName == null) {
                return null;
            }
            Holder<InputStream> inputStreamHolder = new Holder<>();
            @Nullable String originalNodeOid = reportData.getNodeRef() != null ? reportData.getNodeRef().getOid() : null;
            PrismObject<NodeType> executorNode = clusterExecutionHelper.executeWithFallback(originalNodeOid, (client, node, result1) -> {
                client.path(ModelPublicConstants.CLUSTER_REPORT_FILE_PATH);
                client.query(ModelPublicConstants.CLUSTER_REPORT_FILE_FILENAME_PARAMETER, fileName);
                client.accept(MediaType.APPLICATION_OCTET_STREAM);
                Response response = client.get();
                Response.StatusType statusInfo = response.getStatusInfo();
                LOGGER.debug("Retrieving report output file ({}) from {} finished with status {}: {}", fileName, originalNodeOid, statusInfo.getStatusCode(), statusInfo.getReasonPhrase());
                if (statusInfo.getFamily() == Response.Status.Family.SUCCESSFUL) {
                    Object entity = response.getEntity();
                    if (entity == null || entity instanceof InputStream) {
                        inputStreamHolder.setValue((InputStream) entity);
                    // do NOT close the response; input stream will be closed later by the caller(s)
                    } else {
                        LOGGER.error("Content of the report output file retrieved from the remote node is not an InputStream; " + "it is {} instead -- this is not currently supported", entity.getClass());
                        response.close();
                    }
                } else {
                    LOGGER.warn("Retrieving report output file ({}) from {} finished with status {}: {}", fileName, originalNodeOid, statusInfo.getStatusCode(), statusInfo.getReasonPhrase());
                    result1.recordFatalError("Could not retrieve report output file: Got " + statusInfo.getStatusCode() + ": " + statusInfo.getReasonPhrase());
                    response.close();
                }
            }, new ClusterExecutionOptions().tryNodesInTransition().skipDefaultAccept(), "get report output", result);
            if (executorNode != null && !executorNode.getOid().equals(originalNodeOid)) {
                LOGGER.info("Recording new location of {}: {}", reportData, executorNode);
                List<ItemDelta<?, ?>> deltas = prismContext.deltaFor(ReportDataType.class).item(ReportDataType.F_NODE_REF).replace(createObjectRef(executorNode, prismContext)).asItemDeltas();
                try {
                    repositoryService.modifyObject(ReportDataType.class, reportDataOid, deltas, result);
                } catch (ObjectAlreadyExistsException e) {
                    throw new SystemException("Unexpected exception: " + e.getMessage(), e);
                }
            }
            result.computeStatusIfUnknown();
            return inputStreamHolder.getValue();
        }
    } catch (IOException ex) {
        LoggingUtils.logException(LOGGER, "Error while fetching file. File might not exist on the corresponding file system", ex);
        result.recordPartialError("Error while fetching file. File might not exist on the corresponding file system. Reason: " + ex.getMessage(), ex);
        throw ex;
    } catch (ObjectNotFoundException | SchemaException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
        result.recordFatalError("Problem with reading report output. Reason: " + e.getMessage(), e);
        throw e;
    } finally {
        result.computeStatusIfUnknown();
    }
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) InputStream(java.io.InputStream) Holder(com.evolveum.midpoint.util.Holder) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

Holder (com.evolveum.midpoint.util.Holder)45 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)27 PrismObject (com.evolveum.midpoint.prism.PrismObject)16 Task (com.evolveum.midpoint.task.api.Task)13 Test (org.testng.annotations.Test)13 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)12 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)9 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)8 QName (javax.xml.namespace.QName)8 SystemException (com.evolveum.midpoint.util.exception.SystemException)7 LensContext (com.evolveum.midpoint.model.impl.lens.LensContext)6 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)6 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)6 NotNull (org.jetbrains.annotations.NotNull)6 AbstractUninitializedCertificationTest (com.evolveum.midpoint.certification.test.AbstractUninitializedCertificationTest)5 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)5 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)5 Trace (com.evolveum.midpoint.util.logging.Trace)5 TraceManager (com.evolveum.midpoint.util.logging.TraceManager)5 com.evolveum.midpoint.xml.ns._public.common.common_3 (com.evolveum.midpoint.xml.ns._public.common.common_3)5