Search in sources :

Example 56 with SystemException

use of com.evolveum.midpoint.util.exception.SystemException in project midpoint by Evolveum.

the class ConnectorInstanceConnIdImpl method addObject.

@Override
public AsynchronousOperationReturnValue<Collection<ResourceAttribute<?>>> addObject(PrismObject<? extends ShadowType> shadow, Collection<Operation> additionalOperations, StateReporter reporter, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SchemaException, ObjectAlreadyExistsException, ConfigurationException {
    validateShadow(shadow, "add", false);
    ShadowType shadowType = shadow.asObjectable();
    ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(shadow);
    OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".addObject");
    result.addParam("resourceObject", shadow);
    // because of serialization issues
    result.addParam("additionalOperations", DebugUtil.debugDump(additionalOperations));
    ObjectClassComplexTypeDefinition ocDef;
    ResourceAttributeContainerDefinition attrContDef = attributesContainer.getDefinition();
    if (attrContDef != null) {
        ocDef = attrContDef.getComplexTypeDefinition();
    } else {
        ocDef = resourceSchema.findObjectClassDefinition(shadow.asObjectable().getObjectClass());
        if (ocDef == null) {
            throw new SchemaException("Unknown object class " + shadow.asObjectable().getObjectClass());
        }
    }
    // getting icf object class from resource object class
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(shadow, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        result.recordFatalError("Couldn't get icf object class from " + shadow);
        throw new IllegalArgumentException("Couldn't get icf object class from " + shadow);
    }
    // setting ifc attributes from resource object attributes
    Set<Attribute> attributes = null;
    try {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("midPoint object before conversion:\n{}", attributesContainer.debugDump());
        }
        attributes = connIdConvertor.convertFromResourceObject(attributesContainer, ocDef);
        if (shadowType.getCredentials() != null && shadowType.getCredentials().getPassword() != null) {
            PasswordType password = shadowType.getCredentials().getPassword();
            ProtectedStringType protectedString = password.getValue();
            GuardedString guardedPassword = ConnIdUtil.toGuardedString(protectedString, "new password", protector);
            if (guardedPassword != null) {
                attributes.add(AttributeBuilder.build(OperationalAttributes.PASSWORD_NAME, guardedPassword));
            }
        }
        if (ActivationUtil.hasAdministrativeActivation(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.ENABLE_NAME, ActivationUtil.isAdministrativeEnabled(shadowType)));
        }
        if (ActivationUtil.hasValidFrom(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.ENABLE_DATE_NAME, XmlTypeConverter.toMillis(shadowType.getActivation().getValidFrom())));
        }
        if (ActivationUtil.hasValidTo(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.DISABLE_DATE_NAME, XmlTypeConverter.toMillis(shadowType.getActivation().getValidTo())));
        }
        if (ActivationUtil.hasLockoutStatus(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.LOCK_OUT_NAME, ActivationUtil.isLockedOut(shadowType)));
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("ICF attributes after conversion:\n{}", ConnIdUtil.dump(attributes));
        }
    } catch (SchemaException | RuntimeException ex) {
        result.recordFatalError("Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
        throw new SchemaException("Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
    }
    if (attributes == null) {
        result.recordFatalError("Couldn't set attributes for icf.");
        throw new IllegalStateException("Couldn't set attributes for icf.");
    }
    List<String> icfAuxiliaryObjectClasses = new ArrayList<>();
    for (QName auxiliaryObjectClass : shadowType.getAuxiliaryObjectClass()) {
        icfAuxiliaryObjectClasses.add(connIdNameMapper.objectClassToIcf(auxiliaryObjectClass, resourceSchemaNamespace, connectorType, false).getObjectClassValue());
    }
    if (!icfAuxiliaryObjectClasses.isEmpty()) {
        AttributeBuilder ab = new AttributeBuilder();
        ab.setName(PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME);
        ab.addValue(icfAuxiliaryObjectClasses);
        attributes.add(ab.build());
    }
    OperationOptionsBuilder operationOptionsBuilder = new OperationOptionsBuilder();
    OperationOptions options = operationOptionsBuilder.build();
    checkAndExecuteAdditionalOperation(reporter, additionalOperations, BeforeAfterType.BEFORE, result);
    OperationResult connIdResult = result.createSubresult(ConnectorFacade.class.getName() + ".create");
    connIdResult.addArbitraryObjectAsParam("objectClass", icfObjectClass);
    connIdResult.addArbitraryCollectionAsParam("auxiliaryObjectClasses", icfAuxiliaryObjectClasses);
    connIdResult.addArbitraryCollectionAsParam("attributes", attributes);
    connIdResult.addArbitraryObjectAsParam("options", options);
    connIdResult.addContext("connector", connIdConnectorFacade.getClass());
    Uid uid = null;
    try {
        // CALL THE ICF FRAMEWORK
        InternalMonitor.recordConnectorOperation("create");
        // TODO provide object name
        recordIcfOperationStart(reporter, ProvisioningOperation.ICF_CREATE, ocDef, null);
        uid = connIdConnectorFacade.create(icfObjectClass, attributes, options);
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_CREATE, ocDef, uid);
    } catch (Throwable ex) {
        // TODO name
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_CREATE, ocDef, ex, null);
        Throwable midpointEx = processIcfException(ex, this, connIdResult);
        result.computeStatus("Add object failed");
        // exception
        if (midpointEx instanceof ObjectAlreadyExistsException) {
            throw (ObjectAlreadyExistsException) midpointEx;
        } else if (midpointEx instanceof CommunicationException) {
            //				result.muteError();
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof ConfigurationException) {
            throw (ConfigurationException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    checkAndExecuteAdditionalOperation(reporter, additionalOperations, BeforeAfterType.AFTER, result);
    if (uid == null || uid.getUidValue() == null || uid.getUidValue().isEmpty()) {
        connIdResult.recordFatalError("ICF did not returned UID after create");
        result.computeStatus("Add object failed");
        throw new GenericFrameworkException("ICF did not returned UID after create");
    }
    Collection<ResourceAttribute<?>> identifiers = ConnIdUtil.convertToIdentifiers(uid, attributesContainer.getDefinition().getComplexTypeDefinition(), resourceSchema);
    for (ResourceAttribute<?> identifier : identifiers) {
        attributesContainer.getValue().addReplaceExisting(identifier);
    }
    connIdResult.recordSuccess();
    result.recordSuccess();
    return AsynchronousOperationReturnValue.wrap(attributesContainer.getAttributes(), result);
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) Attribute(org.identityconnectors.framework.common.objects.Attribute) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) GuardedString(org.identityconnectors.common.security.GuardedString) GuardedString(org.identityconnectors.common.security.GuardedString) PasswordType(com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AttributeBuilder(org.identityconnectors.framework.common.objects.AttributeBuilder) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) QName(javax.xml.namespace.QName) Uid(org.identityconnectors.framework.common.objects.Uid) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)

