Example usage for org.hibernate EmptyInterceptor INSTANCE

List of usage examples for org.hibernate EmptyInterceptor INSTANCE

Introduction

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

Prototype

Interceptor INSTANCE

To view the source code for org.hibernate EmptyInterceptor INSTANCE.

Click Source Link

Document

The singleton reference.

Usage

From source file:com.db4o.drs.hibernate.impl.HibernateReplicationProvider.java

License:Open Source License

public HibernateReplicationProvider(Configuration cfg, String name) {
    _name = name;//w  w  w . j  av  a 2 s.  c o  m
    _cfg = ReplicationConfiguration.decorate(cfg);

    if (SHOW_SQL) {
        _cfg.setProperty("hibernate.show_sql", "true");
    }

    new TablesCreatorImpl(_cfg).validateOrCreate();

    _cfg.setInterceptor(EmptyInterceptor.INSTANCE);

    EventListeners el = _cfg.getEventListeners();
    el.setFlushEventListeners(
            (FlushEventListener[]) Util.add(el.getFlushEventListeners(), _flushEventListener));

    _listener.configure(cfg);

    _sessionFactory = getConfiguration().buildSessionFactory();
    _session = _sessionFactory.openSession();
    _session.setFlushMode(FlushMode.COMMIT);
    _transaction = _session.beginTransaction();

    _listener.install(getSession(), cfg);

    _generator = GeneratorMap.get(_session);

    _alive = true;
}

From source file:com.db4o.drs.hibernate.impl.ObjectLifeCycleEventsListenerImpl.java

License:Open Source License

private void resetListeners(Configuration cfg) {
    cfg.setInterceptor(EmptyInterceptor.INSTANCE);
    EventListeners el = cfg.getEventListeners();

    PostUpdateEventListener[] o2 = el.getPostUpdateEventListeners();
    PostUpdateEventListener[] r2 = (PostUpdateEventListener[]) Util.removeElement(o2, this);
    if ((o2.length - r2.length) != 1)
        throw new RuntimeException("can't remove");
    el.setPostUpdateEventListeners(r2);// ww  w. ja va 2  s .  co  m

    PreDeleteEventListener[] o3 = el.getPreDeleteEventListeners();
    PreDeleteEventListener[] r3 = (PreDeleteEventListener[]) Util.removeElement(o3, this);
    if ((o3.length - r3.length) != 1)
        throw new RuntimeException("can't remove");
    el.setPreDeleteEventListeners(r3);

    PostInsertEventListener[] o4 = el.getPostInsertEventListeners();
    PostInsertEventListener[] r4 = (PostInsertEventListener[]) Util.removeElement(o4, this);
    if ((o4.length - r4.length) != 1)
        throw new RuntimeException("can't remove");

    FlushEventListener[] o5 = el.getFlushEventListeners();
    FlushEventListener[] r5 = (FlushEventListener[]) Util.removeElement(o5, this);
    if ((o5.length - r5.length) != 1)
        throw new RuntimeException("can't remove");

    el.setPostInsertEventListeners(r4);
}

From source file:com.picocontainer.persistence.hibernate.ScopedSessionTestCase.java

License:Open Source License

@Test
public void cannotSetInterceptorAfterConnectionRetrieved() {
    SessionFactory factory = (new ConstructableConfiguration("/hibernate.cfg.xml")).buildSessionFactory();
    ScopedSession session = new ScopedSession(factory);
    session.setInterceptor(EmptyInterceptor.INSTANCE);
    assertEquals(EmptyInterceptor.INSTANCE, session.getInterceptor());

    // Force creation of delegate interceptor.
    session.getDelegate();//w  w  w. ja v a  2 s .c  om

    try {
        session.setInterceptor(EmptyInterceptor.INSTANCE);
    } catch (IllegalStateException e) {
        // A-ok
        assertNotNull(e.getMessage());
    }

}

From source file:com.springsource.insight.samples.rest.RestfulRepositoryImplTest.java

License:Apache License

