Example usage for org.springframework.transaction.support TransactionTemplate setReadOnly

List of usage examples for org.springframework.transaction.support TransactionTemplate setReadOnly

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionTemplate setReadOnly.

Prototype

public final void setReadOnly(boolean readOnly) 

Source Link

Document

Set whether to optimize as read-only transaction.

Usage

From source file:org.brekka.pegasus.core.services.impl.DownloadServiceImpl.java

@Override
public InputStream download(final AllocationFile file, final ProgressCallback progressCallback,
        final boolean captureDownloadEvent, final boolean incrementCounter) {
    // Has its own transaction
    final FileDownloadEvent event = captureDownloadEvent ? eventService.beginFileDownloadEvent(file) : null;

    // Perform in its own readonly transaction. This ensures that the thread is only using one connection at a time.
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    tt.setReadOnly(true);
    return tt.execute(new TransactionCallback<EventInputStream>() {
        @Override/*from  w w  w . j  a v a  2 s .  co  m*/
        public EventInputStream doInTransaction(final TransactionStatus status) {
            FileType fileType = file.getXml();
            CryptedFile cryptedFile = pavewayService.retrieveCryptedFileById(file.getCryptedFile().getId());
            CryptoProfile cryptoProfile = cryptoProfileService.retrieveProfile(cryptedFile.getProfile());
            SecretKey secretKey = symmetricCryptoService.toSecretKey(fileType.getKey(), cryptoProfile);
            cryptedFile.setSecretKey(secretKey);
            InputStream is = pavewayService.download(cryptedFile);
            return new EventInputStream(is, file, event, cryptedFile.getOriginalLength(), progressCallback,
                    incrementCounter);
        }
    });
}

From source file:com.opensymphony.able.filter.TransactionServletFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    // TODO we could get clever and figure out what URIs are read only transactions etc
    TransactionTemplate transactionTemplate = (TransactionTemplate) context.getBean("transactionTemplate");
    transactionTemplate.setReadOnly(false);

    if (log.isDebugEnabled()) {
        log.debug("Starting a transaction");
    }/*from   w  w  w .j a v  a  2  s . co m*/

    PlatformTransactionManager transactionManager = transactionTemplate.getTransactionManager();
    TransactionStatus status = transactionManager.getTransaction(transactionTemplate);
    TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate);
    request.setAttribute(TRANSACTION_OUTCOME, outcome);

    Exception exception = null;
    try {
        filterChain.doFilter(request, response);
        status = transactionManager.getTransaction(transactionTemplate);
    } catch (Exception e) {
        exception = e;
        log.warn("Caught: " + e, e);
    }

    if (outcome.isRollbackOnly() || exception != null) {
        status.setRollbackOnly();
    }

    try {
        if (status.isRollbackOnly()) {
            log.debug("Rolling back transaction");
            transactionManager.rollback(status);
        } else {
            log.debug("Committing transaction");
            transactionManager.commit(status);
        }
    } catch (TransactionException e) {
        if (exception == null) {
            exception = e;
        } else {
            log.debug("Failed to rollback transaction: " + e, e);
        }
    }

    if (exception instanceof IOException) {
        throw (IOException) exception;
    } else if (exception instanceof ServletException) {
        throw (ServletException) exception;
    } else if (exception != null) {
        throw new ServletException(exception);
    }
}

From source file:org.zlogic.vogon.web.security.UserService.java

/**
 * Returns true if the username is already in use
 *
 * @param username the username to check
 * @return true if the username is already in use
 *//*ww  w  . j av a2  s .  com*/
private boolean isUsernameExists(final String username) {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setReadOnly(true);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    return transactionTemplate.execute(new TransactionCallback<Boolean>() {

        @Override
        public Boolean doInTransaction(TransactionStatus ts) {
            return userRepository.findByUsernameIgnoreCase(username) != null;
        }
    });
}

From source file:fr.mycellar.interfaces.facades.stack.StackServiceFacadeImpl.java

@Override
public synchronized void onThrowable(final Throwable throwable) {
    // The transaction must be inside the lock. So we must use a transaction
    // template and not the Transactional annotation.
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    transactionTemplate.setReadOnly(false);
    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override//from w ww  .ja  v a  2s.  com
        public Object doInTransaction(TransactionStatus status) {
            stackService.onThrowable(throwable);
            return null;
        }
    });
}