Example 57 with SystemException

use of com.evolveum.midpoint.util.exception.SystemException in project midpoint by Evolveum.

the class ConnectorInstanceConnIdImpl method retrieveResourceSchema.

private void retrieveResourceSchema(List<QName> generateObjectClasses, OperationResult parentResult) throws CommunicationException, ConfigurationException, GenericFrameworkException {
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = parentResult.createSubresult(ConnectorFacade.class.getName() + ".schema");
    icfResult.addContext("connector", connIdConnectorFacade.getClass());
    org.identityconnectors.framework.common.objects.Schema icfSchema = null;
    try {
        // Fetch the schema from the connector (which actually gets that
        // from the resource).
        InternalMonitor.recordConnectorOperation("schema");
        // TODO have context present
        //recordIcfOperationStart(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null);
        icfSchema = connIdConnectorFacade.schema();
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null);
        icfResult.recordSuccess();
    } catch (UnsupportedOperationException ex) {
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null, ex);
        // The connector does no support schema() operation.
        icfResult.recordStatus(OperationResultStatus.NOT_APPLICABLE, ex.getMessage());
        resetResourceSchema();
        return;
    } catch (Throwable ex) {
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null, ex);
        // conditions.
        // Therefore this kind of heavy artillery is necessary.
        // ICF interface does not specify exceptions or other error
        // TODO maybe we can try to catch at least some specific exceptions
        Throwable midpointEx = processIcfException(ex, this, icfResult);
        // exception
        if (midpointEx instanceof CommunicationException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof ConfigurationException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (ConfigurationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (Error) midpointEx;
        } else {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    if (icfSchema == null) {
        icfResult.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Null schema returned");
        resetResourceSchema();
        return;
    }
    parseResourceSchema(icfSchema, generateObjectClasses);
}
Also used : CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) Schema(org.identityconnectors.framework.common.objects.Schema)

