Example usage for javax.transaction Synchronization Synchronization

List of usage examples for javax.transaction Synchronization Synchronization

Introduction

In this page you can find the example usage for javax.transaction Synchronization Synchronization.

Prototype

Synchronization

Source Link

Usage

From source file:io.strandberg.xadisk.XADiskSessionFactory.java

public XASession getXASession() throws SystemException, RollbackException {

    final Transaction transaction = transactionManager.getTransaction();

    synchronized (transaction) {

        // get the xaSession associated with the current transaction - if any
        XASession xaSession = xaSessionMap.get(transaction);

        if (xaSession == null) {

            // create a new xaSession
            xaSession = xaFileSystem.createSessionForXATransaction();
            logger.debug("New XASession has been created");

            // enlist the xaSessions XAResource
            transaction.enlistResource(xaSession.getXAResource());
            logger.debug("XASession's XAResource has been enlisted in transaction");

            // Remove the xaSession from the xaSessionMap after the transaction is completed
            transaction.registerSynchronization(new Synchronization() {
                public void beforeCompletion() {
                }/* www .j  a  v a 2 s.  c  o m*/

                public void afterCompletion(int status) {
                    xaSessionMap.remove(transaction);
                    logger.debug("XASession has been removed from the XASession Map");
                }
            });

            // Associate the transaction with the xaSession
            xaSessionMap.put(transaction, xaSession);
            logger.debug("New XASession added to XASession Map");

        } else {
            logger.debug("XASession found in XASession Map");
        }

        return xaSession;
    }
}

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

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 ww .  j ava  2  s . 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:org.apache.ode.bpel.engine.Contexts.java

public void registerCommitSynchronizer(final Runnable runnable) {
    try {// w ww .j  a va  2s  .  c o  m
        txManager.getTransaction().registerSynchronization(new Synchronization() {

            public void afterCompletion(int status) {
                if (status == Status.STATUS_COMMITTED)
                    runnable.run();
            }

            public void beforeCompletion() {

            }

        });
    } catch (Exception ex) {
        throw new BpelEngineException("Error registering synchronizer.", ex);
    }
}

From source file:org.apache.ode.dao.jpa.BPELDAOConnectionFactoryImpl.java

@SuppressWarnings("unchecked")
public BpelDAOConnection getConnection() {
    try {/*from   ww  w. j  a  va  2  s .  c  om*/
        _tm.getTransaction().registerSynchronization(new Synchronization() {
            // OpenJPA allows cross-transaction entity managers, which we don't want
            public void afterCompletion(int i) {
                if (_connections.get() != null)
                    _connections.get().getEntityManager().close();
                _connections.set(null);
            }

            public void beforeCompletion() {
            }
        });
    } catch (RollbackException e) {
        throw new RuntimeException("Coulnd't register synchronizer!");
    } catch (SystemException e) {
        throw new RuntimeException("Coulnd't register synchronizer!");
    }
    if (_connections.get() != null) {
        return _connections.get();
    } else {
        HashMap propMap2 = new HashMap();
        propMap2.put("openjpa.TransactionMode", "managed");
        EntityManager em = _emf.createEntityManager(propMap2);
        BPELDAOConnectionImpl conn = createBPELDAOConnection(em);
        _connections.set(conn);
        return conn;
    }
}

From source file:org.apache.ode.dao.jpa.JpaConnection.java

/** Clear out the entity manager after a commit so no stale entites are
 *  preserved across transactions and all JPA operations pull data directly from
 *  the DB.//from w ww .  j a va  2 s .co m
 *
 */
public void clearOnComplete() {
    try {
        _mgr.getTransaction().registerSynchronization(new Synchronization() {

            public void afterCompletion(int i) {
                _em.clear();
                if (__log.isDebugEnabled()) {
                    __log.debug("-------> clear the entity manager");
                }
            }

            public void beforeCompletion() {
            }
        });
    } catch (Exception e) {
        __log.error("Error adding commit synchronizer", e);
    }
}

From source file:org.apache.ode.il.MockScheduler.java