From source file:com.opensymphony.able.filter.SimpleTransactionServletFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    // TODO we could get clever and figure out what URIs are read only transactions etc
    final TransactionTemplate transactionTemplate = (TransactionTemplate) context
            .getBean("transactionTemplate");
    transactionTemplate.setReadOnly(false);

    if (log.isDebugEnabled()) {
        log.debug("Starting a transaction");
    }/*from   ww  w  . jav a  2s.com*/

    try {
        Exception e = (Exception) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                try {
                    TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate);
                    TransactionOutcome.setTransactionOutcome(outcome);
                    filterChain.doFilter(request, response);

                    if (outcome.isRollbackOnly()) {
                        log.debug("Outcome is rollback");
                        status.setRollbackOnly();
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("Completing a transaction with rollback: " + status.isRollbackOnly());
                    }
                    return null;
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    return e;
                }
            }
        });

        if (log.isDebugEnabled()) {
            log.debug("End transaction with exception: " + e);
        }

        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e != null) {
            throw new ServletException(e);
        }
    } catch (TransactionException e) {
        Throwable cause = e.getCause();
        if (cause.getCause() != null) {
            cause = cause.getCause();
        }
        ;
        if (cause instanceof JDBCException) {
            JDBCException jdbcException = (JDBCException) cause;
            SQLException sqlException = jdbcException.getSQLException();
            throw new ServletException("Failed to execute: " + jdbcException.getSQL() + ": error: "
                    + sqlException.getSQLState() + ". Reason: " + sqlException, sqlException);
        }
        throw new ServletException(cause);
    } finally {
        TransactionOutcome.setTransactionOutcome(null);
    }
}

From source file:org.axonframework.migration.eventstore.JpaEventStoreMigrator.java

public boolean run() throws Exception {
    final AtomicInteger updateCount = new AtomicInteger();
    final AtomicInteger skipCount = new AtomicInteger();
    final AtomicLong lastId = new AtomicLong(
            Long.parseLong(configuration.getProperty("lastProcessedId", "-1")));
    try {// w ww  . jav a 2 s  .com
        TransactionTemplate template = new TransactionTemplate(txManager);
        template.setReadOnly(true);
        System.out.println("Starting conversion. Fetching batches of " + QUERY_BATCH_SIZE + " items.");
        while (template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                final Session hibernate = entityManager.unwrap(Session.class);
                Iterator<Object[]> results = hibernate.createQuery(
                        "SELECT e.aggregateIdentifier, e.sequenceNumber, e.type, e.id FROM DomainEventEntry e "
                                + "WHERE e.id > :lastIdentifier ORDER BY e.id ASC")
                        .setFetchSize(1000).setMaxResults(QUERY_BATCH_SIZE).setReadOnly(true)
                        .setParameter("lastIdentifier", lastId.get()).iterate();
                if (!results.hasNext()) {
                    System.out.println("Empty batch. Assuming we're done.");
                    return false;
                } else if (Thread.interrupted()) {
                    System.out.println("Received an interrupt. Stopping...");
                    return false;
                }
                while (results.hasNext()) {
                    List<ConversionItem> conversionBatch = new ArrayList<ConversionItem>();
                    while (conversionBatch.size() < CONVERSION_BATCH_SIZE && results.hasNext()) {
                        Object[] item = results.next();
                        String aggregateIdentifier = (String) item[0];
                        long sequenceNumber = (Long) item[1];
                        String type = (String) item[2];
                        Long entryId = (Long) item[3];
                        lastId.set(entryId);
                        conversionBatch
                                .add(new ConversionItem(sequenceNumber, aggregateIdentifier, type, entryId));
                    }
                    if (!conversionBatch.isEmpty()) {
                        executor.submit(new TransformationTask(conversionBatch, skipCount));
                    }
                }
                return true;
            }
        })) {
            System.out.println("Reading next batch, starting at ID " + lastId.get() + ".");
            System.out.println(
                    "Estimated backlog size is currently: " + (workQueue.size() * CONVERSION_BATCH_SIZE));
        }
    } finally {
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.MINUTES);
        if (lastId.get() >= 0) {
            System.out.println(
                    "Processed events from old event store up to (and including) id = " + lastId.get());
        }
    }
    System.out.println("In total " + updateCount.get() + " items have been converted.");
    return skipCount.get() == 0;
}

From source file:org.ambraproject.struts2.TransactionInterceptor.java

