List of usage examples for org.hibernate.collection.spi PersistentCollection getRole
String getRole();
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); }// w ww .j a va 2 s .c o 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
/** * /*from www .j av a 2 s. 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:net.e6tech.elements.persist.hibernate.Interceptor.java
License:Apache License
@SuppressWarnings("squid:CommentedOutCodeLine") protected void publishCollectionChanged(Object collection) { if (notificationCenter != null && collection instanceof PersistentCollection) { PersistentCollection coll = (PersistentCollection) collection; boolean cached = false; if (sessionFactory != null) { cached = sessionFactory.getMetamodel().collectionPersister(coll.getRole()).hasCache(); }// www . j av a2 s . c om /* Another way of doing it EntityManager em = resources.getInstance(EntityManager.class); Cache cache = em.unwrap(Session.class).getSessionFactory().getCache(); boolean cached = cache.containsCollection(coll.getRole(), key); */ if (cached) { // publisher.publish(EntityManagerProvider.CACHE_EVICT_COLLECTION_REGION, coll.getRole()); // center.fireNotification(new EvictCollectionRegion(coll.getRole())); notificationCenter.publish(EvictCollectionRegion.class, new EvictCollectionRegion(coll.getRole())); } } }
From source file:org.babyfish.hibernate.internal.SessionImplWrapper.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void delete(XSessionImplementor sessionProxy, Object object) { if (object != null) { SessionFactory sessionFactory = sessionProxy.getRawSessionImpl().getSessionFactory(); PersistenceContext persistenceContext = ((org.hibernate.internal.SessionImpl) sessionProxy .getRawSessionImpl()).getPersistenceContext(); Map<PersistentCollection, CollectionEntry> collectionEntries = persistenceContext .getCollectionEntries(); for (Entry<PersistentCollection, CollectionEntry> entry : collectionEntries.entrySet()) { PersistentCollection persistentCollection = entry.getKey(); if (persistentCollection.wasInitialized()) { CollectionMetadata collectionMetadata = sessionFactory .getCollectionMetadata(persistentCollection.getRole()); Class<?> elementClass = collectionMetadata.getElementType().getReturnedClass(); if (elementClass.isAssignableFrom(object.getClass())) { if (persistentCollection instanceof Map<?, ?>) { ((Map<?, ?>) persistentCollection).values().remove(object); } else if (persistentCollection instanceof Collection<?>) { ((Collection<?>) persistentCollection).remove(object); }/*from w ww .j a v a2 s . c o m*/ } } } Class<?> clazz = object.getClass(); Collection<HbmReference> hbmReferences = null; NavigableMap<Class<?>, Collection<HbmReference>> hbmReferencesByTargetClass = (NavigableMap<Class<?>, Collection<HbmReference>>) ((XSessionFactoryImplementor) sessionProxy .getFactory()).getInternalData(SessionFactoryImplWrapper.IDK_HBM_REFERENCES_BY_TARGET_CLASS); for (Entry<Class<?>, Collection<HbmReference>> entry : hbmReferencesByTargetClass.descendingMap() .entrySet()) { if (entry.getKey().isAssignableFrom(clazz)) { hbmReferences = entry.getValue(); break; } } if (hbmReferences != null) { EntityReferenceComparator<? super Object> referenceComparator = EntityReferenceComparator .getInstance(); Entry<Object, EntityEntry>[] entityEntries = persistenceContext.reentrantSafeEntityEntries(); if (entityEntries != null) { for (Entry<Object, EntityEntry> entry : entityEntries) { Object entity = entry.getKey(); if (Hibernate.isInitialized(entity)) { EntityPersister persister = entry.getValue().getPersister(); ClassMetadata classMetadata = persister.getClassMetadata(); for (HbmReference hbmReference : hbmReferences) { if (hbmReference.ownerMetadata == classMetadata) { Object expectedObject = persister.getPropertyValue(entity, hbmReference.propertyIndex); if (referenceComparator.same(expectedObject, object)) { persister.setPropertyValue(entity, hbmReference.propertyIndex, null); } } } } } } } } sessionProxy.getRawSessionImpl().delete(object); }
From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreChunkReader.java
License:Open Source License
public List<Chunk> executeRead() { // get a transaction, the hibernateStoreAccessor is placed in a threadlocal // so all db access uses the same session. final Session session = getAccessor().getHibernateSession(); // reread the revision as it is probably unreferenced final InternalCDORevision latestRevision = getLatestRevision(session); Object value = latestRevision.getValue(getFeature()); if (value instanceof WrappedHibernateList) { value = ((WrappedHibernateList) value).getDelegate(); }/*from w ww.jav a 2 s.co m*/ // hibernate details... boolean useExtraLazyMode = false; boolean standardCDOList = false; QueryableCollection persister = null; CollectionEntry entry = null; if (value instanceof PersistentCollection) { final PersistentCollection persistentCollection = (PersistentCollection) value; persister = (QueryableCollection) ((SessionFactoryImplementor) session.getSessionFactory()) .getCollectionPersister(persistentCollection.getRole()); entry = ((SessionImplementor) session).getPersistenceContext().getCollectionEntry(persistentCollection); useExtraLazyMode = !persister.getElementType().isEntityType(); if (useExtraLazyMode && ((PersistentCollection) value).hasQueuedOperations()) { session.flush(); } } else { standardCDOList = true; } final List<Chunk> chunks = getChunks(); for (Chunk chunk : chunks) { final int startIndex = chunk.getStartIndex(); final int maxElements = chunk.size(); if (standardCDOList) { // for eattributes just read them all, no chunking there... final CDOList list = (CDOList) value; if (startIndex >= list.size()) { return chunks; } for (int i = startIndex; i < startIndex + maxElements; i++) { if (i >= list.size()) { break; } addToChunk(chunk, i - startIndex, list.get(i)); } } else if (useExtraLazyMode) { if (getFeature() instanceof EReference) { for (int i = startIndex; i < startIndex + maxElements; i++) { final Object object = persister.getElementByIndex(entry.getLoadedKey(), i, (SessionImplementor) session, latestRevision); // could happen if the index > size) if (object == null) { continue; } addToChunk(chunk, i - startIndex, object); } } else { // for eattributes just read them all, no chunking there... final List<?> list = (List<?>) value; if (startIndex >= list.size()) { return chunks; } for (int i = startIndex; i < startIndex + maxElements; i++) { if (i >= list.size()) { break; } addToChunk(chunk, i - startIndex, list.get(i)); } } } else { final Query filterQuery = session.createFilter(value, ""); filterQuery.setMaxResults(maxElements); filterQuery.setFirstResult(startIndex); int i = 0; for (Object object : filterQuery.list()) { addToChunk(chunk, i++, object); } } } return chunks; }
From source file:org.granite.hibernate4.HibernateExternalizer.java
License:Open Source License
protected AbstractExternalizablePersistentCollection newExternalizableCollection(PersistentCollection value) { final boolean initialized = Hibernate.isInitialized(value); final boolean dirty = value.isDirty(); AbstractExternalizablePersistentCollection coll = null; if (value instanceof PersistentSet) coll = new ExternalizablePersistentSet(initialized ? (Set<?>) value : null, initialized, dirty); else if (value instanceof PersistentList) coll = new ExternalizablePersistentList(initialized ? (List<?>) value : null, initialized, dirty); else if (value instanceof PersistentBag) coll = new ExternalizablePersistentBag(initialized ? (List<?>) value : null, initialized, dirty); else if (value instanceof PersistentMap) coll = new ExternalizablePersistentMap(initialized ? (Map<?, ?>) value : null, initialized, dirty); else/* w w w . j a v a2s .c o m*/ throw new UnsupportedOperationException("Unsupported Hibernate collection type: " + value); if (serializeMetadata != SerializeMetadata.NO && (serializeMetadata == SerializeMetadata.YES || !initialized) && value.getRole() != null) { char[] hexKey = StringUtil.bytesToHexChars(serializeSerializable(value.getKey())); char[] hexSnapshot = StringUtil.bytesToHexChars(serializeSerializable(value.getStoredSnapshot())); String metadata = new StringBuilder( hexKey.length + 1 + hexSnapshot.length + 1 + value.getRole().length()).append(hexKey) .append(':').append(hexSnapshot).append(':').append(value.getRole()).toString(); coll.setMetadata(metadata); } return coll; }
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 www . j a va 2 s . c o 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; }