public void registerSynchronizer(final Synchronizer synch) throws ContextException {
    if (_txm != null) {
        try {//from ww w  .j  a  v  a 2 s  . c  o m
            _txm.getTransaction().registerSynchronization(new Synchronization() {
                public void beforeCompletion() {
                    synch.beforeCompletion();
                }

                public void afterCompletion(int status) {
                    synch.afterCompletion(status == Status.STATUS_COMMITTED);
                }
            });
        } catch (Exception e) {
            __log.error("Exception in mock scheduler sync registration.", e);
            throw new RuntimeException(e);
        }
    } else {
        _synchros.get().add(synch);
    }
}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public void registerSynchronizer(final Synchronizer synch) throws ContextException {
    TransactionManager txm = _txm;//w w w.j  av  a  2  s. c  om
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }

    try {
        txm.getTransaction().registerSynchronization(new Synchronization() {

            public void beforeCompletion() {
                synch.beforeCompletion();
            }

            public void afterCompletion(int status) {
                synch.afterCompletion(status == Status.STATUS_COMMITTED);
            }

        });
    } catch (Exception e) {
        throw new ContextException("Unable to register synchronizer.", e);
    }
}

From source file:org.apache.openejb.resource.AutoConnectionTracker.java

/**
 * Proxies new connection handles so we can detect when they have been garbage collected.
 *
 * @param interceptor    the interceptor used to release the managed connection when the handled is garbage collected.
 * @param connectionInfo the connection that was obtained
 * @param reassociate    should always be false
 *//*  ww w.  java  2s.c o  m*/
public void handleObtained(final ConnectionTrackingInterceptor interceptor, final ConnectionInfo connectionInfo,
        final boolean reassociate) throws ResourceException {
    if (txMgr != null && registry != null) {
        Transaction currentTx = null;
        try {
            currentTx = txMgr.getTransaction();
        } catch (SystemException e) {
            //ignore
        }

        if (currentTx != null) {
            Map<ManagedConnectionInfo, Map<ConnectionInfo, Object>> txConnections = (Map<ManagedConnectionInfo, Map<ConnectionInfo, Object>>) registry
                    .getResource(KEY);
            if (txConnections == null) {
                txConnections = new HashMap<>();
                registry.putResource(KEY, txConnections);
            }

            Map<ConnectionInfo, Object> connectionObjects = txConnections
                    .computeIfAbsent(connectionInfo.getManagedConnectionInfo(), k -> new HashMap<>());

            connectionObjects.put(connectionInfo, connectionInfo.getConnectionProxy());

            registry.registerInterposedSynchronization(new Synchronization() {
                @Override
                public void beforeCompletion() {
                    final Map<ManagedConnectionInfo, Map<ConnectionInfo, Object>> txConnections = (Map<ManagedConnectionInfo, Map<ConnectionInfo, Object>>) registry
                            .getResource(KEY);
                    if (txConnections != null && txConnections.size() > 0) {

                        for (final Map.Entry<ManagedConnectionInfo, Map<ConnectionInfo, Object>> managedConnectionInfoMapEntry : txConnections
                                .entrySet()) {
                            final StringBuilder sb = new StringBuilder();
                            final Collection<ConnectionInfo> connectionInfos = managedConnectionInfoMapEntry
                                    .getValue().keySet();
                            for (final ConnectionInfo connectionInfo : connectionInfos) {
                                sb.append("\n  ").append("Connection handle opened at ")
                                        .append(stackTraceToString(connectionInfo.getTrace().getStackTrace()));
                            }

                            logger.warning("Transaction complete, but connection still has handles associated: "
                                    + managedConnectionInfoMapEntry.getKey()
                                    + "\nAbandoned connection information: " + sb);
                        }
                    }
                }

                @Override
                public void afterCompletion(final int status) {

                }
            });
        }
    }

    if (!reassociate) {
        proxyConnection(interceptor, connectionInfo);
    }
}

From source file:org.jbpm.EventCallback.java

private static void registerNotification(final String event) {
    Synchronization notification = new Synchronization() {

        public void beforeCompletion() {
        }//from  w  ww .jav a2s.co m

        public void afterCompletion(int status) {
            if (status == Status.STATUS_COMMITTED) {
                log.debug("sending '" + event + "' notification");
                Semaphore eventSemaphore = getEventSemaphore(event);
                eventSemaphore.release();
            }
        }

    };
    JbpmContext.getCurrentJbpmContext().getSession().getTransaction().registerSynchronization(notification);
}

From source file:org.jbpm.graph.def.EventCallback.java

private static void registerNotification(final String event) {
    Synchronization notification = new Synchronization() {

        public void beforeCompletion() {
        }//from w  w w .j  a  v a 2s . co  m

        public void afterCompletion(int status) {
            if (status == Status.STATUS_COMMITTED) {
                if (log.isDebugEnabled())
                    log.debug("sending '" + event + "' notification");
                Semaphore eventSemaphore = getEventSemaphore(event);
                eventSemaphore.release();
            }
        }
    };
    JbpmContext.getCurrentJbpmContext().getSession().getTransaction().registerSynchronization(notification);
}