Example 58 with SystemException

use of com.evolveum.midpoint.util.exception.SystemException in project midpoint by Evolveum.

the class ConnectorInstanceConnIdImpl method search.

@Override
public <T extends ShadowType> SearchResultMetadata search(final ObjectClassComplexTypeDefinition objectClassDefinition, final ObjectQuery query, final ResultHandler<T> handler, AttributesToReturn attributesToReturn, PagedSearchCapabilityType pagedSearchCapabilityType, SearchHierarchyConstraints searchHierarchyConstraints, final StateReporter reporter, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SecurityViolationException, SchemaException, ObjectNotFoundException {
    // Result type for this operation
    final OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".search");
    result.addParam("objectClass", objectClassDefinition);
    result.addContext("connector", connectorType);
    if (objectClassDefinition == null) {
        result.recordFatalError("Object class not defined");
        throw new IllegalArgumentException("objectClass not defined");
    }
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(objectClassDefinition, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        IllegalArgumentException ex = new IllegalArgumentException("Unable to determine object class from QName " + objectClassDefinition + " while attempting to search objects by " + ObjectTypeUtil.toShortString(connectorType));
        result.recordFatalError("Unable to determine object class", ex);
        throw ex;
    }
    final PrismObjectDefinition<T> objectDefinition = toShadowDefinition(objectClassDefinition);
    if (pagedSearchCapabilityType == null) {
        pagedSearchCapabilityType = getCapability(PagedSearchCapabilityType.class);
    }
    final boolean useConnectorPaging = pagedSearchCapabilityType != null;
    if (!useConnectorPaging && query != null && query.getPaging() != null && (query.getPaging().getOffset() != null || query.getPaging().getMaxSize() != null)) {
        InternalMonitor.recordConnectorSimulatedPagingSearchCount();
    }
    final Holder<Integer> countHolder = new Holder<>(0);
    ResultsHandler icfHandler = new ResultsHandler() {

        @Override
        public boolean handle(ConnectorObject connectorObject) {
            // Convert ICF-specific connector object to a generic
            // ResourceObject
            recordIcfOperationSuspend(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
            int count = countHolder.getValue();
            countHolder.setValue(count + 1);
            if (!useConnectorPaging) {
                if (query != null && query.getPaging() != null && query.getPaging().getOffset() != null && query.getPaging().getMaxSize() != null) {
                    if (count < query.getPaging().getOffset()) {
                        recordResume();
                        return true;
                    }
                    if (count == (query.getPaging().getOffset() + query.getPaging().getMaxSize())) {
                        recordResume();
                        return false;
                    }
                }
            }
            PrismObject<T> resourceObject;
            try {
                resourceObject = connIdConvertor.convertToResourceObject(connectorObject, objectDefinition, false, caseIgnoreAttributeNames, legacySchema);
            } catch (SchemaException e) {
                recordResume();
                throw new IntermediateException(e);
            }
            // .. and pass it to the handler
            boolean cont = handler.handle(resourceObject);
            if (!cont) {
                result.recordWarning("Stopped on request from the handler");
            }
            recordResume();
            return cont;
        }

        private void recordResume() {
            recordIcfOperationResume(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        }
    };
    OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
    try {
        convertToIcfAttrsToGet(objectClassDefinition, attributesToReturn, optionsBuilder);
        if (query != null && query.isAllowPartialResults()) {
            optionsBuilder.setAllowPartialResults(query.isAllowPartialResults());
        }
        // preparing paging-related options
        if (useConnectorPaging && query != null && query.getPaging() != null) {
            ObjectPaging paging = query.getPaging();
            if (paging.getOffset() != null) {
                // ConnId API says the numbering starts at 1
                optionsBuilder.setPagedResultsOffset(paging.getOffset() + 1);
            }
            if (paging.getMaxSize() != null) {
                optionsBuilder.setPageSize(paging.getMaxSize());
            }
            QName orderByAttributeName;
            boolean isAscending;
            ItemPath orderByPath = paging.getOrderBy();
            String desc;
            if (orderByPath != null && !orderByPath.isEmpty()) {
                orderByAttributeName = ShadowUtil.getAttributeName(orderByPath, "OrderBy path");
                if (SchemaConstants.C_NAME.equals(orderByAttributeName)) {
                    orderByAttributeName = SchemaConstants.ICFS_NAME;
                }
                isAscending = paging.getDirection() != OrderDirection.DESCENDING;
                desc = "(explicitly specified orderBy attribute)";
            } else {
                orderByAttributeName = pagedSearchCapabilityType.getDefaultSortField();
                isAscending = pagedSearchCapabilityType.getDefaultSortDirection() != OrderDirectionType.DESCENDING;
                desc = "(default orderBy attribute from capability definition)";
            }
            if (orderByAttributeName != null) {
                String orderByIcfName = connIdNameMapper.convertAttributeNameToIcf(orderByAttributeName, objectClassDefinition, desc);
                optionsBuilder.setSortKeys(new SortKey(orderByIcfName, isAscending));
            }
        }
        if (searchHierarchyConstraints != null) {
            ResourceObjectIdentification baseContextIdentification = searchHierarchyConstraints.getBaseContext();
            // Only LDAP connector really supports base context. And this one will work better with
            // DN. And DN is secondary identifier (__NAME__). This is ugly, but practical. It works around ConnId problems.
            ResourceAttribute<?> secondaryIdentifier = baseContextIdentification.getSecondaryIdentifier();
            if (secondaryIdentifier == null) {
                SchemaException e = new SchemaException("No secondary identifier in base context identification " + baseContextIdentification);
                result.recordFatalError(e);
                throw e;
            }
            String secondaryIdentifierValue = secondaryIdentifier.getRealValue(String.class);
            ObjectClass baseContextIcfObjectClass = connIdNameMapper.objectClassToIcf(baseContextIdentification.getObjectClassDefinition(), getSchemaNamespace(), connectorType, legacySchema);
            QualifiedUid containerQualifiedUid = new QualifiedUid(baseContextIcfObjectClass, new Uid(secondaryIdentifierValue));
            optionsBuilder.setContainer(containerQualifiedUid);
        }
    } catch (SchemaException e) {
        result.recordFatalError(e);
        throw e;
    }
    // Relax completeness requirements. This is a search, not get. So it is OK to
    // return incomplete member lists and similar attributes.
    optionsBuilder.setAllowPartialAttributeValues(true);
    OperationOptions options = optionsBuilder.build();
    Filter filter;
    try {
        filter = convertFilterToIcf(query, objectClassDefinition);
    } catch (SchemaException | RuntimeException e) {
        result.recordFatalError(e);
        throw e;
    }
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".search");
    icfResult.addArbitraryObjectAsParam("objectClass", icfObjectClass);
    icfResult.addContext("connector", connIdConnectorFacade.getClass());
    SearchResult icfSearchResult;
    try {
        InternalMonitor.recordConnectorOperation("search");
        recordIcfOperationStart(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        icfSearchResult = connIdConnectorFacade.search(icfObjectClass, filter, icfHandler, options);
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        icfResult.recordSuccess();
    } catch (IntermediateException inex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, inex);
        SchemaException ex = (SchemaException) inex.getCause();
        icfResult.recordFatalError(ex);
        result.recordFatalError(ex);
        throw ex;
    } catch (Throwable ex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, ex);
        Throwable midpointEx = processIcfException(ex, this, icfResult);
        result.computeStatus();
        // exception
        if (midpointEx instanceof CommunicationException) {
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof ObjectNotFoundException) {
            throw (ObjectNotFoundException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof SecurityViolationException) {
            throw (SecurityViolationException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    SearchResultMetadata metadata = null;
    if (icfSearchResult != null) {
        metadata = new SearchResultMetadata();
        metadata.setPagingCookie(icfSearchResult.getPagedResultsCookie());
        if (icfSearchResult.getRemainingPagedResults() >= 0) {
            metadata.setApproxNumberOfAllResults(icfSearchResult.getRemainingPagedResults());
        }
        if (!icfSearchResult.isAllResultsReturned()) {
            metadata.setPartialResults(true);
        }
    }
    if (result.isUnknown()) {
        result.recordSuccess();
    }
    return metadata;
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) SortKey(org.identityconnectors.framework.common.objects.SortKey) GuardedString(org.identityconnectors.common.security.GuardedString) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) PagedSearchCapabilityType(com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.PagedSearchCapabilityType) SystemException(com.evolveum.midpoint.util.exception.SystemException) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) QName(javax.xml.namespace.QName) Holder(com.evolveum.midpoint.util.Holder) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) SearchResultMetadata(com.evolveum.midpoint.schema.SearchResultMetadata) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) SyncResultsHandler(org.identityconnectors.framework.common.objects.SyncResultsHandler) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) Uid(org.identityconnectors.framework.common.objects.Uid) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) ObjectPaging(com.evolveum.midpoint.prism.query.ObjectPaging) Filter(org.identityconnectors.framework.common.objects.filter.Filter) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 59 with SystemException

