Example usage for org.springframework.transaction.support TransactionSynchronizationManager registerSynchronization

List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager registerSynchronization

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionSynchronizationManager registerSynchronization.

Prototype

public static void registerSynchronization(TransactionSynchronization synchronization)
        throws IllegalStateException 

Source Link

Document

Register a new transaction synchronization for the current thread.

Usage

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImpl.java

@Override
@TransactionalRollbackAllExceptions/*from   w ww. ja va 2 s. c o  m*/
@Timed
public int ageEvents(long agingInterval, TimeUnit unit, EventSeverity maxSeverity, int limit,
        boolean inclusiveSeverity) throws ZepException {
    TypeConverter<Long> timestampConverter = databaseCompatibility.getTimestampConverter();
    long agingIntervalMs = unit.toMillis(agingInterval);
    if (agingIntervalMs < 0 || agingIntervalMs == Long.MAX_VALUE) {
        throw new ZepException("Invalid aging interval: " + agingIntervalMs);
    }
    if (limit <= 0) {
        throw new ZepException("Limit can't be negative: " + limit);
    }
    List<Integer> severityIds = getSeverityIds(maxSeverity, inclusiveSeverity);
    if (severityIds.isEmpty()) {
        logger.debug("Not aging events - min severity specified");
        return 0;
    }
    long now = System.currentTimeMillis();
    long ageTs = now - agingIntervalMs;

    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put(COLUMN_STATUS_ID, EventStatus.STATUS_AGED.getNumber());
    fields.put(COLUMN_CLOSED_STATUS, ZepConstants.CLOSED_STATUSES.contains(EventStatus.STATUS_AGED));
    fields.put(COLUMN_STATUS_CHANGE, timestampConverter.toDatabaseType(now));
    fields.put(COLUMN_UPDATE_TIME, timestampConverter.toDatabaseType(now));
    fields.put(COLUMN_LAST_SEEN, timestampConverter.toDatabaseType(ageTs));
    fields.put("_severity_ids", severityIds);
    fields.put("_limit", limit);

    final String updateSql;
    if (databaseCompatibility.getDatabaseType() == DatabaseType.MYSQL) {
        String indexSql = "INSERT INTO event_summary_index_queue (uuid, update_time) " + "SELECT uuid, "
                + String.valueOf(now) + " " + "FROM event_summary " + " WHERE last_seen < :last_seen AND"
                + " severity_id IN (:_severity_ids) AND" + " closed_status = FALSE LIMIT :_limit";
        this.template.update(indexSql, fields);

        // Use UPDATE ... LIMIT
        updateSql = "UPDATE event_summary SET"
                + " status_id=:status_id,status_change=:status_change,update_time=:update_time"
                + ",closed_status=:closed_status"
                + " WHERE last_seen < :last_seen AND severity_id IN (:_severity_ids)"
                + " AND closed_status = FALSE LIMIT :_limit";
    } else if (databaseCompatibility.getDatabaseType() == DatabaseType.POSTGRESQL) {
        String indexSql = "INSERT INTO event_summary_index_queue (uuid, update_time) " + "SELECT uuid, "
                + String.valueOf(now) + " " + "FROM event_summary "
                + " WHERE uuid IN (SELECT uuid FROM event_summary WHERE"
                + " last_seen < :last_seen AND severity_id IN (:_severity_ids)"
                + " AND closed_status = FALSE LIMIT :_limit)";
        this.template.update(indexSql, fields);

        // Use UPDATE ... WHERE pk IN (SELECT ... LIMIT)
        updateSql = "UPDATE event_summary SET"
                + " status_id=:status_id,status_change=:status_change,update_time=:update_time"
                + ",closed_status=:closed_status" + " WHERE uuid IN (SELECT uuid FROM event_summary WHERE"
                + " last_seen < :last_seen AND severity_id IN (:_severity_ids)"
                + " AND closed_status = FALSE LIMIT :_limit)";
    } else {
        throw new IllegalStateException(
                "Unsupported database type: " + databaseCompatibility.getDatabaseType());
    }
    final int numRows = this.template.update(updateSql, fields);
    if (numRows > 0) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                counters.addToAgedEventCount(numRows);
            }
        });
    }
    return numRows;
}

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImpl.java

