Search in sources :

Example 21 with GetOperationOptions

use of com.evolveum.midpoint.schema.GetOperationOptions in project midpoint by Evolveum.

the class ReportFunctions method searchCertificationDefinitions.

// TODO implement if needed
//    <O extends Containerable> RefFilter createReferenceEqualFilter(QName propertyName, Class<O> type, String... oids) {
//        return RefFilter.createReferenceEqual(propertyName, type, prismContext, oids);
//    }
//    <O extends Containerable> RefFilter createReferenceEqualFilter(ItemPath propertyPath, Class<O> type, String... oids) throws SchemaException {
//        return RefFilter.createReferenceEqual(propertyPath, type, prismContext, oids);
//    }
//    Object parseObjectFromXML (String xml) throws SchemaException {
//        return prismContext.parserFor(xml).xml().parseAnyData();
//    }
/**
     * Retrieves all definitions.
     * Augments them by count of campaigns (all + open ones).
     *
     * TODO query parameters, customizable sorting
     * definitions and campaigns counts are expected to be low, so we can afford to go through all of them here
     */
public Collection<PrismObject<AccessCertificationDefinitionForReportType>> searchCertificationDefinitions() throws ConfigurationException, SchemaException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ExpressionEvaluationException {
    Task task = taskManager.createTaskInstance();
    OperationResult result = task.getResult();
    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames());
    List<PrismObject<AccessCertificationDefinitionType>> definitions = model.searchObjects(AccessCertificationDefinitionType.class, null, options, task, result);
    final Map<String, PrismObject<AccessCertificationDefinitionForReportType>> definitionsForReportMap = new HashMap<>();
    for (PrismObject<AccessCertificationDefinitionType> definition : definitions) {
        // create subclass with the values copied from the superclass
        PrismObject<AccessCertificationDefinitionForReportType> definitionForReport = prismContext.createObjectable(AccessCertificationDefinitionForReportType.class).asPrismObject();
        for (Item<?, ?> item : definition.getValue().getItems()) {
            definitionForReport.getValue().add(item.clone());
        }
        definitionsForReportMap.put(definition.getOid(), definitionForReport);
    }
    ResultHandler<AccessCertificationCampaignType> handler = (campaignObject, parentResult) -> {
        AccessCertificationCampaignType campaign = campaignObject.asObjectable();
        if (campaign.getDefinitionRef() != null) {
            String definitionOid = campaign.getDefinitionRef().getOid();
            PrismObject<AccessCertificationDefinitionForReportType> definitionObject = definitionsForReportMap.get(definitionOid);
            if (definitionObject != null) {
                AccessCertificationDefinitionForReportType definition = definitionObject.asObjectable();
                int campaigns = definition.getCampaigns() != null ? definition.getCampaigns() : 0;
                definition.setCampaigns(campaigns + 1);
                AccessCertificationCampaignStateType state = campaign.getState();
                if (state != AccessCertificationCampaignStateType.CREATED && state != CLOSED) {
                    int openCampaigns = definition.getOpenCampaigns() != null ? definition.getOpenCampaigns() : 0;
                    definition.setOpenCampaigns(openCampaigns + 1);
                }
            }
        }
        return true;
    };
    model.searchObjectsIterative(AccessCertificationCampaignType.class, null, handler, null, task, result);
    List<PrismObject<AccessCertificationDefinitionForReportType>> rv = new ArrayList<>(definitionsForReportMap.values());
    Collections.sort(rv, (o1, o2) -> {
        String n1 = o1.asObjectable().getName().getOrig();
        String n2 = o2.asObjectable().getName().getOrig();
        if (n1 == null) {
            n1 = "";
        }
        return n1.compareTo(n2);
    });
    for (PrismObject<AccessCertificationDefinitionForReportType> defObject : rv) {
        AccessCertificationDefinitionForReportType def = defObject.asObjectable();
        if (def.getCampaigns() == null) {
            def.setCampaigns(0);
        }
        if (def.getOpenCampaigns() == null) {
            def.setOpenCampaigns(0);
        }
    }
    return rv;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) F_STATE(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_STATE) Trace(com.evolveum.midpoint.util.logging.Trace) F_NAME(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME) TaskManager(com.evolveum.midpoint.task.api.TaskManager) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) AuditEventStage(com.evolveum.midpoint.audit.api.AuditEventStage) RetrieveOption(com.evolveum.midpoint.schema.RetrieveOption) AuditEventRecord(com.evolveum.midpoint.audit.api.AuditEventRecord) CLOSED(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignStateType.CLOSED) com.evolveum.midpoint.prism(com.evolveum.midpoint.prism) AuditService(com.evolveum.midpoint.audit.api.AuditService) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) Task(com.evolveum.midpoint.task.api.Task) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) AuditEventTypeType(com.evolveum.midpoint.xml.ns._public.common.audit_3.AuditEventTypeType) ModelService(com.evolveum.midpoint.model.api.ModelService) QueryBuilder(com.evolveum.midpoint.prism.query.builder.QueryBuilder) AuditEventType(com.evolveum.midpoint.audit.api.AuditEventType) AuditEventStageType(com.evolveum.midpoint.xml.ns._public.common.audit_3.AuditEventStageType) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) Entry(java.util.Map.Entry) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) QName(javax.xml.namespace.QName) Validate(org.apache.commons.lang.Validate) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions)

