Example usage for org.springframework.orm.hibernate5 SessionFactoryUtils convertHibernateAccessException

List of usage examples for org.springframework.orm.hibernate5 SessionFactoryUtils convertHibernateAccessException

Introduction

In this page you can find the example usage for org.springframework.orm.hibernate5 SessionFactoryUtils convertHibernateAccessException.

Prototype

public static DataAccessException convertHibernateAccessException(HibernateException ex) 

Source Link

Document

Convert the given HibernateException to an appropriate exception from the org.springframework.dao hierarchy.

Usage

From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java

protected DataAccessException convertHibernateAccessException(HibernateException ex) {
    if (ex instanceof JDBCException) {
        return convertJdbcAccessException((JDBCException) ex, jdbcExceptionTranslator);
    }//from  w  w  w  .j a  va 2  s.c  om
    if (GenericJDBCException.class.equals(ex.getClass())) {
        return convertJdbcAccessException((GenericJDBCException) ex, jdbcExceptionTranslator);
    }
    return SessionFactoryUtils.convertHibernateAccessException(ex);
}

From source file:org.springframework.orm.hibernate5.HibernateTemplate.java

/**
 * Execute the action specified by the given action object within a Session.
 * @param action callback object that specifies the Hibernate action
 * @param enforceNativeSession whether to enforce exposure of the native
 * Hibernate Session to callback code/*from   www.  j  a  v  a  2  s  .c om*/
 * @return a result object returned by the action, or {@code null}
 * @throws DataAccessException in case of Hibernate errors
 */
@SuppressWarnings("deprecation")
@Nullable
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession)
        throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");

    Session session = null;
    boolean isNew = false;
    try {
        session = obtainSessionFactory().getCurrentSession();
    } catch (HibernateException ex) {
        logger.debug("Could not retrieve pre-bound Hibernate session", ex);
    }
    if (session == null) {
        session = obtainSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        isNew = true;
    }

    try {
        enableFilters(session);
        Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session
                : createSessionProxy(session));
        return action.doInHibernate(sessionToExpose);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw SessionFactoryUtils.convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (isNew) {
            SessionFactoryUtils.closeSession(session);
        } else {
            disableFilters(session);
        }
    }
}

From source file:org.springframework.orm.hibernate5.HibernateTemplate.java

@Override
public void initialize(Object proxy) throws DataAccessException {
    try {/*w  w  w .jav a2 s  .c  om*/
        Hibernate.initialize(proxy);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    }
}

From source file:org.springframework.orm.hibernate5.HibernateTemplate.java