use of com.evolveum.midpoint.util.exception.SystemException in project midpoint by Evolveum.

the class ExpressionUtil method convertValue.

/**
	 * Slightly more powerful version of "convert" as compared to
	 * JavaTypeConverter. This version can also encrypt/decrypt and also handles
	 * polystrings.
	 */
public static <I, O> O convertValue(Class<O> finalExpectedJavaType, Function<Object, Object> additionalConvertor, I inputVal, Protector protector, PrismContext prismContext) {
    if (inputVal == null) {
        return null;
    }
    if (finalExpectedJavaType.isInstance(inputVal)) {
        return (O) inputVal;
    }
    Object intermediateVal;
    if (finalExpectedJavaType == ProtectedStringType.class) {
        String valueToEncrypt;
        if (inputVal instanceof String) {
            valueToEncrypt = (String) inputVal;
        } else {
            valueToEncrypt = JavaTypeConverter.convert(String.class, inputVal);
        }
        try {
            intermediateVal = protector.encryptString(valueToEncrypt);
        } catch (EncryptionException e) {
            throw new SystemException(e.getMessage(), e);
        }
    } else if (inputVal instanceof ProtectedStringType) {
        try {
            intermediateVal = protector.decryptString((ProtectedStringType) inputVal);
        } catch (EncryptionException e) {
            throw new SystemException(e.getMessage(), e);
        }
    } else {
        intermediateVal = inputVal;
    }
    if (additionalConvertor != null) {
        intermediateVal = additionalConvertor.apply(intermediateVal);
    }
    O convertedVal = JavaTypeConverter.convert(finalExpectedJavaType, intermediateVal);
    PrismUtil.recomputeRealValue(convertedVal, prismContext);
    return convertedVal;
}
Also used : SystemException(com.evolveum.midpoint.util.exception.SystemException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)

