Example usage for org.hibernate CallbackException CallbackException

List of usage examples for org.hibernate CallbackException CallbackException

Introduction

In this page you can find the example usage for org.hibernate CallbackException CallbackException.

Prototype

public CallbackException(String message) 

Source Link

Document

Creates a CallbackException using the given message.

Usage

From source file:com.fiveamsolutions.nci.commons.audit.AuditLogInterceptor.java

License:Open Source License

/**
 * {@inheritDoc}//from   w  ww  . j av  a  2s  . c o  m
 */
@Override
@SuppressWarnings("deprecation")
public void postFlush(Iterator arg0) {

    if (audits.get() != null && !audits.get().isEmpty()) {
        SessionFactory sf = getHibernateHelper().getSessionFactory();
        Session session = sf.openSession(getHibernateHelper().getCurrentSession().connection());
        Long transactionId = null;
        try {
            transactionId = getTxIdGenerator().generateId(getDialect(), session);

            // Resolve the new entity values on the audit log record itself, then save
            Iterator<AuditLogHelper> it = audits.get().iterator();
            while (it.hasNext()) {
                AuditLogHelper audit = it.next();
                it.remove();
                audit.getAuditLogRecord().setTransactionId(transactionId);
                Serializable id = (Serializable) audit.getIdGetter().get(audit.getEntity());
                audit.getAuditLogRecord().setEntityId((Long) id);

                for (DetailHelper detail : audit.getDetails()) {
                    processor.processDetail(audit.getAuditLogRecord(), audit.getEntity(), id,
                            detail.getProperty(), detail.getColumnName(), detail.getOldVal(),
                            detail.getNewVal());
                }
                session.save(audit.getAuditLogRecord());
            }
            session.flush();
        } catch (HibernateException e) {
            LOG.error(e);
            throw new CallbackException(e);
        } finally {
            audits.get().clear();
            records.get().clear();
            session.close();
        }
    }
}

From source file:com.utest.dao.AuditTrailInterceptor.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  ww w  .  j a v a 2s . c  o  m*/
public void postFlush(final Iterator entities) throws CallbackException {
    final Session session = sessionFactory.openSession();

    try {
        while (!logRecords.isEmpty()) {
            final AuditRecord logRecord = logRecords.firstElement();
            logRecords.remove(logRecord);
            if (AuditRecord.INSERT.equals(logRecord.getEventId())) {
                final Integer id = getObjectId(logRecord.getEntityObject());
                if (id != null) {
                    logRecord.setEntityId(getObjectId(logRecord.getEntityObject()));
                    session.save(logRecord);
                } else {
                    session.evict(logRecord);
                }
            } else {
                session.save(logRecord);
            }
        }
    } catch (final HibernateException e) {
        throw new CallbackException(e);
    } finally {
        // logRecords.clear();
        session.flush();
        session.close();
    }

}

From source file:gov.nih.nci.caarray.util.CaArrayAuditLogInterceptor.java

License:BSD License

/**
 * {@inheritDoc}/*from   w ww  . ja va2s . c  om*/
 */