@Deprecated
@Override/*ww  w. j a v a  2  s .  co m*/
public void closeIterator(Iterator<?> it) throws DataAccessException {
    try {
        Hibernate.close(it);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.CalendarDaoImpl.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/* w w  w.java2s  .c o m*/
public Set<ICalendarItem> findCalendarItems(CollectionItem collection, CalendarFilter filter) {
    try {
        CalendarFilterConverter filterConverter = new CalendarFilterConverter();
        try {
            if (collection instanceof HibCollectionItem) {
                // Translate CalendarFilter to ItemFilter and execute filter. This does not make sense for external collections which are
                ItemFilter itemFilter = filterConverter.translateToItemFilter(collection, filter);
                Set results = itemFilterProcessor.processFilter(itemFilter);
                return (Set<ICalendarItem>) results;
            }
        } catch (Exception e) {
            /* Set this log message to debug because all iPad requests trigger it and log files get polluted. */
            LOG.debug("Illegal filter item. Only VCALENDAR is supported so far.", e);
        }
        /*
         * Use brute-force method if CalendarFilter can't be translated to an ItemFilter (slower but at least gets
         * the job done).
         */
        Set<ICalendarItem> results = new HashSet<ICalendarItem>();
        Set<Item> itemsToProcess = collection.getChildren();

        /*
         * Optimization: Do a first pass query if possible to reduce the number of items that needs to be examined.
         * Otherwise we have to examine all items.
         */
        /* TODO Left only for historical reasons.
         * ItemFilter firstPassItemFilter = filterConverter.getFirstPassFilter(collection, filter); if
         * (firstPassItemFilter != null) { itemsToProcess = itemFilterProcessor.processFilter(firstPassItemFilter);
         * } else { itemsToProcess = collection.getChildren(); }
         */

        CalendarFilterEvaluater evaluater = new CalendarFilterEvaluater();

        // Evaluate filter against all calendar items
        for (Item child : itemsToProcess) {

            // only care about calendar items
            if (child instanceof ICalendarItem) {

                ICalendarItem content = (ICalendarItem) child;
                Calendar calendar = entityConverter.convertContent(content);

                if (calendar != null && evaluater.evaluate(calendar, filter)) {
                    results.add(content);
                }
            }
        }

        return results;
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.CalendarDaoImpl.java

public Set<ContentItem> findEvents(CollectionItem collection, Date rangeStart, Date rangeEnd, String timezoneId,
        boolean expandRecurringEvents) {

    // Create a NoteItemFilter that filters by parent
    NoteItemFilter itemFilter = new NoteItemFilter();
    itemFilter.setParent(collection);//  ww  w. java 2 s  . c om

    // and EventStamp by timeRange
    EventStampFilter eventFilter = new EventStampFilter();

    if (timezoneId != null) {
        TimeZone timeZone = TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone(timezoneId);
        eventFilter.setTimezone(timeZone);
    }

    eventFilter.setTimeRange(rangeStart, rangeEnd);
    eventFilter.setExpandRecurringEvents(expandRecurringEvents);
    itemFilter.getStampFilters().add(eventFilter);

    try {
        Set results = itemFilterProcessor.processFilter(itemFilter);
        return (Set<ContentItem>) results;
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.CalendarDaoImpl.java

public ContentItem findEventByIcalUid(String uid, CollectionItem calendar) {
    try {/*  w w  w  .  j a  v  a  2s  . c  om*/
        Query<ContentItem> query = this.getSession().createNamedQuery("event.by.calendar.icaluid",
                ContentItem.class);
        query.setParameter("calendar", calendar);
        query.setParameter("uid", uid);
        List<ContentItem> resultList = query.getResultList();
        if (!resultList.isEmpty()) {
            return resultList.get(0);
        }
        return null;
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ContentDaoImpl.java

public CollectionItem createCollection(CollectionItem parent, CollectionItem collection) {

    if (parent == null) {
        throw new IllegalArgumentException("parent cannot be null");
    }/*from   w  w w  .j  a va  2 s.c  om*/

    if (collection == null) {
        throw new IllegalArgumentException("collection cannot be null");
    }

    if (collection.getOwner() == null) {
        throw new IllegalArgumentException("collection must have owner");
    }

    if (getBaseModelObject(collection).getId() != -1) {
        throw new IllegalArgumentException("invalid collection id (expected -1)");
    }

    try {
        // verify uid not in use
        checkForDuplicateUid(collection);

        setBaseItemProps(collection);
        ((HibItem) collection).addParent(parent);

        getSession().save(collection);
        getSession().flush();

        return collection;
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    } catch (ConstraintViolationException cve) {
        logConstraintViolationException(cve);
        throw cve;
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ContentDaoImpl.java

/**
 * Updates collection.//from  www. j a v  a  2  s  .  co  m
 */
public CollectionItem updateCollection(CollectionItem collection, Set<ContentItem> children) {

    // Keep track of duplicate icalUids because we don't flush
    // the db until the end so we need to handle the case of 
    // duplicate icalUids in the same request.
    HashMap<String, NoteItem> icalUidMap = new HashMap<String, NoteItem>();

    try {
        updateCollectionInternal(collection);

        // Either create, update, or delete each item
        for (ContentItem item : children) {

            // Because we batch all the db operations, we must check
            // for duplicate icalUid within the same request
            if (item instanceof NoteItem && ((NoteItem) item).getIcalUid() != null) {
                NoteItem note = (NoteItem) item;
                if (item.getIsActive() == true) {
                    NoteItem dup = icalUidMap.get(note.getIcalUid());
                    if (dup != null && !dup.getUid().equals(item.getUid())) {
                        throw new IcalUidInUseException("iCal uid" + note.getIcalUid()
                                + " already in use for collection " + collection.getUid(), item.getUid(),
                                dup.getUid());
                    }
                }

                icalUidMap.put(note.getIcalUid(), note);
            }

            // create item
            if (getBaseModelObject(item).getId() == -1) {
                createContentInternal(collection, item);
            }
            // delete item
            else if (item.getIsActive() == false) {
                // If item is a note modification, only remove the item
                // if its parent is not also being removed.  This is because
                // when a master item is removed, all its modifications are
                // removed.
                if (item instanceof NoteItem) {
                    NoteItem note = (NoteItem) item;
                    if (note.getModifies() != null && note.getModifies().getIsActive() == false) {
                        continue;
                    }
                }
                removeItemFromCollectionInternal(item, collection);
            }
            // update item
            else {
                if (!item.getParents().contains(collection)) {

                    // If item is being added to another collection,
                    // we need the ticket/perms to add that item.
                    // If ticket exists, then add with ticket and ticket perms.
                    // If ticket doesn't exist, but item uuid is present in
                    // itemPerms map, then add with read-only access.

                    addItemToCollectionInternal(item, collection);
                }

                updateContentInternal(item);
            }
        }

        getSession().flush();

        // clear the session to improve subsequent flushes
        getSession().clear();

        // load collection to get it back into the session
        getSession().load(collection, getBaseModelObject(collection).getId());

        return collection;
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    } catch (ConstraintViolationException cve) {
        logConstraintViolationException(cve);
        throw cve;
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ContentDaoImpl.java

public ContentItem createContent(CollectionItem parent, ContentItem content) {

    try {//from  w  ww. ja v a  2  s. c o m
        createContentInternal(parent, content);
        getSession().flush();
        return content;
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    } catch (ConstraintViolationException cve) {
        logConstraintViolationException(cve);
        throw cve;
    }
}