Example usage for org.hibernate.collection.spi PersistentCollection getOwner

List of usage examples for org.hibernate.collection.spi PersistentCollection getOwner

Introduction

In this page you can find the example usage for org.hibernate.collection.spi PersistentCollection getOwner.

Prototype

Object getOwner();

Source Link

Document

Get the owning entity.

Usage

From source file:ch.algotrader.cache.CollectionHandler.java

License:Open Source License

@Override
protected CacheResponse update(Object obj) {

    if (!(obj instanceof PersistentCollection)) {
        throw new IllegalArgumentException("none PersistentCollection passed " + obj);
    }//from w w  w . ja va2 s . co m

    PersistentCollection origCollection = (PersistentCollection) obj;

    // sometimes there is no role so collection initialization will not work
    if (origCollection.getRole() == null) {
        return CacheResponse.skippedObject();
    }

    synchronized (obj) {

        Object updatedCollection = this.cacheManager.getGenericDao()
                .getInitializedCollection(origCollection.getRole(), (Long) origCollection.getKey());

        // owner does not exist anymore so remove it
        if (updatedCollection == null) {

            Object owner = origCollection.getOwner();
            EntityCacheKey cacheKey = new EntityCacheKey((BaseEntityI) owner);
            this.cacheManager.getEntityCache().detach(cacheKey);

            return CacheResponse.removedObject();

        } else {

            if (updatedCollection instanceof PersistentCollection) {

                // copy the updatedCollection unto the origCollection in order to update entities holding a reference to the origCollection
                FieldUtil.copyAllFields(updatedCollection, origCollection);

                // make sure all elements of the updateCollection are in the cache
                ArrayList<EntityCacheSubKey> stack = new ArrayList<EntityCacheSubKey>();
                put(updatedCollection, stack);

                // getInitializedCollection should normally return a PersistentCollection
            } else {

                if (updatedCollection instanceof Collection) {
                    Collection<?> col = (Collection<?>) updatedCollection;
                    if (col.size() != 0) {
                        LOGGER.error("non empty collection returned instead of PersistentCollection");
                    }
                } else if (updatedCollection instanceof Map) {
                    Map<?, ?> map = (Map<?, ?>) updatedCollection;
                    if (map.size() != 0) {
                        LOGGER.error("non empty map returned instead of PersistentCollection");
                    }
                }
            }

            return CacheResponse.updatedObject(updatedCollection);
        }
    }
}

From source file:com.blazebit.security.impl.interceptor.ChangeInterceptor.java

License:Apache License

/**
 * // www. j a  va2s .c  om
 */
@Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
    if (!EntityFeatures.isInterceptorActive()) {
        super.onCollectionUpdate(collection, key);
        return;
    }
    if (collection instanceof PersistentCollection) {
        PersistentCollection newValuesCollection = (PersistentCollection) collection;
        Object entity = newValuesCollection.getOwner();
        if (AnnotationUtils.findAnnotation(entity.getClass(), EntityResourceType.class) == null) {
            super.onCollectionUpdate(collection, key);
            return;
        }
        // copy new values and old values
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Collection<?> newValues = new HashSet((Collection<?>) newValuesCollection.getValue());
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Set<?> oldValues = new HashSet(((Map<?, ?>) newValuesCollection.getStoredSnapshot()).keySet());

        String fieldName = StringUtils.replace(newValuesCollection.getRole(), entity.getClass().getName() + ".",
                "");
        UserContext userContext = BeanProvider.getContextualReference(UserContext.class);
        ActionFactory actionFactory = BeanProvider.getContextualReference(ActionFactory.class);
        EntityResourceFactory resourceFactory = BeanProvider
                .getContextualReference(EntityResourceFactory.class);
        PermissionService permissionService = BeanProvider.getContextualReference(PermissionService.class);

        // find all objects that were added
        boolean isGrantedToAdd = true;
        boolean isGrantedToRemove = true;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        Set<?> retained = new HashSet(oldValues);
        retained.retainAll(newValues);

        oldValues.removeAll(retained);
        // if there is a difference between oldValues and newValues
        if (!oldValues.isEmpty()) {
            // if something remained
            isGrantedToRemove = permissionService.isGranted(actionFactory.createAction(Action.REMOVE),
                    resourceFactory.createResource(entity, fieldName));
        }
        newValues.removeAll(retained);
        if (!newValues.isEmpty()) {
            isGrantedToAdd = permissionService.isGranted(actionFactory.createAction(Action.ADD),
                    resourceFactory.createResource(entity, fieldName));
        }

        if (!isGrantedToAdd) {
            throw new PermissionActionException("Element cannot be added to entity " + entity + "'s collection "
                    + fieldName + " by " + userContext.getUser());
        } else {
            if (!isGrantedToRemove) {
                throw new PermissionActionException("Element cannot be removed from entity " + entity
                        + "'s collection " + fieldName + " by " + userContext.getUser());
            } else {
                super.onCollectionUpdate(collection, key);
                return;
            }
        }
    } else {
        // not a persistent collection?
    }
}

From source file:org.nextframework.persistence.HibernateUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static <E> E getLazyValue(E value) {
    if (value instanceof HibernateProxy) {
        LazyInitializer hibernateLazyInitializer = ((HibernateProxy) value).getHibernateLazyInitializer();
        if (hibernateLazyInitializer.isUninitialized()) {
            try {
                Class<?> superclass = value.getClass().getSuperclass();
                Serializable identifier = hibernateLazyInitializer.getIdentifier();

                value = loadValue(value, superclass, identifier);
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            }/*from  w  ww.j a  v  a 2s  .  co m*/
        }
    } else if (value instanceof PersistentCollection) {
        try {
            PersistentCollection collection = (PersistentCollection) value;
            if (!collection.wasInitialized()) {
                Object owner = collection.getOwner();
                String role = collection.getRole();
                value = (E) DAOUtils.getDAOForClass(owner.getClass()).loadCollection(owner,
                        role.substring(role.lastIndexOf('.') + 1));
                System.out.println("COLECAO LAZY " + owner.getClass().getSimpleName() + "." + role);
            }
        } catch (Exception e) {
            //se nao conseguir carregar o valor lazy, no fazer nada
        }
    }
    return value;
}