protected void manuallyStartDaoSession() {
    // simulate open session in view
    final SessionFactory sessFac = getSessionFactory();
    if (TransactionSynchronizationManager.hasResource(sessFac)) {
        // Do not modify the Session: just set the participate flag.
        _txParticipating = true;/*from   ww  w.  ja v a 2  s  . co m*/
    } else {
        // NOTE: the session factory interceptor is overridden by an empty one, because the
        // real interceptor may not function correctly in this test-specific setup.
        final Session session = SessionFactoryUtils.getSession(sessFac, EmptyInterceptor.INSTANCE, null);
        session.setFlushMode(FlushMode.AUTO);
        TransactionSynchronizationManager.bindResource(sessFac, new SessionHolder(session));
        logger.info("Started transaction context");
    }
}

From source file:edu.upenn.cis.ppod.model.PPodVersionInfoInterceptor.java

License:Apache License

/**
 * In a temporary session, grab the next available pPOD version number,
 * increment it, assign it to a {@code sessionFactory.getCurrentSession()}
 * and {@code PPodVersionInfo} in {@link #pPodVersionInfosBySession}, and
 * save (but not commit) it to the database.
 *//*from   ww  w. jav  a  2  s .co  m*/
private void initializePPodVersionInfo() {
    if (pPodVersionInfosBySession.containsKey(sessionFactory.getCurrentSession())) {
        // Already been called.
        return;
    }
    // there's no alternative to the deprecated method yet - see its
    // javadoc: it says "TBD".
    @SuppressWarnings("deprecation")
    final Session tempSession = sessionFactory.openSession(sessionFactory.getCurrentSession().connection(),
            EmptyInterceptor.INSTANCE);
    final IPPodVersionInfoDAO pPodVersionInfoDAO = hibernateDAOFactoryFactory.create(tempSession)
            .getPPodVersionInfoDAO();
    pPodVersionInfosBySession.put(sessionFactory.getCurrentSession(), pPodVersionInfoProvider.get()
            .setPPodVersion(pPodVersionInfoDAO.getMaxPPodVersion() + 1).setCreated(new Date()));
    tempSession.save(pPodVersionInfosBySession.get(sessionFactory.getCurrentSession()));
    tempSession.flush();
}

From source file:org.projectforge.database.XmlDump.java

License:Open Source License

/**
 * @param reader/*  www .  j  ava 2 s  .c  o m*/
 * @return Only for test cases.
 */
public XStreamSavingConverter restoreDatabase(final Reader reader) {
    final XStreamSavingConverter xstreamSavingConverter = new XStreamSavingConverter() {

        @Override
        protected Serializable getOriginalIdentifierValue(final Object obj) {
            return HibernateUtils.getIdentifier(obj);
        }

        @Override
        public Serializable onBeforeSave(final Session session, final Object obj) {
            log.info("Object " + obj);
            if (obj instanceof PFUserDO) {
                final PFUserDO user = (PFUserDO) obj;
                return save(user, user.getRights());
            } else if (obj instanceof AbstractRechnungDO<?>) {
                final AbstractRechnungDO<? extends AbstractRechnungsPositionDO> rechnung = (AbstractRechnungDO<?>) obj;
                final List<? extends AbstractRechnungsPositionDO> positions = rechnung.getPositionen();
                rechnung.setPositionen(null); // Need to nullable positions first (otherwise insert fails).
                final Serializable id = save(rechnung);
                if (positions != null) {
                    for (final AbstractRechnungsPositionDO pos : positions) {
                        if (pos.getKostZuweisungen() != null) {
                            final List<KostZuweisungDO> zuweisungen = pos.getKostZuweisungen();
                            pos.setKostZuweisungen(null); // Need to nullable first (otherwise insert fails).
                            save(pos);
                            if (pos instanceof RechnungsPositionDO) {
                                ((RechnungDO) rechnung).addPosition((RechnungsPositionDO) pos);
                            } else {
                                ((EingangsrechnungDO) rechnung).addPosition((EingangsrechnungsPositionDO) pos);
                            }
                            if (zuweisungen != null) {
                                for (final KostZuweisungDO zuweisung : zuweisungen) {
                                    pos.addKostZuweisung(zuweisung);
                                    save(zuweisung);
                                }
                            }
                        }
                    }
                }
                return id;
            } else if (obj instanceof AuftragDO) {
                final AuftragDO auftrag = (AuftragDO) obj;
                return save(auftrag, auftrag.getPositionen());
            }
            return super.onBeforeSave(session, obj);
        }
    };
    // UserRightDO is inserted on cascade while inserting PFUserDO.
    xstreamSavingConverter.appendIgnoredObjects(embeddedClasses);
    xstreamSavingConverter.appendOrderedType(PFUserDO.class, GroupDO.class, TaskDO.class, KundeDO.class,
            ProjektDO.class, Kost1DO.class, Kost2ArtDO.class, Kost2DO.class, AuftragDO.class, //
            RechnungDO.class, EingangsrechnungDO.class, EmployeeSalaryDO.class, KostZuweisungDO.class, //
            UserPrefEntryDO.class, UserPrefDO.class, //
            AccessEntryDO.class, GroupTaskAccessDO.class, ConfigurationDO.class);
    Session session = null;
    try {
        final SessionFactory sessionFactory = hibernate.getSessionFactory();
        session = sessionFactory.openSession(EmptyInterceptor.INSTANCE);
        session.setFlushMode(FlushMode.AUTO);
        final XStream xstream = new XStream(new DomDriver());
        xstream.setMode(XStream.ID_REFERENCES);
        xstreamSavingConverter.setSession(session);
        xstream.registerConverter(xstreamSavingConverter, 10);
        xstream.registerConverter(new UserRightIdSingleValueConverter(), 20);
        xstream.registerConverter(new UserPrefAreaSingleValueConverter(), 19);
        // alle Objekte Laden und speichern
        xstream.fromXML(reader);

        xstreamSavingConverter.saveObjects();
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(reader);
        if (session != null) {
            session.close();
        }
    }
    return xstreamSavingConverter;
}

