Search in sources :

Example 1 with RObject

use of com.evolveum.midpoint.repo.sql.data.common.RObject in project midpoint by Evolveum.

the class SequenceHelper method returnUnusedValuesToSequenceAttempt.

public void returnUnusedValuesToSequenceAttempt(String oid, Collection<Long> unusedValues, OperationResult result) throws ObjectNotFoundException, SchemaException, SerializationRelatedException {
    LOGGER.debug("Returning unused values of {} to a sequence with oid '{}'.", unusedValues, oid);
    LOGGER_PERFORMANCE.debug("> return unused values, oid={}, values={}", oid, unusedValues);
    Session session = null;
    try {
        session = baseHelper.beginTransaction();
        PrismObject<SequenceType> prismObject = objectRetriever.getObjectInternal(session, SequenceType.class, oid, null, true, result);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("OBJECT before:\n{}", prismObject.debugDump());
        }
        SequenceType sequence = prismObject.asObjectable();
        int maxUnusedValues = sequence.getMaxUnusedValues() != null ? sequence.getMaxUnusedValues() : 0;
        Iterator<Long> valuesToReturnIterator = unusedValues.iterator();
        while (valuesToReturnIterator.hasNext() && sequence.getUnusedValues().size() < maxUnusedValues) {
            Long valueToReturn = valuesToReturnIterator.next();
            if (valueToReturn == null) {
                // sanity check
                continue;
            }
            if (!sequence.getUnusedValues().contains(valueToReturn)) {
                sequence.getUnusedValues().add(valueToReturn);
            } else {
                LOGGER.warn("UnusedValues in sequence {} already contains value of {} - ignoring the return request", oid, valueToReturn);
            }
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("OBJECT after:\n{}", prismObject.debugDump());
        }
        // merge and update object
        LOGGER.trace("Translating JAXB to data type.");
        RObject rObject = objectUpdater.createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY);
        rObject.setVersion(rObject.getVersion() + 1);
        objectUpdater.updateFullObject(rObject, prismObject);
        session.merge(rObject);
        LOGGER.trace("Before commit...");
        session.getTransaction().commit();
        LOGGER.trace("Committed!");
    } catch (ObjectNotFoundException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        // should always throw an exception
        baseHelper.handleGeneralException(ex, session, result);
        // ...so this shouldn't occur at all
        throw new SystemException("Exception " + ex + " was not handled correctly", ex);
    } finally {
        baseHelper.cleanupSessionAndResult(session, result);
        LOGGER.trace("Session cleaned up.");
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) SequenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.SequenceType) DtoTranslationException(com.evolveum.midpoint.repo.sql.util.DtoTranslationException) SystemException(com.evolveum.midpoint.util.exception.SystemException) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) Session(org.hibernate.Session)

Example 2 with RObject

use of com.evolveum.midpoint.repo.sql.data.common.RObject in project midpoint by Evolveum.

the class SequenceHelper method advanceSequenceAttempt.

