Example usage for org.hibernate Transaction registerSynchronization

List of usage examples for org.hibernate Transaction registerSynchronization

Introduction

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

Prototype

void registerSynchronization(Synchronization synchronization) throws HibernateException;

Source Link

Document

Register a user synchronization callback for this transaction.

Usage

From source file:at.molindo.esi4j.module.hibernate.HibernateEventListener.java

License:Apache License

private EventSession findEventSession(EventSource hibernateSession) {
    if (hibernateSession.isTransactionInProgress()) {
        final Transaction transaction = hibernateSession.getTransaction();
        EventSession session = _map.get(transaction);
        if (session == null) {
            session = _batchedEventProcessor.startSession();

            transaction.registerSynchronization(new Esi4JHibernateSynchronization(transaction));

            _map.put(transaction, session);
        }/*from  w  w  w  .j a va 2  s .  c  o  m*/
        return session;
    } else {
        return null;
    }
}

From source file:com.appeligo.alerts.AlertManager.java

License:Apache License

public void checkIfPending(ProgramAlert programAlert) {
    if (programAlert.isDeleted() || programAlert.isDisabled() || (programAlert.getUser() == null)) {
        if (log.isDebugEnabled())
            log.debug("programAlert deleted=" + programAlert.isDeleted() + ", disabled="
                    + programAlert.isDisabled() + ", user=" + programAlert.getUser());
        return;/*from w w w  .j  a va 2s.  c o  m*/
    }
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 14); // 14 days in the future
    List<ScheduledProgram> scheduledPrograms = epg.getNextShowings(programAlert.getUser().getLineupId(),
            programAlert.getProgramId(), programAlert.isNewEpisodes(), true);

    log.debug("Adding alert for program " + programAlert.getProgramId() + ", list of upcoming count="
            + scheduledPrograms.size());

    boolean pendingAlertsAdded = false;
    for (ScheduledProgram scheduledProgram : scheduledPrograms) {
        if (programAlert.isNewEpisodes() && // only alert on new episodes
                (!scheduledProgram.isNewEpisode())) {
            continue;
        }
        if (scheduledProgram == null) {
            if (log.isDebugEnabled())
                log.debug("checkIfPending did not find an upcoming program");
        }
        if (scheduledProgram != null) {
            if (log.isDebugEnabled())
                log.debug("Found next showing " + scheduledProgram.getProgramTitle() + ", start: "
                        + scheduledProgram.getStartTime());

            String callSign = scheduledProgram.getNetwork().getStationCallSign();
            Timestamp startTime = new Timestamp(scheduledProgram.getStartTime().getTime());
            Timestamp alertTime = new Timestamp(startTime.getTime() - (programAlert.getAlertMinutes() * 60000));

            Set<PendingAlert> pendingAlerts = programAlert.getLivePendingAlerts();
            for (PendingAlert pa : pendingAlerts) {
                if ((!pa.isDeleted()) && (pa.getCallSign().equals(callSign))
                        && (pa.getProgramStartTime().equals(startTime))
                        && (pa.getAlertTime().equals(alertTime))) {
                    if (log.isDebugEnabled())
                        log.debug("found matching pending alert");
                    continue;
                }
            }

            PendingAlert pendingAlert = new PendingAlert();
            pendingAlert.setProgramAlert(programAlert);
            pendingAlert.setProgramId(scheduledProgram.getProgramId());
            pendingAlert.setUserId(programAlert.getUser().getUserId());
            pendingAlert.setCallSign(callSign);
            pendingAlert.setProgramStartTime(scheduledProgram.getStartTime());
            pendingAlert.setAlertTime(alertTime);

            if (log.isDebugEnabled())
                log.debug("adding pending alert");
            pendingAlerts.add(pendingAlert);

            pendingAlertsAdded = true;
        }
    }
    if (pendingAlertsAdded) {
        Transaction currentTransaction = TransactionManager.currentTransaction();
        if (currentTransaction == null) {
            synchronized (pendingAlertThread) {
                if (log.isDebugEnabled())
                    log.debug("Notifying pending alert thread immediately");
                pendingAlertThread.notifyAll();
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Will Notify pending alert thread after transaction is done");
            currentTransaction.registerSynchronization(new Synchronization() {

                public void afterCompletion(int arg0) {
                    synchronized (pendingAlertThread) {
                        if (log.isDebugEnabled())
                            log.debug("Notifying pending alert thread now that the transaction is done");
                        pendingAlertThread.notifyAll();
                    }
                }

                public void beforeCompletion() {
                    // Not needed
                }
            });
        }
    }
}