@Override
@TransactionalRollbackAllExceptions//w  w w .j  a  v a  2s.  c  o m
@Timed
public int archive(List<String> uuids) throws ZepException {
    if (uuids.isEmpty()) {
        return 0;
    }
    if (this.archiveColumnNames == null) {
        try {
            this.archiveColumnNames = DaoUtils.getColumnNames(this.dataSource, TABLE_EVENT_ARCHIVE);
        } catch (MetaDataAccessException e) {
            throw new ZepException(e.getLocalizedMessage(), e);
        }
    }

    TypeConverter<Long> timestampConverter = databaseCompatibility.getTimestampConverter();
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put(COLUMN_UPDATE_TIME, timestampConverter.toDatabaseType(System.currentTimeMillis()));
    fields.put("_uuids", TypeConverterUtils.batchToDatabaseType(uuidConverter, uuids));
    StringBuilder selectColumns = new StringBuilder();

    for (Iterator<String> it = this.archiveColumnNames.iterator(); it.hasNext();) {
        String columnName = it.next();
        if (fields.containsKey(columnName)) {
            selectColumns.append(':').append(columnName);
        } else {
            selectColumns.append(columnName);
        }
        if (it.hasNext()) {
            selectColumns.append(',');
        }
    }

    final long updateTime = System.currentTimeMillis();
    /* signal event_summary table rows to get indexed */
    this.template.update("INSERT INTO event_summary_index_queue (uuid, update_time) " + "SELECT uuid, "
            + String.valueOf(updateTime) + " " + "FROM event_summary"
            + " WHERE uuid IN (:_uuids) AND closed_status = TRUE", fields);

    String insertSql = String.format("INSERT INTO event_archive (%s) SELECT %s FROM event_summary"
            + " WHERE uuid IN (:_uuids) AND closed_status = TRUE ON DUPLICATE KEY UPDATE summary=event_summary.summary",
            StringUtils.collectionToCommaDelimitedString(this.archiveColumnNames), selectColumns);

    this.template.update(insertSql, fields);
    final int updated = this.template
            .update("DELETE FROM event_summary WHERE uuid IN (:_uuids) AND closed_status = TRUE", fields);
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            counters.addToArchivedEventCount(updated);
        }
    });
    return updated;
}

From source file:org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter.java

public void executeOnTransactionCompletion(Runnable runnable) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Submitting new runnable {" + runnable + "} to run after completion");
    }// w  w  w  .j  ava2 s . c om

    /*
    From TransactionSynchronizationManager documentation:
    TransactionSynchronizationManager is a central helper that manages resources and transaction synchronizations per thread.
    Resource management code should only register synchronizations when this manager is active,
    which can be checked via isSynchronizationActive(); it should perform immediate resource cleanup else.
    If transaction synchronization isn't active, there is either no current transaction,
    or the transaction manager doesn't support transaction synchronization.
            
    Note: Synchronization is an Interface for transaction synchronization callbacks which is implemented by
    TransactionSynchronizationAdapter
    */

    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        LOG.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {" + runnable + "}");
        runnable.run();
        return;
    }
    List<Runnable> threadRunnables = RUNNABLES.get();
    if (threadRunnables == null) {
        threadRunnables = new ArrayList<Runnable>();
        RUNNABLES.set(threadRunnables);
        // Register a new transaction synchronization for the current thread.
        // TransactionSynchronizationManage will call afterCompletion() when current transaction completes.
        TransactionSynchronizationManager.registerSynchronization(this);
    }
    threadRunnables.add(runnable);
}

From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsSessionContext.java

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *///from www. j  a v  a2s . com
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    }

    if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && !sessionHolder.isSynchronizedWithTransaction()) {
            TransactionSynchronizationManager
                    .registerSynchronization(createSpringSessionSynchronization(sessionHolder));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();
            if (FlushMode.isManualFlushMode(flushMode)
                    && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    }

    if (jtaSessionContext != null) {
        Session session = jtaSessionContext.currentSession();
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager
                    .registerSynchronization(createSpringFlushSynchronization(session));
        }
        return session;
    }

    if (allowCreate) {
        // be consistent with older HibernateTemplate behavior
        return createSession(value);
    }

    throw new HibernateException("No Session found for current thread");
}

From source file:org.compass.spring.transaction.SpringSyncTransaction.java

public void begin(PlatformTransactionManager transactionManager, InternalCompassSession session,
        boolean commitBeforeCompletion) {

    this.session = session;
    this.transactionManager = transactionManager;

    // the factory called begin, so we are in charge, if we were not, than
    // it would not call begin (we are in charge of the COMPASS transaction,
    // the spring one is handled later)
    controllingNewTransaction = true;//from  w w  w.  jav  a 2  s.c  o  m

    if (transactionManager != null) {
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        int timeout = session.getSettings().getSettingAsInt(CompassEnvironment.Transaction.TRANSACTION_TIMEOUT,
                -1);
        if (timeout != -1) {
            transactionDefinition.setTimeout(timeout);
        }
        transactionDefinition.setReadOnly(session.isReadOnly());
        status = transactionManager.getTransaction(transactionDefinition);
    }

    session.getSearchEngine().begin();

    SpringTransactionSynchronization sync;
    if (transactionManager != null) {
        if (log.isDebugEnabled()) {
            if (status.isNewTransaction()) {
                log.debug("Beginning new Spring transaction, and a new compass transaction on thread ["
                        + Thread.currentThread().getName() + "]");
            } else {
                log.debug("Joining Spring transaction, and starting a new compass transaction on thread ["
                        + Thread.currentThread().getName() + "]");
            }
        }
        sync = new SpringTransactionSynchronization(session, status.isNewTransaction(), commitBeforeCompletion,
                transactionFactory);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Joining Spring transaction, and starting a new compass transaction on thread ["
                    + Thread.currentThread().getName() + "]");
        }
        sync = new SpringTransactionSynchronization(session, false, commitBeforeCompletion, transactionFactory);
    }
    TransactionSynchronizationManager.registerSynchronization(sync);

    setBegun(true);
}