From source file:org.projectforge.database.XmlDump.java

License:Open Source License

/**
 * Verify the imported dump.//from  w w w.j  a va2  s . co m
 * @return Number of checked objects. This number is negative if any error occurs (at least one object wasn't imported successfully).
 */
public int verifyDump(final XStreamSavingConverter xstreamSavingConverter) {
    final SessionFactory sessionFactory = hibernate.getSessionFactory();
    Session session = null;
    boolean hasError = false;
    try {
        session = sessionFactory.openSession(EmptyInterceptor.INSTANCE);
        session.setDefaultReadOnly(true);
        int counter = 0;
        for (final Map.Entry<Class<?>, List<Object>> entry : xstreamSavingConverter.getAllObjects()
                .entrySet()) {
            final List<Object> objects = entry.getValue();
            final Class<?> entityClass = entry.getKey();
            if (objects == null) {
                continue;
            }
            for (final Object obj : objects) {
                if (HibernateUtils.isEntity(obj.getClass()) == false) {
                    continue;
                }
                final Serializable id = HibernateUtils.getIdentifier(obj);
                if (id == null) {
                    // Can't compare this object without identifier.
                    continue;
                }
                // log.info("Testing object: " + obj);
                final Object databaseObject = session.get(entityClass, id, LockOptions.READ);
                Hibernate.initialize(databaseObject);
                final boolean equals = equals(obj, databaseObject, true);
                if (equals == false) {
                    log.error("Object not sucessfully imported! xml object=[" + obj + "], data base=["
                            + databaseObject + "]");
                    hasError = true;
                }
                ++counter;
            }
        }
        for (final HistoryEntry historyEntry : xstreamSavingConverter.getHistoryEntries()) {
            final Class<?> type = xstreamSavingConverter.getClassFromHistoryName(historyEntry.getClassName());
            final Object o = session.get(type, historyEntry.getEntityId());
            if (o == null) {
                log.error("A corrupted history entry found (entity of class '" + historyEntry.getClassName()
                        + "' with id + " + historyEntry.getEntityId() + " not found: " + historyEntry);
                hasError = true;
            }
            ++counter;
        }
        if (hasError == true) {
            log.fatal(
                    "*********** A inconsistency in the import was found! This may result in a data loss or corrupted data! Please retry the import. "
                            + counter + " entries checked.");
            return -counter;
        }
        log.info("Data-base import successfully verified: " + counter + " entries checked.");
        return counter;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.projectforge.framework.persistence.database.XmlDump.java

License:Open Source License

/**
 * @param reader/*www  . j  a v  a2s .c  o  m*/
 * @return Only for test cases.
 */
public XStreamSavingConverter restoreDatabase(final Reader reader) {
    final List<AbstractPlugin> plugins = pluginAdminService.getActivePlugin();
    final XStreamSavingConverter xstreamSavingConverter = new XStreamSavingConverter() {

        @Override
        protected Serializable getOriginalIdentifierValue(final Object obj) {
            return HibernateUtils.getIdentifier(obj);
        }

        @Override
        public Serializable onBeforeSave(final Session session, final Object obj) {
            log.info("Object " + obj);
            if (obj instanceof PFUserDO) {
                final PFUserDO user = (PFUserDO) obj;
                return save(user, user.getRights());
            } else if (obj instanceof AbstractRechnungDO<?>) {

                final AbstractRechnungDO<? extends AbstractRechnungsPositionDO> rechnung = (AbstractRechnungDO<?>) obj;
                final List<? extends AbstractRechnungsPositionDO> positions = rechnung.getPositionen();
                final KontoDO konto = rechnung.getKonto();
                if (konto != null) {
                    save(konto);
                    rechnung.setKonto(null);
                }
                rechnung.setPositionen(null); // Need to nullable positions first (otherwise insert fails).
                final Serializable id = save(rechnung);
                if (konto != null) {
                    rechnung.setKonto(konto);
                }
                if (positions != null) {
                    for (final AbstractRechnungsPositionDO pos : positions) {
                        if (pos.getKostZuweisungen() != null) {
                            final List<KostZuweisungDO> zuweisungen = pos.getKostZuweisungen();
                            pos.setKostZuweisungen(null); // Need to nullable first (otherwise insert fails).
                            save(pos);
                            if (pos instanceof RechnungsPositionDO) {
                                ((RechnungDO) rechnung).addPosition((RechnungsPositionDO) pos);
                            } else {
                                ((EingangsrechnungDO) rechnung).addPosition((EingangsrechnungsPositionDO) pos);
                            }
                            if (zuweisungen != null) {
                                for (final KostZuweisungDO zuweisung : zuweisungen) {
                                    pos.addKostZuweisung(zuweisung);
                                    save(zuweisung);
                                }
                            }
                        }
                    }
                }
                return id;
            } else if (obj instanceof AuftragDO) {
                final AuftragDO auftrag = (AuftragDO) obj;
                return save(auftrag, auftrag.getPositionen());
            }
            if (plugins != null) {
                for (final AbstractPlugin plugin : plugins) {
                    try {
                        plugin.onBeforeRestore(this, obj);
                    } catch (final Exception ex) {
                        log.error("Error in Plugin while restoring object: " + ex.getMessage(), ex);
                    }
                }
            }
            for (final XmlDumpHook xmlDumpHook : xmlDumpHooks) {
                try {
                    xmlDumpHook.onBeforeRestore(userXmlPreferencesDao, this, obj);
                } catch (final Exception ex) {
                    log.error("Error in XmlDumpHook while restoring object: " + ex.getMessage(), ex);
                }
            }
            return super.onBeforeSave(session, obj);
        }

        /**
         * @see org.projectforge.framework.persistence.xstream.XStreamSavingConverter#onAfterSave(java.lang.Object,
         *      java.io.Serializable)
         */
        @Override
        public void onAfterSave(final Object obj, final Serializable id) {
            if (plugins != null) {
                for (final AbstractPlugin plugin : plugins) {
                    plugin.onAfterRestore(this, obj, id);
                }
            }
        }
    };
    // UserRightDO is inserted on cascade while inserting PFUserDO.
    xstreamSavingConverter.appendIgnoredObjects(embeddedClasses);
    // automatically detect insert order.
    List<EntityMetadata> ents = emf.getMetadataRepository().getTableEntities();
    List<Class<?>> classList = ents.stream().map((e) -> e.getJavaType()).collect(Collectors.toList());
    // first entities with now deps
    Collections.reverse(classList);

    xstreamSavingConverter.appendOrderedType(PFUserDO.class, GroupDO.class, TaskDO.class, KundeDO.class,
            ProjektDO.class, Kost1DO.class, Kost2ArtDO.class, Kost2DO.class, AuftragDO.class, //
            RechnungDO.class, EingangsrechnungDO.class, EmployeeSalaryDO.class, KostZuweisungDO.class, //
            UserPrefEntryDO.class, UserPrefDO.class, //
            AccessEntryDO.class, GroupTaskAccessDO.class, ConfigurationDO.class);
    xstreamSavingConverter.appendOrderedType(classList.toArray(new Class<?>[] {}));

    //    if (plugins != null) {
    //      for (final AbstractPlugin plugin : plugins) {
    //        xstreamSavingConverter.appendOrderedType(plugin.getPersistentEntities());
    //      }
    //    }
    Session session = null;
    try {
        final SessionFactory sessionFactory = hibernate.getSessionFactory();
        session = HibernateCompatUtils.openSession(sessionFactory, EmptyInterceptor.INSTANCE);
        session.setFlushMode(FlushMode.AUTO);
        final XStream xstream = XStreamHelper.createXStream();
        xstream.setMode(XStream.ID_REFERENCES);
        xstreamSavingConverter.setSession(session);
        xstream.registerConverter(xstreamSavingConverter, 10);
        xstream.registerConverter(new UserRightIdSingleValueConverter(userRights), 20);
        xstream.registerConverter(new UserPrefAreaSingleValueConverter(), 19);
        // alle Objekte Laden und speichern
        xstream.fromXML(reader);

        xstreamSavingConverter.saveObjects();
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(reader);
        if (session != null) {
            session.close();
        }
    }
    return xstreamSavingConverter;
}

From source file:org.projectforge.framework.persistence.database.XmlDump.java

License:Open Source License

/**
 * Verify the imported dump./*from w  w w  . j  a v  a 2s . co m*/
 * 
 * @return Number of checked objects. This number is negative if any error occurs (at least one object wasn't imported
 *         successfully).
 */
public int verifyDump(final XStreamSavingConverter xstreamSavingConverter) {
    final SessionFactory sessionFactory = hibernate.getSessionFactory();
    Session session = null;
    boolean hasError = false;
    try {
        session = HibernateCompatUtils.openSession(sessionFactory, EmptyInterceptor.INSTANCE);
        session.setDefaultReadOnly(true);
        int counter = 0;
        for (final Map.Entry<Class<?>, List<Object>> entry : xstreamSavingConverter.getAllObjects()
                .entrySet()) {
            final List<Object> objects = entry.getValue();
            final Class<?> entityClass = entry.getKey();
            if (objects == null) {
                continue;
            }
            for (final Object obj : objects) {
                if (HibernateUtils.isEntity(obj.getClass()) == false) {
                    continue;
                }
                final Serializable id = HibernateUtils.getIdentifier(obj);
                if (id == null) {
                    // Can't compare this object without identifier.
                    continue;
                }
                // log.info("Testing object: " + obj);
                final Object databaseObject = session.get(entityClass, id, LockOptions.READ);
                Hibernate.initialize(databaseObject);
                final boolean equals = equals(obj, databaseObject, true);
                if (equals == false) {
                    log.error("Object not sucessfully imported! xml object=[" + obj + "], data base=["
                            + databaseObject + "]");
                    hasError = true;
                }
                ++counter;
            }
        }

        for (final HistoryEntry historyEntry : xstreamSavingConverter.getHistoryEntries()) {
            final Class<?> type = xstreamSavingConverter.getClassFromHistoryName(historyEntry.getEntityName());
            final Object o = type != null ? session.get(type, historyEntry.getEntityId()) : null;
            if (o == null) {
                log.warn("A corrupted history entry found (entity of class '" + historyEntry.getEntityName()
                        + "' with id " + historyEntry.getEntityId() + " not found: " + historyEntry
                        + ". This doesn't affect the functioning of ProjectForge, this may result in orphaned history entries.");
                hasError = true;
            }
            ++counter;
        }
        if (hasError == true) {
            log.fatal(
                    "*********** A inconsistency in the import was found! This may result in a data loss or corrupted data! Please retry the import. "
                            + counter + " entries checked.");
            return -counter;
        }
        log.info("Data-base import successfully verified: " + counter + " entries checked.");
        return counter;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}