From source file:com.autobizlogic.abl.engine.phase.Constraints.java

License:Open Source License

/**
 * Execute all CommitConstraints, based on the set of all the latest LogicRunners for each touched object.
 */// ww w .j  av  a 2  s . c  o  m
public static void executeAllCommitConstraints(Collection<LogicRunner> logicRunners) {

    List<ConstraintFailure> constraintFailures = new ArrayList<ConstraintFailure>();
    Transaction tx = null;
    LogicRunner failedLogicRunner = null;

    for (LogicRunner runner : logicRunners) {

        LogicGroup logicGroup = runner.getLogicGroup();
        if (logicGroup == null)
            continue;

        if (tx == null)
            tx = runner.getContext().getSession().getTransaction();
        Set<CommitConstraintRule> commitConstraints = logicGroup.getCommitConstraints();
        for (ConstraintRule constraint : commitConstraints) {
            if (!constraint.verbIsRelevant(runner))
                continue;
            if (log.isDebugEnabled())
                log.debug("CommitConstraint(" + constraint.getLogicMethodName() + ") invoking on", runner);

            // Set up the LogicContext, which may have been shared by several LogicRunners
            PersistentBean currentBean = runner.getCurrentDomainObject();
            if (currentBean != null)
                runner.getLogicContext().setCurrentState(currentBean);
            else
                runner.getLogicContext().setCurrentState(runner.getCurrentDomainObject());

            if (runner.getPriorDomainObject() != null) {
                PersistentBean priorBean = runner.getPriorDomainObject();
                if (priorBean != null)
                    runner.getLogicContext().setOldState(priorBean);
                else
                    runner.getLogicContext().setOldState(runner.getPriorDomainObject());
            }
            runner.getLogicContext().setLogicRunner(runner);

            ConstraintFailure failure = constraint.executeConstraint(runner);
            if (failure != null) {
                constraintFailures.add(failure);
                failedLogicRunner = runner;
            }
        }
    }

    // No constraint failures? We're done
    if (constraintFailures.isEmpty())
        return;

    // There were constraint failures, package them up nicely, poison the transaction and throw an exception
    StringBuffer constraintMsg = new StringBuffer();
    for (ConstraintFailure eachConstraintFailure : constraintFailures) {
        String msgLine = eachConstraintFailure.getConstraintMessage();
        constraintMsg.append("\n" + msgLine);
    }
    String msg = LogicMessageFormatter.getMessage(MessageName.rule_ConstraintFailure_prefix,
            constraintMsg.toString());

    ConstraintException ex = new ConstraintException(msg, constraintFailures);

    // Frameworks like Grails do not like to have transactions rolled back
    // by applications, so we no longer roll back, but rather just throw an exception, and make sure that
    // the transaction cannot be committed.
    if (tx != null) {
        LogicAfterCommitEvent evt = new LogicAfterCommitEvent(failedLogicRunner.getContext(),
                CommitFailure.CONSTRAINTFAILURE);
        GlobalLogicEventHandler.getGlobalLogicListenerHandler().fireEvent(evt);

        // We want to guarantee that this transaction will not get committed, even if the exception we're about
        // to throw gets buried by some code somewhere. So we register a Synchronization with the transaction,
        // and if it gets to that, it will throw an exception before commit. Note that it will usually not get called,
        // only if our exception somehow gets buried.
        TransactionFailureSynchronization sync = new TransactionFailureSynchronization(ex);
        tx.registerSynchronization(sync);
    }

    throw ex;
}