@Override
public void postFlush(Iterator arg0) {

    if (audits.get() != null && !audits.get().isEmpty()) {
        SessionFactory sf = getHibernateHelper().getSessionFactory();
        @SuppressWarnings("deprecation")
        Session session = sf.openSession(getHibernateHelper().getCurrentSession().connection());
        Long transactionId = null;
        try {
            transactionId = getTxIdGenerator().generateId(getDialect(), session);

            // Resolve the new entity values on the audit log record itself, then save
            Iterator<AuditLogHelper> it = audits.get().iterator();
            while (it.hasNext()) {
                AuditLogHelper audit = it.next();
                it.remove();
                audit.getAuditLogRecord().setTransactionId(transactionId);
                Serializable id = (Serializable) audit.getIdGetter().get(audit.getEntity());
                audit.getAuditLogRecord().setEntityId((Long) id);

                for (DetailHelper detail : audit.getDetails()) {
                    processor.processDetail(audit.getAuditLogRecord(), audit.getEntity(), id,
                            detail.getProperty(), detail.getColumnName(), detail.getOldVal(),
                            detail.getNewVal());
                }
                session.save(audit.getAuditLogRecord());
            }
            // This code was added for ARRAY-1933, which required access to the session to save the audit log
            // security entries. This should be incorporated into AuditLogInterceptor and DefaultProcessor in
            // nci-commons.  See ARRAY-2496.
            ((CaArrayAuditLogProcessor) this.processor).postProcessDetail(session, records.get().values());
            session.flush();
        } catch (HibernateException e) {
            LOG.error(e);
            throw new CallbackException(e);
        } finally {
            audits.get().clear();
            records.get().clear();
            session.close();
        }
    }
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

License:Open Source License

/**
 * Processes changes to hibernate collections. At the moment, only persistent sets are
 * supported./*  w  w w .ja v a2  s .c  o m*/
 * <p>
 * Remarks: Note that simple lists and maps of primitive types are supported also by default via
 * normalizers and do not require explicit handling as shown here for sets of any reference
 * types.
 * <p>
 *
 * @param collection Instance of Hibernate AbstractPersistentCollection to process.
 * @param key key of owner for the collection.
 * @param action hibernate 'action' being performed: update, recreate. note, deletes are handled
 *            via re-create
 */
protected void processHibernateCollection(AbstractPersistentCollection collection, Serializable key,
        String action) {

    if (!(collection instanceof PersistentSet || collection instanceof PersistentMap
            || collection instanceof PersistentList)) {
        log.debug("Unsupported collection type, collection type was:" + collection.getClass().getName());
        return;
    }

    OpenmrsObject owner = null;
    String originalRecordUuid = null;
    LinkedHashMap<String, OpenmrsObject> entriesHolder = null;

    // we only process recreate and update
    if (!"update".equals(action) && !"recreate".equals(action)) {
        log.error("Unexpected 'action' supplied, valid values: recreate, update. value provided: " + action);
        throw new CallbackException("Unexpected 'action' supplied while processing a persistent set.");
    }

    // retrieve owner and original uuid if there is one
    if (collection.getOwner() instanceof OpenmrsObject) {
        owner = (OpenmrsObject) collection.getOwner();

        if (!this.shouldSynchronize(owner)) {
            if (log.isDebugEnabled())
                log.debug("Determined entity not to be journaled, exiting onDelete.");
            return;
        }

        originalRecordUuid = getSyncRecord().getOriginalUuid();

    } else {
        log.debug("Cannot process collection where owner is not OpenmrsObject.");
        return;
    }

    /*
     * determine if this set needs to be processed. Process if: 1. it is
     * recreate or 2. is dirty && current state does not equal stored
     * snapshot
     */
    boolean process = false;
    if ("recreate".equals(action)) {
        process = true;
    } else {
        if (collection.isDirty()) {
            org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory())
                    .getCollectionPersister(collection.getRole());
            Object ss = null;
            try { // code around hibernate bug:
                  // http://opensource.atlassian.com/projects/hibernate/browse/HHH-2937
                ss = collection.getSnapshot(persister);
            } catch (NullPointerException ex) {
            }
            if (ss == null) {
                log.debug("snapshot is null");
                if (collection.empty())
                    process = false;
                else
                    process = true;
            } else if (!collection.equalsSnapshot(persister)) {
                process = true;
            }
            ;
        }

        if (!process) {
            log.debug("set processing, no update needed: not dirty or current state and snapshots are same");
        }
    }
    if (!process)
        return;

    // pull out the property name on owner that corresponds to the collection
    ClassMetadata data = getSessionFactory().getClassMetadata(owner.getClass());
    String[] propNames = data.getPropertyNames();
    // this is the name of the property on owner object that contains the set
    String ownerPropertyName = null;

    for (String propName : propNames) {
        Object propertyVal = data.getPropertyValue(owner, propName, org.hibernate.EntityMode.POJO);
        // note: test both with equals() and == because
        // PersistentSet.equals()
        // actually does not handle equality of two persistent sets well
        if (collection == propertyVal || collection.equals(propertyVal)) {
            ownerPropertyName = propName;
            break;
        }
    }
    if (ownerPropertyName == null) {
        log.error(
                "Could not find the property on owner object that corresponds to the collection being processed.");
        log.error("owner info: \ntype: " + owner.getClass().getName() + ", \nuuid: " + owner.getUuid()
                + ",\n property name for collection: " + ownerPropertyName);
        throw new CallbackException(
                "Could not find the property on owner object that corresponds to the collection being processed.");
    }

    //now we know this needs to be processed. Proceed accordingly:
    if (collection instanceof PersistentSet || collection instanceof PersistentList
            || collection instanceof PersistentMap) {
        processPersistentCollection(collection, key, action, originalRecordUuid, owner, ownerPropertyName);
    }

    return;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

License:Open Source License

/**
 * Processes changes to persistent collection that contains instances of OpenmrsObject objects.
 * <p>/*from   w ww.  j av a  2 s .c o m*/
 * Remarks:
 * <p>
 * Xml 'schema' for the sync item content for the persisted collection follows. Note that for persisted
 * collections syncItemKey is a composite of owner object uuid and the property name that contains the
 * collection. <br/>
 * &lt;persistent-collection&gt; element: wrapper element <br/>
 * &lt;owner uuid='' propertyName='' type='' action='recreate|update' &gt; element: this
 * captures the information about the object that holds reference to the collection being
 * processed <br/>
 * -uuid: owner object uuid <br/>
 * -properyName: names of the property on owner object that holds this collection <br/>
 * -type: owner class name <br/>
 * -action: recreate, update -- these are collection events defined by hibernate interceptor <br/>
 * &lt;entry action='update|delete' uuid='' type='' &gt; element: this captures info about
 * individual collection entries: <br/>
 * -action: what is being done to this item of the collection: delete (item was removed from the
 * collection) or update (item was added to the collection) <br/>
 * -uuid: entry's uuid <br/>
 * -type: class name
 *
 * @param collection Instance of Hibernate AbstractPersistentCollection to process.
 * @param key key of owner for the collection.
 * @param action action being performed on the collection: update, recreate
 */
private void processPersistentCollection(AbstractPersistentCollection collection, Serializable key,
        String action, String originalRecordUuid, OpenmrsObject owner, String ownerPropertyName) {

    LinkedHashMap<String, OpenmrsObject> entriesHolder = null;

    // Setup the serialization data structures to hold the state
    Package pkg = new Package();
    entriesHolder = new LinkedHashMap<String, OpenmrsObject>();
    try {

        CollectionMetadata collMD = getCollectionMetadata(owner.getClass(), ownerPropertyName,
                getSessionFactory());
        if (collMD == null) {
            throw new SyncException(
                    "Can't find a collection with " + ownerPropertyName + " in class " + owner.getClass());
        }

        Class<?> elementClass = collMD.getElementType().getReturnedClass();
        //If this is a simple type like Integer, serialization of the collection will be as below:
        //<org.openmrs.Cohort>
        //   <memberIds type="java.util.Set(org.openmrs.Cohort)">[2, 3]</memberIds>
        //  ............. and more
        //This should work just fine as long as there is a Normalizer registered for it
        if (!OpenmrsObject.class.isAssignableFrom(elementClass)
                && SyncUtil.getNormalizer(elementClass) != null) {

            //Check if there is already a NEW/UPDATE sync item for the owner
            SyncItem syncItem = new SyncItem();
            syncItem.setKey(new SyncItemKey<String>(owner.getUuid(), String.class));
            syncItem.setContainedType(owner.getClass());
            syncItem.setState(SyncItemState.UPDATED);

            boolean ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);
            syncItem.setState(SyncItemState.NEW);
            if (!ownerHasSyncItem)
                ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);

            if (!ownerHasSyncItem) {
                ClassMetadata cmd = getSessionFactory().getClassMetadata(owner.getClass());
                //create an UPDATE sync item for the owner so that the collection changes get recorded along
                Serializable primaryKeyValue = cmd.getIdentifier(owner,
                        (SessionImplementor) getSessionFactory().getCurrentSession());
                packageObject(owner, cmd.getPropertyValues(owner, EntityMode.POJO), cmd.getPropertyNames(),
                        cmd.getPropertyTypes(), primaryKeyValue, SyncItemState.UPDATED);
            } else {
                //There is already an UPDATE OR NEW SyncItem for the owner containing the above updates
            }

            return;
        }
        // find out what entries need to be serialized
        for (Object entry : (Iterable) collection) {
            if (entry instanceof OpenmrsObject) {
                OpenmrsObject obj = (OpenmrsObject) entry;

                // attempt to retrieve entry uuid
                String entryUuid = obj.getUuid();
                if (entryUuid == null) {
                    entryUuid = fetchUuid(obj);
                    if (log.isDebugEnabled()) {
                        log.debug("Entry uuid was null, attempted to fetch uuid with the following results");
                        log.debug("Entry type:" + obj.getClass().getName() + ",uuid:" + entryUuid);
                    }
                }
                // well, this is messed up: have an instance of
                // OpenmrsObject but has no uuid
                if (entryUuid == null) {
                    log.error("Cannot handle collection entries where uuid is null.");
                    throw new CallbackException("Cannot handle collection entries where uuid is null.");
                }

                // add it to the holder to avoid possible duplicates: key =
                // uuid + action
                entriesHolder.put(entryUuid + "|update", obj);
            } else {
                log.warn(
                        "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers. Type was "
                                + entry.getClass() + " in property " + ownerPropertyName + " in class "
                                + owner.getClass());
                // skip out early because we don't want to write any xml for it
                // it was handled by the normal property writer hopefully
                return;
            }
        }

        // add on deletes
        if (!"recreate".equals(action) && collection.getRole() != null) {
            org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory())
                    .getCollectionPersister(collection.getRole());
            Iterator it = collection.getDeletes(persister, false);
            if (it != null) {
                while (it.hasNext()) {
                    Object entryDelete = it.next();
                    if (entryDelete instanceof OpenmrsObject) {
                        OpenmrsObject objDelete = (OpenmrsObject) entryDelete;
                        // attempt to retrieve entry uuid
                        String entryDeleteUuid = objDelete.getUuid();
                        if (entryDeleteUuid == null) {
                            entryDeleteUuid = fetchUuid(objDelete);
                            if (log.isDebugEnabled()) {
                                log.debug(
                                        "Entry uuid was null, attempted to fetch uuid with the following results");
                                log.debug("Entry type:" + entryDeleteUuid.getClass().getName() + ",uuid:"
                                        + entryDeleteUuid);
                            }
                        }
                        // well, this is messed up: have an instance of
                        // OpenmrsObject but has no uuid
                        if (entryDeleteUuid == null) {
                            log.error("Cannot handle collection delete entries where uuid is null.");
                            throw new CallbackException(
                                    "Cannot handle collection delete entries where uuid is null.");
                        }

                        // add it to the holder to avoid possible
                        // duplicates: key = uuid + action
                        // also, only add if there is no update action for the same object: see SYNC-280
                        if (!entriesHolder.containsKey(entryDeleteUuid + "|update")) {
                            entriesHolder.put(entryDeleteUuid + "|delete", objDelete);
                        }

                    } else {
                        // TODO: more debug info
                        log.warn(
                                "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers!");
                        // skip out early because we don't want to write any
                        // xml for it. it
                        // was handled by the normal property writer
                        // hopefully
                        return;
                    }
                }
            }
        }

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal. note: when making SyncItemKey, make it a composite
         * string of uuid + prop. name to avoid collisions with updates to
         * parent object or updates to more than one collection on same
         * owner
         */

        // Setup the serialization data structures to hold the state
        Record xml = pkg.createRecordForWrite(collection.getClass().getName());
        Item entityItem = xml.getRootItem();

        // serialize owner info: we will need type, prop name where collection
        // goes, and owner uuid
        Item item = xml.createItem(entityItem, "owner");
        item.setAttribute("type", this.getType(owner));
        item.setAttribute("properyName", ownerPropertyName);
        item.setAttribute("action", action);
        item.setAttribute("uuid", owner.getUuid());

        // build out the xml for the item content
        Boolean hasNoAutomaticPrimaryKey = null;
        String type = null;
        for (String entryKey : entriesHolder.keySet()) {
            OpenmrsObject entryObject = entriesHolder.get(entryKey);
            if (type == null) {
                type = this.getType(entryObject);
                hasNoAutomaticPrimaryKey = SyncUtil.hasNoAutomaticPrimaryKey(type);
            }

            Item temp = xml.createItem(entityItem, "entry");
            temp.setAttribute("type", type);
            temp.setAttribute("action", entryKey.substring(entryKey.indexOf('|') + 1));
            temp.setAttribute("uuid", entryObject.getUuid());
            if (hasNoAutomaticPrimaryKey) {
                temp.setAttribute("primaryKey", getSyncService().getPrimaryKey(entryObject));
            }
        }

        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(owner.getUuid() + "|" + ownerPropertyName, String.class));
        syncItem.setState(SyncItemState.UPDATED);
        syncItem.setContainedType(collection.getClass());
        syncItem.setContent(xml.toStringAsDocumentFragement());

        getSyncRecord().addOrRemoveAndAddItem(syncItem);
        getSyncRecord().addContainedClass(owner.getClass().getName());

        // do the original uuid dance, same as in packageObject
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (Exception ex) {
        log.error("Error processing Persistent collection, see callstack and inner expection", ex);
        throw new CallbackException(
                "Error processing Persistent collection, see callstack and inner expection.", ex);
    }
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