Example 22 with GetOperationOptions

use of com.evolveum.midpoint.schema.GetOperationOptions in project midpoint by Evolveum.

the class AuditServiceProxy method completeRecord.

/**
	 * Complete the record with data that can be computed or discovered from the
	 * environment
	 */
private void completeRecord(AuditEventRecord record, Task task) {
    LightweightIdentifier id = null;
    if (record.getEventIdentifier() == null) {
        id = lightweightIdentifierGenerator.generate();
        record.setEventIdentifier(id.toString());
    }
    if (record.getTimestamp() == null) {
        if (id == null) {
            record.setTimestamp(System.currentTimeMillis());
        } else {
            // To be consistent with the ID
            record.setTimestamp(id.getTimestamp());
        }
    }
    if (record.getTaskIdentifier() == null && task != null) {
        record.setTaskIdentifier(task.getTaskIdentifier());
    }
    if (record.getTaskOID() == null && task != null) {
        record.setTaskOID(task.getOid());
    }
    if (record.getChannel() == null && task != null) {
        record.setChannel(task.getChannel());
    }
    if (record.getInitiator() == null && task != null) {
        record.setInitiator(task.getOwner());
    }
    if (record.getNodeIdentifier() == null && taskManager != null) {
        record.setNodeIdentifier(taskManager.getNodeId());
    }
    HttpConnectionInformation connInfo = SecurityUtil.getCurrentConnectionInformation();
    if (connInfo == null && securityEnforcer != null) {
        connInfo = securityEnforcer.getStoredConnectionInformation();
    }
    if (connInfo != null) {
        if (record.getSessionIdentifier() == null) {
            record.setSessionIdentifier(connInfo.getSessionId());
        }
        if (record.getRemoteHostAddress() == null) {
            record.setRemoteHostAddress(connInfo.getRemoteHostAddress());
        }
        if (record.getHostIdentifier() == null) {
            record.setHostIdentifier(connInfo.getLocalHostName());
        }
    }
    if (record.getSessionIdentifier() == null && task != null) {
        record.setSessionIdentifier(task.getTaskIdentifier());
    }
    if (record.getDeltas() != null) {
        for (ObjectDeltaOperation<? extends ObjectType> objectDeltaOperation : record.getDeltas()) {
            ObjectDelta<? extends ObjectType> delta = objectDeltaOperation.getObjectDelta();
            final Map<String, PolyString> resolvedOids = new HashMap<>();
            Visitor namesResolver = new Visitor() {

                @Override
                public void visit(Visitable visitable) {
                    if (visitable instanceof PrismReferenceValue) {
                        PrismReferenceValue refVal = ((PrismReferenceValue) visitable);
                        String oid = refVal.getOid();
                        if (oid == null) {
                            // happen
                            return;
                        }
                        if (refVal.getTargetName() != null) {
                            resolvedOids.put(oid, refVal.getTargetName());
                            return;
                        }
                        if (resolvedOids.containsKey(oid)) {
                            // may
                            PolyString resolvedName = resolvedOids.get(oid);
                            // be
                            // null
                            refVal.setTargetName(resolvedName);
                            return;
                        }
                        if (refVal.getObject() != null) {
                            PolyString name = refVal.getObject().getName();
                            refVal.setTargetName(name);
                            resolvedOids.put(oid, name);
                            return;
                        }
                        if (repositoryService == null) {
                            LOGGER.warn("No repository, no OID resolution (for {})", oid);
                            return;
                        }
                        PrismObjectDefinition<? extends ObjectType> objectDefinition = null;
                        if (refVal.getTargetType() != null) {
                            objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByType(refVal.getTargetType());
                        }
                        Class<? extends ObjectType> objectClass = null;
                        if (objectDefinition != null) {
                            objectClass = objectDefinition.getCompileTimeClass();
                        }
                        if (objectClass == null) {
                            // the default
                            objectClass = ObjectType.class;
                        // (shouldn't be
                        // needed)
                        }
                        SelectorOptions<GetOperationOptions> getNameOnly = SelectorOptions.create(new ItemPath(ObjectType.F_NAME), GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
                        try {
                            PrismObject<? extends ObjectType> object = repositoryService.getObject(objectClass, oid, Arrays.asList(getNameOnly), new OperationResult("dummy"));
                            PolyString name = object.getName();
                            refVal.setTargetName(name);
                            resolvedOids.put(oid, name);
                            LOGGER.trace("Resolved {}: {} to {}", objectClass, oid, name);
                        } catch (ObjectNotFoundException e) {
                            LOGGER.trace("Couldn't determine the name for {}: {} as it does not exist", objectClass, oid, e);
                            resolvedOids.put(oid, null);
                        } catch (SchemaException | RuntimeException e) {
                            LOGGER.trace("Couldn't determine the name for {}: {} because of unexpected exception", objectClass, oid, e);
                            resolvedOids.put(oid, null);
                        }
                    }
                }
            };
            delta.accept(namesResolver);
        }
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Visitor(com.evolveum.midpoint.prism.Visitor) HashMap(java.util.HashMap) Visitable(com.evolveum.midpoint.prism.Visitable) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) HttpConnectionInformation(com.evolveum.midpoint.security.api.HttpConnectionInformation) PrismReferenceValue(com.evolveum.midpoint.prism.PrismReferenceValue) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) LightweightIdentifier(com.evolveum.midpoint.task.api.LightweightIdentifier) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 23 with GetOperationOptions

use of com.evolveum.midpoint.schema.GetOperationOptions in project midpoint by Evolveum.

the class NameResolutionHelper method resolveNamesIfRequested.

public void resolveNamesIfRequested(Session session, List<? extends PrismContainerValue> containerValues, Collection<SelectorOptions<GetOperationOptions>> options) {
    List<ItemPath> pathsToResolve = getPathsToResolve(options);
    if (pathsToResolve.isEmpty()) {
        return;
    }
    final Set<String> oidsToResolve = new HashSet<>();
    Visitor oidExtractor = visitable -> {
        if (visitable instanceof PrismReferenceValue) {
            PrismReferenceValue value = (PrismReferenceValue) visitable;
            if (!ItemPath.containsSubpathOrEquivalent(pathsToResolve, value.getPath())) {
                return;
            }
            if (value.getTargetName() != null) {
                return;
            }
            if (value.getObject() != null) {
                value.setTargetName(value.getObject().getName());
                return;
            }
            if (value.getOid() == null) {
                return;
            }
            oidsToResolve.add(value.getOid());
        }
    };
    Set<PrismContainerValue> roots = containerValues.stream().map(pcv -> pcv.getRootValue()).collect(Collectors.toSet());
    roots.forEach(root -> root.accept(oidExtractor));
    Map<String, PolyString> oidNameMap = new HashMap<>();
    List<String> batch = new ArrayList<>();
    for (Iterator<String> iterator = oidsToResolve.iterator(); iterator.hasNext(); ) {
        batch.add(iterator.next());
        if (batch.size() >= MAX_OIDS_TO_RESOLVE_AT_ONCE || !iterator.hasNext()) {
            Query query = session.getNamedQuery("resolveReferences");
            query.setParameterList("oid", batch);
            query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            @SuppressWarnings({ "unchecked", "raw" }) List<Map<String, Object>> // returns oid + name
            results = query.list();
            for (Map<String, Object> result : results) {
                String oid = (String) result.get("0");
                RPolyString name = (RPolyString) result.get("1");
                oidNameMap.put(oid, new PolyString(name.getOrig(), name.getNorm()));
            }
            batch.clear();
        }
    }
    if (!oidNameMap.isEmpty()) {
        Visitor nameSetter = visitable -> {
            if (visitable instanceof PrismReferenceValue) {
                PrismReferenceValue value = (PrismReferenceValue) visitable;
                if (value.getTargetName() == null && value.getOid() != null) {
                    value.setTargetName(oidNameMap.get(value.getOid()));
                }
            }
        };
        roots.forEach(root -> root.accept(nameSetter));
    }
}
Also used : SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) java.util(java.util) RPolyString(com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString) Transformers(org.hibernate.transform.Transformers) Session(org.hibernate.Session) Collectors(java.util.stream.Collectors) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) CollectionUtils(org.apache.commons.collections4.CollectionUtils) Component(org.springframework.stereotype.Component) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) Query(org.hibernate.Query) NotNull(org.jetbrains.annotations.NotNull) com.evolveum.midpoint.prism(com.evolveum.midpoint.prism) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) Query(org.hibernate.Query) RPolyString(com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString) RPolyString(com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) RPolyString(com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 24 with GetOperationOptions

use of com.evolveum.midpoint.schema.GetOperationOptions in project midpoint by Evolveum.

the class DeleteAllPanel method createDeleteOrgUnitsMessage.

private String createDeleteOrgUnitsMessage() {
    if (!model.getObject().getDeleteOrgs()) {
        return createStringResource("deleteAllDialog.label.orgUnitsDelete", 0).getString();
    }
    DeleteAllDto dto = model.getObject();
    Task task = getPagebase().createSimpleTask(OPERATION_COUNT_TASK);
    OperationResult result = new OperationResult(OPERATION_COUNT_TASK);
    Collection<SelectorOptions<GetOperationOptions>> options = new ArrayList<>();
    GetOperationOptions opt = GetOperationOptions.createRaw();
    options.add(SelectorOptions.create(ItemPath.EMPTY_PATH, opt));
    try {
        dto.setOrgUnitCount(getPagebase().getModelService().countObjects(OrgType.class, null, options, task, result));
        dto.setObjectsToDelete(dto.getObjectsToDelete() + dto.getOrgUnitCount());
    } catch (Exception ex) {
        result.computeStatus(getString("deleteAllDialog.message.countSearchProblem"));
        LoggingUtils.logUnexpectedException(LOGGER, getString("deleteAllDialog.message.countSearchProblem"), ex);
    }
    return createStringResource("deleteAllDialog.label.orgUnitsDelete", dto.getOrgUnitCount()).getString();
}
Also used : Task(com.evolveum.midpoint.task.api.Task) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) OrgType(com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult)