From source file:com.eucalyptus.entities.Entities.java

License:Open Source License

public static <T> void registerSynchronization(final Class<T> syncClass,
        final Synchronization synchronization) {
    final Session session = getTransaction(syncClass).getTxState().getSession();
    final Transaction transaction = session.getTransaction();
    transaction.registerSynchronization(synchronization);
}

From source file:com.googlecode.hibernate.audit.extension.syncronization.DefaultTransactionSyncronization.java

License:Open Source License

public void registerSynchronization(EventSource eventSource, Synchronization synchronization) {
    Transaction transaction = eventSource.getTransaction();
    checkForActiveTransaction(eventSource);

    transaction.registerSynchronization(synchronization);
}

From source file:org.compass.gps.device.hibernate.embedded.CompassEventListener.java

License:Apache License

private TransactionSyncHolder getOrCreateHolder(EventSource session) {
    if (session.isTransactionInProgress()) {
        Transaction transaction = session.getTransaction();
        TransactionSyncHolder holder = compassHolder.syncHolderPerTx.get(transaction);
        if (holder == null) {
            holder = new TransactionSyncHolder();
            holder.session = compassHolder.compass.openSession();
            holder.tr = holder.session.beginTransaction();
            holder.transacted = true;//from  w w w.  ja va 2s  . co  m
            transaction.registerSynchronization(new CompassEmbeddedSyncronization(holder, transaction));
            compassHolder.syncHolderPerTx.put(transaction, holder);
        }
        return holder;
    } else {
        TransactionSyncHolder holder = new TransactionSyncHolder();
        holder.session = compassHolder.compass.openSession();
        holder.tr = holder.session.beginTransaction();
        holder.transacted = false;
        return holder;
    }
}

From source file:org.libreplan.business.hibernate.notification.HibernateDatabaseModificationsListener.java

License:Open Source License

void modificationOn(Transaction transaction, Class<?> entityClass) {
    if (transaction == null) {
        dispatch(snapshotsInterestedOn(entityClass));

        return;//from w  ww .  j  a v a  2  s . c  om
    }
    Dispatcher newDispatcher = new Dispatcher(transaction, entityClass);
    Dispatcher previous;
    previous = pending.putIfAbsent(transaction, newDispatcher);

    boolean dispatcherAlreadyExisted = previous != null;
    if (dispatcherAlreadyExisted) {
        previous.add(entityClass);
    } else {
        transaction.registerSynchronization(newDispatcher);
    }
}

From source file:org.openremote.container.persistence.PersistenceEventInterceptor.java

License:Open Source License

@Override
public void afterTransactionBegin(Transaction tx) {
    tx.registerSynchronization(new Synchronization() {
        @Override/*from ww w . ja v a2  s. c  om*/
        public void beforeCompletion() {
        }

        @Override
        public void afterCompletion(int status) {
            try {
                if (status != Status.STATUS_COMMITTED)
                    return;

                for (PersistenceEvent persistenceEvent : persistenceEvents) {
                    try {
                        messageBrokerService.getProducerTemplate().sendBodyAndHeader(
                                PersistenceEvent.PERSISTENCE_TOPIC, ExchangePattern.InOnly, persistenceEvent,
                                PersistenceEvent.HEADER_ENTITY_TYPE, persistenceEvent.getEntity().getClass());
                    } catch (CamelExecutionException ex) {
                        // TODO Better error handling?
                        LOG.log(Level.SEVERE, "Error dispatching: " + persistenceEvent + " - " + ex, ex);
                    }
                }
            } finally {
                persistenceEvents.clear();
            }
        }
    });
}