License:Open Source License

/**
 * Returns string representation of type for given object. The main idea is to strip off the
 * hibernate proxy info, if it happens to be present.
 *
 * @param obj object//from w  w  w  . j  av  a 2s .  c o m
 * @return
 */
private String getType(Object obj) {

    // be defensive about it
    if (obj == null) {
        throw new CallbackException("Error trying to determine type for object; object is null.");
    }

    Object concreteObj = obj;
    if (obj instanceof org.hibernate.proxy.HibernateProxy) {
        concreteObj = ((HibernateProxy) obj).getHibernateLazyInitializer().getImplementation();
    }

    return concreteObj.getClass().getName();
}

From source file:org.riotfamily.common.hibernate.EntityListenerInterceptor.java

License:Apache License

@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
        throws CallbackException {

    getInterceptions().entityDeleted(entity);
    for (EntityListener listener : getListeners(entity)) {
        try {//from   w ww.j  ava2  s. c om
            listener.onDelete(entity, sessionFactory.getCurrentSession());
        } catch (Exception e) {
            throw new CallbackException(e);
        }
    }
}

From source file:org.riotfamily.common.hibernate.EntityListenerInterceptor.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void postFlush(Iterator entities) {
    final Interceptions i = getInterceptions();
    if (!i.isEmpty()) {
        interceptions.set(i.nested());//from  w w  w  .ja va 2  s . co  m
        try {
            template.execute(new HibernateCallbackWithoutResult() {
                @Override
                public void doWithoutResult(Session session) throws Exception {
                    for (Object entity : i.getSavedEntities()) {
                        for (EntityListener listener : getListeners(entity)) {
                            listener.onSave(entity, session);
                        }
                    }
                    for (Update update : i.getUpdates()) {
                        Object newState = update.getEntity();
                        for (EntityListener listener : getListeners(newState)) {
                            listener.onUpdate(newState, update.getOldState(), session);
                        }
                    }
                    session.flush();
                }
            });
            sessionFactory.getCurrentSession().flush();
        } catch (Exception e) {
            throw new CallbackException(e);
        } finally {
            i.closeOldStateSession();
        }
    }
}