Example 25 with GetOperationOptions

use of com.evolveum.midpoint.schema.GetOperationOptions in project midpoint by Evolveum.

the class DeleteAllPanel method createDeleteUsersMessage.

private String createDeleteUsersMessage() {
    if (!model.getObject().getDeleteUsers()) {
        return createStringResource("deleteAllDialog.label.usersDelete", 0).getString();
    }
    DeleteAllDto dto = model.getObject();
    Task task = getPagebase().createSimpleTask(OPERATION_COUNT_TASK);
    OperationResult result = new OperationResult(OPERATION_COUNT_TASK);
    Collection<SelectorOptions<GetOperationOptions>> options = new ArrayList<>();
    GetOperationOptions opt = GetOperationOptions.createRaw();
    options.add(SelectorOptions.create(ItemPath.EMPTY_PATH, opt));
    try {
        dto.setUserCount(getPagebase().getModelService().countObjects(UserType.class, null, options, task, result));
        //We need to substract 1, because we are not deleting user 'Administrator'
        dto.setUserCount(dto.getUserCount() - 1);
        dto.setObjectsToDelete(dto.getObjectsToDelete() + dto.getUserCount());
    } catch (Exception ex) {
        result.computeStatus(getString("deleteAllDialog.message.countSearchProblem"));
        LoggingUtils.logUnexpectedException(LOGGER, getString("deleteAllDialog.message.countSearchProblem"), ex);
    }
    return createStringResource("deleteAllDialog.label.usersDelete", dto.getUserCount()).getString();
}
Also used : Task(com.evolveum.midpoint.task.api.Task) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Aggregations

GetOperationOptions (com.evolveum.midpoint.schema.GetOperationOptions)52 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)38 SelectorOptions (com.evolveum.midpoint.schema.SelectorOptions)31 Task (com.evolveum.midpoint.task.api.Task)22 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)19 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)19 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)13 Collection (java.util.Collection)12 PrismObject (com.evolveum.midpoint.prism.PrismObject)11 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)11 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)11 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)11 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)10 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)10 QName (javax.xml.namespace.QName)10 Test (org.testng.annotations.Test)10 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)9 ArrayList (java.util.ArrayList)9 ResultHandler (com.evolveum.midpoint.schema.ResultHandler)8 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)7