From source file:org.hyperic.hq.common.server.session.AuditManagerImpl.java

/**
 * Push a global audit container onto the stack. Any subsequent audits
 * created (via saveAudit) will be added to this container.
 * /*from   w  w  w  .j  a  v a2 s  .  co  m*/
 * 
 */
public void pushContainer(Audit newContainer) {
    Audit currentContainer = getCurrentAudit();

    newContainer.setStartTime(System.currentTimeMillis());
    if (currentContainer == null) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            public void suspend() {
            }

            public void resume() {
            }

            public void flush() {
            }

            public void beforeCompletion() {
            }

            public void beforeCommit(boolean readOnly) {
                popAll();
            }

            public void afterCompletion(int status) {
            }

            public void afterCommit() {
            }
        });
    } else {
        currentContainer.addChild(newContainer);
    }
    CONTAINERS.set(newContainer);
}

From source file:org.hyperic.hq.escalation.server.session.EscalationRuntimeImpl.java

/**
 * Unschedule the execution of an escalation state. The unschedule will only
 * occur if the transaction successfully commits.
 *///from   ww  w .  java  2s.  c  o m
public void unscheduleEscalation(EscalationState state) {
    final Integer stateId = state.getId();
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
        public void suspend() {
        }

        public void resume() {
        }

        public void flush() {
        }

        public void beforeCompletion() {
        }

        public void beforeCommit(boolean readOnly) {
        }

        public void afterCompletion(int status) {
        }

        public void afterCommit() {
            unscheduleEscalation_(stateId);
        }
    });
}

From source file:org.hyperic.hq.escalation.server.session.EscalationRuntimeImpl.java

/**
 * Unschedule the execution of all escalation states associated with this
 * entity that performs escalations. The unschedule will only occur if the
 * transaction successfully commits.//  www.j  a  v a 2  s  .c o  m
 */
public void unscheduleAllEscalationsFor(PerformsEscalations def) {
    BatchUnscheduleEscalationsTransactionListener batchTxnListener = (BatchUnscheduleEscalationsTransactionListener) _batchUnscheduleTxnListeners
            .get();

    if (batchTxnListener == null) {
        batchTxnListener = new BatchUnscheduleEscalationsTransactionListener();
        _batchUnscheduleTxnListeners.set(batchTxnListener);
        TransactionSynchronizationManager.registerSynchronization(batchTxnListener);
    }

    batchTxnListener.unscheduleAllEscalationsFor(def);
}

From source file:org.hyperic.hq.escalation.server.session.EscalationRuntimeImpl.java

/**
 * Remove the uncommitted escalation state for this entity performing
 * escalations from the uncommitted escalation state cache.
 * /*from   w w  w.  jav a2s. c  om*/
 * @param def
 *            The entity that performs escalations.
 * @param postTxnCommit
 *            <code>true</code> to remove post txn commit;
 *            <code>false</code> to remove immediately.
 */
public void removeFromUncommittedEscalationStateCache(final PerformsEscalations def, boolean postTxnCommit) {
    if (postTxnCommit) {
        boolean addedTxnListener = false;
        try {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

                public void suspend() {
                }

                public void resume() {
                }

                public void flush() {
                }

                public void beforeCompletion() {
                }

                public void beforeCommit(boolean readOnly) {
                }

                public void afterCompletion(int status) {
                }

                public void afterCommit() {
                    removeFromUncommittedEscalationStateCache(def, false);
                }
            });

            addedTxnListener = true;
        } finally {
            if (!addedTxnListener) {
                removeFromUncommittedEscalationStateCache(def, false);
            }
        }
    } else {
        _uncomittedEscalatingEntities.remove(new EscalatingEntityIdentifier(def));
    }

}

From source file:org.hyperic.hq.escalation.server.session.EscalationRuntimeImpl.java

/**
 * This method introduces an escalation state to the runtime. The escalation
 * will be invoked according to the next action time of the state.
 * /*from   w ww  .j av  a 2s.  c  o  m*/
 * If the state had been previously scheduled, it will be rescheduled with
 * the new time.
 */
public void scheduleEscalation(final EscalationState state) {
    final long schedTime = state.getNextActionTime();
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
        public void suspend() {
        }

        public void resume() {
        }

        public void flush() {
        }

        public void beforeCompletion() {
        }

        public void beforeCommit(boolean readOnly) {
        }

        public void afterCompletion(int status) {
        }

        public void afterCommit() {
            scheduleEscalation_(state, schedTime);
        }
    });
}