From source file:org.tonguetied.audit.AuditLog.java

License:Apache License

/**
 * Create an audit log entry and save in persistent storage.
 * /* w ww.  ja  v a  2s  . c o  m*/
 * @param message the message describing the action taken
 * @param entity the object being logged
 * @param newValue the new values of attributes of the entity
 * @param oldValue the previous values of attributes of the entity
 * @param implementor
 * @throws CallbackException
 */
public static synchronized void logEvent(final Operation message, Auditable entity, final String newValue,
        final String oldValue, SessionFactoryImplementor implementor) throws CallbackException {
    Session tempSession = null;
    Transaction tx = null;
    try {
        // Use a separate session for saving audit log records
        tempSession = implementor.openSession();
        tx = tempSession.beginTransaction();

        tx.begin();
        final AuditLogRecord record = new AuditLogRecord(message, entity, newValue, oldValue, getUsername());

        tempSession.save(record);
        tx.commit();
        if (logger.isDebugEnabled())
            logger.debug("successfully saved audit log record: " + record);
    } catch (HibernateException ex) {
        if (logger.isInfoEnabled())
            logger.info("rolling back transation ");
        if (tx != null)
            tx.rollback();
        throw new CallbackException(ex);
    } finally {
        if (tempSession != null)
            tempSession.close();
    }
}