public long advanceSequenceAttempt(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException, SerializationRelatedException {
    long returnValue;
    LOGGER.debug("Advancing sequence with oid '{}'.", oid);
    LOGGER_PERFORMANCE.debug("> advance sequence, oid={}", oid);
    Session session = null;
    try {
        session = baseHelper.beginTransaction();
        PrismObject<SequenceType> prismObject = objectRetriever.getObjectInternal(session, SequenceType.class, oid, null, true, result);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("OBJECT before:\n{}", prismObject.debugDump());
        }
        SequenceType sequence = prismObject.asObjectable();
        if (!sequence.getUnusedValues().isEmpty()) {
            returnValue = sequence.getUnusedValues().remove(0);
        } else {
            long counter = sequence.getCounter() != null ? sequence.getCounter() : 0L;
            long maxCounter = sequence.getMaxCounter() != null ? sequence.getMaxCounter() : Long.MAX_VALUE;
            boolean allowRewind = Boolean.TRUE.equals(sequence.isAllowRewind());
            if (counter < maxCounter) {
                returnValue = counter;
                sequence.setCounter(counter + 1);
            } else if (counter == maxCounter) {
                returnValue = counter;
                if (allowRewind) {
                    sequence.setCounter(0L);
                } else {
                    // will produce exception during next run
                    sequence.setCounter(counter + 1);
                }
            } else {
                // i.e. counter > maxCounter
                if (allowRewind) {
                    // shouldn't occur but...
                    LOGGER.warn("Sequence {} overflown with allowRewind set to true. Rewinding.", oid);
                    returnValue = 0;
                    sequence.setCounter(1L);
                } else {
                    // TODO some better exception...
                    throw new SystemException("No (next) value available from sequence " + oid + ". Current counter = " + sequence.getCounter() + ", max value = " + sequence.getMaxCounter());
                }
            }
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Return value = {}, OBJECT after:\n{}", returnValue, prismObject.debugDump());
        }
        // merge and update object
        LOGGER.trace("Translating JAXB to data type.");
        RObject rObject = objectUpdater.createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY);
        rObject.setVersion(rObject.getVersion() + 1);
        objectUpdater.updateFullObject(rObject, prismObject);
        session.merge(rObject);
        LOGGER.trace("Before commit...");
        session.getTransaction().commit();
        LOGGER.trace("Committed!");
        return returnValue;
    } catch (ObjectNotFoundException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        // should always throw an exception
        baseHelper.handleGeneralException(ex, session, result);
        // ...so this shouldn't occur at all
        throw new SystemException("Exception " + ex + " was not handled correctly", ex);
    } finally {
        baseHelper.cleanupSessionAndResult(session, result);
        LOGGER.trace("Session cleaned up.");
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) DtoTranslationException(com.evolveum.midpoint.repo.sql.util.DtoTranslationException) SystemException(com.evolveum.midpoint.util.exception.SystemException) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) SequenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.SequenceType) Session(org.hibernate.Session)

Example 3 with RObject

use of com.evolveum.midpoint.repo.sql.data.common.RObject in project midpoint by Evolveum.

the class ClassDefinitionParser method parseMethod.