public String intercept(final ActionInvocation actionInvocation) throws Exception {

    final Action action = (Action) actionInvocation.getAction();
    final ActionProxy actionProxy = actionInvocation.getProxy();
    final String methodName = actionProxy.getMethod();

    if (getAnnotation(action.getClass(), methodName, ManualTransactionManagement.class) != null) {
        //Method is annotated tellling us not to manage a transaction for it
        log.debug(/*from w  w  w .j  ava2  s .  c o m*/
                "Not managing transaction for " + action.getClass().getSimpleName() + "." + methodName + "()");
        return actionInvocation.invoke();
    }

    if (log.isDebugEnabled()) {
        log.debug("Intercepted " + action.getClass().getSimpleName() + "." + methodName + "()");
    }

    final Transactional transactionalAnnotation = getAnnotation(action.getClass(), methodName,
            Transactional.class);
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    if (transactionalAnnotation != null) {
        txTemplate.setReadOnly(transactionalAnnotation.readOnly());
        txTemplate.setTimeout(transactionalAnnotation.timeout());
        txTemplate.setIsolationLevel(transactionalAnnotation.isolation().value());
        txTemplate.setPropagationBehavior(transactionalAnnotation.propagation().value());
    }

    CallbackResult callbackResult = (CallbackResult) txTemplate.execute(new TransactionCallback() {
        public CallbackResult doInTransaction(TransactionStatus transactionStatus) {
            CallbackResult result = new CallbackResult();
            try {
                String actionResult = actionInvocation.invoke();
                result.setResult(actionResult);
                //Rollback for Action responses indicating failure
                for (String response : new String[] { Action.ERROR, Action.INPUT, Action.LOGIN }) {
                    if (response.equalsIgnoreCase(actionResult) && !transactionStatus.isRollbackOnly()) {
                        log.debug("Rolling back action " + action.getClass().getSimpleName()
                                + " due to result: " + actionResult);
                        transactionStatus.setRollbackOnly();
                        break;
                    }
                }
            } catch (Exception e) {
                /*
                * Callback does not throw exception. We need to pass Exception object in the return
                * parameter so we can throw it in the calling method.
                */
                boolean noRollback = false;

                if (transactionalAnnotation != null && transactionalAnnotation.noRollbackFor() != null) {
                    for (Class<? extends Throwable> exception : transactionalAnnotation.noRollbackFor()) {
                        if (exception.isInstance(e)) {
                            noRollback = true;
                            break;
                        }
                    }
                }

                if (!noRollback && transactionalAnnotation != null
                        && transactionalAnnotation.rollbackFor() != null) {
                    for (Class<? extends Throwable> exception : transactionalAnnotation.rollbackFor()) {
                        if (exception.isInstance(e)) {
                            log.debug("Caught exception, rolling back action invocation "
                                    + action.getClass().getSimpleName());
                            transactionStatus.setRollbackOnly();
                            break;
                        }
                    }
                }
                result.setException(e);
            }
            return result;
        }
    });

    if (callbackResult.getException() != null)
        throw callbackResult.getException();

    return callbackResult.getResult();
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@Test
public void testJtaTransactionWithIsolationLevelContentSourceAdapter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final IsolationLevelContentSourceAdapter dsToUse = new IsolationLevelContentSourceAdapter();
    dsToUse.setTargetContentSource(contentSource);
    dsToUse.afterPropertiesSet();//  w  w  w .  j  av  a 2s  . c o m

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.setReadOnly(true);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session).setTransactionMode(Session.TransactionMode.QUERY);
    verify(session, times(2)).close();
}

From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java

@Override
public List<EvaluatedSuccessIndicatorTO> getForPerson(final UUID personId, final ObjectStatus status)
        throws ObjectNotFoundException {

    // Elaborate transaction management workaround b/c we can't avoid opening a transaction, but any exception
    // that crosses a transactional boundary in the code will mark the transaction as rollback only, which is
    // fine except that if we just tag this method with @Transactional(readOnly=true), the transaction manager
    // will still attempt a commit if the exception doesn't exit all the way out of this method (which is
    // what we usually want in this specific case - we want to try to return as many indicators as we can). And
    // if you attempt to commit a transaction marked as rollback only, you get a
    // org.springframework.transaction.UnexpectedRollbackException
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    transactionTemplate.setReadOnly(true);
    final AtomicReference<List<EvaluatedSuccessIndicatorTO>> rsltHolder = new AtomicReference<>();
    final AtomicReference<ObjectNotFoundException> onfeHolder = new AtomicReference<>();
    try {//from  w ww .  j a v a  2s . c  om
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus txnStatus) {
                try {
                    getForPersonInTransaction(personId, status, rsltHolder);
                } catch (ObjectNotFoundException e) {
                    onfeHolder.set(e);
                    throw new RuntimeException("Rolling back transaction", e);
                }
            }
        });
    } catch (UnexpectedRollbackException e) {
        // nothing to be done, totally normal. see comments above.
    } catch (RuntimeException e) {
        if (onfeHolder.get() == null) {
            throw e;
        } // otherwise it's just us, rolling back the transaction, nothing to be done, totally normal
    }

    if (onfeHolder.get() != null) {
        throw onfeHolder.get();
    }

    return rsltHolder.get();
}