From source file:org.tsm.concharto.audit.AuditInterceptor.java

License:Apache License

public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
        String[] propertyNames, Type[] types) throws CallbackException {
    boolean updated = false;
    if (entity instanceof Auditable) {
        //log.debug("onFlushDirty");
        Session session = sessionFactory.openSession();
        try {/*from  ww w . j a  v  a  2s .com*/
            Class<? extends Object> objectClass = entity.getClass();

            //update the lastModified field
            for (int i = 0; i < propertyNames.length; i++) {
                if ("lastModified".equals(propertyNames[i])) {
                    currentState[i] = new Date();
                    updated = true;
                } else if ("version".equals(propertyNames[i])) {
                    Long version = ((Long) (currentState[i]));
                    if (version == null) {
                        currentState[i] = 0L;
                    } else {
                        currentState[i] = ++version;
                    }
                    updated = true;
                }
            }

            // Use the id and class to get the pre-update state from the
            // database
            Serializable persistedObjectId = ((Auditable) entity).getId();
            Object previousInstance = session.get(objectClass, persistedObjectId);
            refresh((Auditable) entity);
            refresh((Auditable) previousInstance);
            UpdateState state = new UpdateState((Auditable) entity, (Auditable) previousInstance);
            stateSets.getUpdates().add(state);

        } catch (HibernateException e) {
            clearStateSets();
            throw new CallbackException(e);
        } finally {
            session.close();
        }
    }
    return updated;
}