private JpaLinkDefinition parseMethod(Method method) {
    // non-null if return type is Set<X>, null if it's X
    CollectionSpecification collectionSpecification;
    // X in return type, which is either X or Set<X>
    Type returnedContentType;
    if (Set.class.isAssignableFrom(method.getReturnType())) {
        // e.g. Set<RObject> or Set<String> or Set<REmbeddedReference<RFocus>>
        Type returnType = method.getGenericReturnType();
        if (!(returnType instanceof ParameterizedType)) {
            throw new IllegalStateException("Method " + method + " returns a non-parameterized collection");
        }
        returnedContentType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
        collectionSpecification = new CollectionSpecification();
    } else {
        returnedContentType = method.getReturnType();
        collectionSpecification = null;
    }
    ItemPath itemPath = getJaxbName(method);
    String jpaName = getJpaName(method);
    Class jpaClass = getClass(returnedContentType);
    // sanity check
    if (Set.class.isAssignableFrom(jpaClass)) {
        throw new IllegalStateException("Collection within collection is not supported: method=" + method);
    }
    JpaLinkDefinition<? extends JpaDataNodeDefinition> linkDefinition;
    Any any = method.getAnnotation(Any.class);
    if (any != null) {
        JpaAnyContainerDefinition targetDefinition = new JpaAnyContainerDefinition(jpaClass);
        QName jaxbNameForAny = new QName(any.jaxbNameNamespace(), any.jaxbNameLocalPart());
        linkDefinition = new JpaLinkDefinition<>(jaxbNameForAny, jpaName, collectionSpecification, false, targetDefinition);
    } else if (ObjectReference.class.isAssignableFrom(jpaClass)) {
        boolean embedded = method.isAnnotationPresent(Embedded.class);
        // computing referenced entity type from returned content type like RObjectReference<RFocus> or REmbeddedReference<RRole>
        Class referencedJpaClass;
        if (returnedContentType instanceof ParameterizedType) {
            referencedJpaClass = getClass(((ParameterizedType) returnedContentType).getActualTypeArguments()[0]);
        } else {
            referencedJpaClass = RObject.class;
        }
        JpaReferenceDefinition targetDefinition = new JpaReferenceDefinition(jpaClass, referencedJpaClass);
        linkDefinition = new JpaLinkDefinition<>(itemPath, jpaName, collectionSpecification, embedded, targetDefinition);
    } else if (isEntity(jpaClass)) {
        JpaEntityDefinition content = parseClass(jpaClass);
        boolean embedded = method.isAnnotationPresent(Embedded.class) || jpaClass.isAnnotationPresent(Embeddable.class);
        linkDefinition = new JpaLinkDefinition<JpaDataNodeDefinition>(itemPath, jpaName, collectionSpecification, embedded, content);
    } else {
        boolean lob = method.isAnnotationPresent(Lob.class);
        boolean enumerated = method.isAnnotationPresent(Enumerated.class);
        //todo implement also lookup for @Table indexes
        boolean indexed = method.isAnnotationPresent(Index.class);
        boolean count = method.isAnnotationPresent(Count.class);
        Class jaxbClass = getJaxbClass(method, jpaClass);
        if (method.isAnnotationPresent(IdQueryProperty.class)) {
            if (collectionSpecification != null) {
                throw new IllegalStateException("ID property is not allowed to be multivalued; for method " + method);
            }
            itemPath = new ItemPath(new IdentifierPathSegment());
        } else if (method.isAnnotationPresent(OwnerIdGetter.class)) {
            if (collectionSpecification != null) {
                throw new IllegalStateException("Owner ID property is not allowed to be multivalued; for method " + method);
            }
            itemPath = new ItemPath(new ParentPathSegment(), new IdentifierPathSegment());
        }
        JpaPropertyDefinition propertyDefinition = new JpaPropertyDefinition(jpaClass, jaxbClass, lob, enumerated, indexed, count);
        // Note that properties are considered to be embedded
        linkDefinition = new JpaLinkDefinition<JpaDataNodeDefinition>(itemPath, jpaName, collectionSpecification, true, propertyDefinition);
    }
    return linkDefinition;
}
Also used : RPolyString(com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString) ParameterizedType(java.lang.reflect.ParameterizedType) ObjectReference(com.evolveum.midpoint.repo.sql.data.common.ObjectReference) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) Embedded(javax.persistence.Embedded) IdentifierPathSegment(com.evolveum.midpoint.prism.path.IdentifierPathSegment) ParentPathSegment(com.evolveum.midpoint.prism.path.ParentPathSegment) QName(javax.xml.namespace.QName) Embeddable(javax.persistence.Embeddable) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 4 with RObject

use of com.evolveum.midpoint.repo.sql.data.common.RObject in project midpoint by Evolveum.

the class ObjectUpdater method createDataObjectFromJAXB.