Example 60 with SystemException

use of com.evolveum.midpoint.util.exception.SystemException in project midpoint by Evolveum.

the class AuditEventRecord method createAuditEventRecordType.

public AuditEventRecordType createAuditEventRecordType(boolean tolerateInconsistencies) {
    AuditEventRecordType auditRecordType = new AuditEventRecordType();
    auditRecordType.setChannel(channel);
    auditRecordType.setEventIdentifier(eventIdentifier);
    auditRecordType.setEventStage(AuditEventStage.fromAuditEventStage(eventStage));
    auditRecordType.setEventType(AuditEventType.fromAuditEventType(eventType));
    auditRecordType.setHostIdentifier(hostIdentifier);
    auditRecordType.setRemoteHostAddress(remoteHostAddress);
    auditRecordType.setNodeIdentifier(nodeIdentifier);
    auditRecordType.setInitiatorRef(ObjectTypeUtil.createObjectRef(initiator, true));
    auditRecordType.setMessage(message);
    auditRecordType.setOutcome(OperationResultStatus.createStatusType(outcome));
    auditRecordType.setParameter(parameter);
    auditRecordType.setResult(result);
    auditRecordType.setSessionIdentifier(sessionIdentifier);
    auditRecordType.setTargetOwnerRef(ObjectTypeUtil.createObjectRef(targetOwner, true));
    auditRecordType.setTargetRef(ObjectTypeUtil.createObjectRef(target, true));
    auditRecordType.setTaskIdentifier(taskIdentifier);
    auditRecordType.setTaskOID(taskOID);
    auditRecordType.setTimestamp(MiscUtil.asXMLGregorianCalendar(timestamp));
    for (ObjectDeltaOperation delta : deltas) {
        ObjectDeltaOperationType odo = new ObjectDeltaOperationType();
        try {
            DeltaConvertor.toObjectDeltaOperationType(delta, odo, DeltaConversionOptions.createSerializeReferenceNames());
            auditRecordType.getDelta().add(odo);
        } catch (Exception e) {
            if (tolerateInconsistencies) {
                if (delta.getExecutionResult() != null) {
                    // TODO does this even work? [med]
                    delta.getExecutionResult().setMessage("Could not show audit record, bad data in delta: " + delta.getObjectDelta());
                } else {
                    OperationResult result = new OperationResult("Create audit event record type");
                    result.setMessage("Could not show audit record, bad data in delta: " + delta.getObjectDelta());
                    odo.setExecutionResult(result.createOperationResultType());
                }
                continue;
            } else {
                throw new SystemException(e.getMessage(), e);
            }
        }
    }
    for (Map.Entry<String, Set<String>> propertyEntry : properties.entrySet()) {
        AuditEventRecordPropertyType propertyType = new AuditEventRecordPropertyType();
        propertyType.setName(propertyEntry.getKey());
        propertyType.getValue().addAll(propertyEntry.getValue());
        auditRecordType.getProperty().add(propertyType);
    }
    for (Map.Entry<String, Set<AuditReferenceValue>> referenceEntry : references.entrySet()) {
        AuditEventRecordReferenceType referenceType = new AuditEventRecordReferenceType();
        referenceType.setName(referenceEntry.getKey());
        referenceEntry.getValue().forEach(v -> referenceType.getValue().add(v.toXml()));
        auditRecordType.getReference().add(referenceType);
    }
    return auditRecordType;
}
Also used : AuditEventRecordReferenceType(com.evolveum.midpoint.xml.ns._public.common.audit_3.AuditEventRecordReferenceType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) SystemException(com.evolveum.midpoint.util.exception.SystemException) ObjectDeltaOperationType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType) ObjectDeltaOperation(com.evolveum.midpoint.schema.ObjectDeltaOperation) SystemException(com.evolveum.midpoint.util.exception.SystemException) AuditEventRecordType(com.evolveum.midpoint.xml.ns._public.common.audit_3.AuditEventRecordType) AuditEventRecordPropertyType(com.evolveum.midpoint.xml.ns._public.common.audit_3.AuditEventRecordPropertyType)

Aggregations

SystemException (com.evolveum.midpoint.util.exception.SystemException)201 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)113 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)76 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)65 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)35 PrismObject (com.evolveum.midpoint.prism.PrismObject)32 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)32 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)31 QName (javax.xml.namespace.QName)28 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)26 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)26 Task (com.evolveum.midpoint.task.api.Task)23 ArrayList (java.util.ArrayList)21 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)16 GenericFrameworkException (com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException)16 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)14 Test (org.testng.annotations.Test)14 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)12 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)12 ResultHandler (com.evolveum.midpoint.schema.ResultHandler)12