public <T extends ObjectType> RObject createDataObjectFromJAXB(PrismObject<T> prismObject, PrismIdentifierGenerator.Operation operation) throws SchemaException {
    PrismIdentifierGenerator generator = new PrismIdentifierGenerator();
    IdGeneratorResult generatorResult = generator.generate(prismObject, operation);
    T object = prismObject.asObjectable();
    RObject rObject;
    Class<? extends RObject> clazz = ClassMapper.getHQLTypeClass(object.getClass());
    try {
        rObject = clazz.newInstance();
        Method method = clazz.getMethod("copyFromJAXB", object.getClass(), clazz, RepositoryContext.class, IdGeneratorResult.class);
        method.invoke(clazz, object, rObject, new RepositoryContext(repositoryService, prismContext), generatorResult);
    } catch (Exception ex) {
        String message = ex.getMessage();
        if (StringUtils.isEmpty(message) && ex.getCause() != null) {
            message = ex.getCause().getMessage();
        }
        throw new SchemaException(message, ex);
    }
    return rObject;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) RepositoryContext(com.evolveum.midpoint.repo.sql.data.RepositoryContext) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) IdGeneratorResult(com.evolveum.midpoint.repo.sql.util.IdGeneratorResult) PrismIdentifierGenerator(com.evolveum.midpoint.repo.sql.util.PrismIdentifierGenerator) Method(java.lang.reflect.Method) SerializationRelatedException(com.evolveum.midpoint.repo.sql.SerializationRelatedException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) DtoTranslationException(com.evolveum.midpoint.repo.sql.util.DtoTranslationException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) SQLException(java.sql.SQLException)

Example 5 with RObject

use of com.evolveum.midpoint.repo.sql.data.common.RObject in project midpoint by Evolveum.

the class ObjectUpdater method deleteObjectAttempt.

public <T extends ObjectType> void deleteObjectAttempt(Class<T> type, String oid, OperationResult result) throws ObjectNotFoundException {
    LOGGER_PERFORMANCE.debug("> delete object {}, oid={}", new Object[] { type.getSimpleName(), oid });
    Session session = null;
    OrgClosureManager.Context closureContext = null;
    try {
        session = baseHelper.beginTransaction();
        closureContext = closureManager.onBeginTransactionDelete(session, type, oid);
        Criteria query = session.createCriteria(ClassMapper.getHQLTypeClass(type));
        query.add(Restrictions.eq("oid", oid));
        RObject object = (RObject) query.uniqueResult();
        if (object == null) {
            throw new ObjectNotFoundException("Object of type '" + type.getSimpleName() + "' with oid '" + oid + "' was not found.", null, oid);
        }
        closureManager.updateOrgClosure(null, null, session, oid, type, OrgClosureManager.Operation.DELETE, closureContext);
        session.delete(object);
        if (LookupTableType.class.equals(type)) {
            lookupTableHelper.deleteLookupTableRows(session, oid);
        }
        if (AccessCertificationCampaignType.class.equals(type)) {
            caseHelper.deleteCertificationCampaignCases(session, oid);
        }
        session.getTransaction().commit();
    } catch (ObjectNotFoundException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        cleanupClosureAndSessionAndResult(closureContext, session, result);
    }
}
Also used : RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) Criteria(org.hibernate.Criteria) Session(org.hibernate.Session)

Aggregations

RObject (com.evolveum.midpoint.repo.sql.data.common.RObject)10 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)6 DtoTranslationException (com.evolveum.midpoint.repo.sql.util.DtoTranslationException)5 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)5 Session (org.hibernate.Session)5 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)3 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)3 PrismIdentifierGenerator (com.evolveum.midpoint.repo.sql.util.PrismIdentifierGenerator)2 SystemException (com.evolveum.midpoint.util.exception.SystemException)2 SequenceType (com.evolveum.midpoint.xml.ns._public.common.common_3.SequenceType)2 IdentifierPathSegment (com.evolveum.midpoint.prism.path.IdentifierPathSegment)1 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)1 ParentPathSegment (com.evolveum.midpoint.prism.path.ParentPathSegment)1 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)1 SerializationRelatedException (com.evolveum.midpoint.repo.sql.SerializationRelatedException)1 RepositoryContext (com.evolveum.midpoint.repo.sql.data.RepositoryContext)1 ObjectReference (com.evolveum.midpoint.repo.sql.data.common.ObjectReference)1 RPolyString (com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString)1 RQuery (com.evolveum.midpoint.repo.sql.query.RQuery)1 IdGeneratorResult (com.evolveum.midpoint.repo.sql.util.IdGeneratorResult)1