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

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

Introduction

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

Prototype

@Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException 

Source Link

Usage

From source file:org.projectforge.framework.persistence.history.HibernateSearchReindexer.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void reindex(final Class<?> clazz, final ReindexSettings settings, final StringBuffer buf) {
    // PF-378: Performance of run of full re-indexing the data-base is very slow for large data-bases
    // Single transactions needed, otherwise the full run will be very slow for large data-bases.
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        // The call-back is needed, otherwise a lot of transactions are left open until last run is completed:
        @Override//from  w w w .ja va 2  s. c  om
        public Object doInTransaction(final TransactionStatus status) {
            try {
                hibernate.execute(new HibernateCallback() {
                    @Override
                    public Object doInHibernate(final Session session) throws HibernateException {
                        databaseDao.reindex(clazz, settings, buf);
                        status.setRollbackOnly();
                        return null;
                    }
                });
            } catch (final Exception ex) {
                buf.append(" (an error occured, see log file for further information.), ");
                log.error("While rebuilding data-base-search-index for '" + clazz.getName() + "': "
                        + ex.getMessage(), ex);
            }
            return null;
        }
    });
}

From source file:org.projectforge.framework.persistence.xstream.HibernateXmlConverter.java

/**
 * Schreibt alle Objekte der Datenbank in den angegebenen Writer.<br/>
 * <b>Warnung!</b> Bei der Serialisierung von Collections wird derzeit nur {@link java.util.Set} sauber untersttzt.
 * //from   w  ww.  ja v  a  2 s.c  o  m
 * @param writer Ziel fr die XML-Datei.
 * @param includeHistory bei false werden die History Eintrge nicht geschrieben
 * @param preserveIds If true, the object ids will be preserved, otherwise new ids will be assigned through xstream.
 */
public void dumpDatabaseToXml(final Writer writer, final boolean includeHistory, final boolean preserveIds) {
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            hibernate.execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(final Session session) throws HibernateException {
                    writeObjects(writer, includeHistory, session, preserveIds);
                    status.setRollbackOnly();
                    return null;
                }
            });
            return null;
        }
    });
}

From source file:org.sakaiproject.component.app.help.HelpManagerImpl.java

private void dropExistingContent() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("dropExistingContent()");
    }//from  ww  w.jav a 2s. c  o m

    TransactionTemplate tt = new TransactionTemplate(txManager);
    tt.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            getHibernateTemplate().bulkUpdate("delete CategoryBean");
            getHibernateTemplate().flush();
            return null;
        }
    });
}

From source file:org.sakaiproject.portal.service.BullhornServiceImpl.java

public void update(Observable o, final Object arg) {

    if (arg instanceof Event) {
        Event e = (Event) arg;
        String event = e.getEvent();
        // We add this comparation with UNKNOWN_USER because implementation of BaseEventTrackingService
        // UNKNOWN_USER is an user in a server without session. 
        if (HANDLED_EVENTS.contains(event) && !EventTrackingService.UNKNOWN_USER.equals(e.getUserId())) {
            String ref = e.getResource();
            String context = e.getContext();
            String[] pathParts = ref.split("/");
            String from = e.getUserId();
            long at = e.getEventTime().getTime();
            try {
                BullhornHandler handler = handlerMap.get(event);

                if (handler != null) {
                    Optional<List<BullhornData>> result = handler.handleEvent(e, countCache);
                    if (result.isPresent()) {
                        result.get().forEach(bd -> {

                            if (bd.isSocial()) {
                                doSocialInsert(bd.getFrom(), bd.getTo(), event, ref, e.getEventTime(),
                                        bd.getUrl());
                            } else {
                                doAcademicInsert(from, bd.getTo(), event, ref, bd.getTitle(), bd.getSiteId(),
                                        e.getEventTime(), bd.getUrl());
                            }/*from   w w w.  j a  v a  2  s . c o  m*/
                        });
                    }
                } else if (LessonBuilderEvents.COMMENT_CREATE.equals(event)) {
                    try {
                        long commentId = Long.parseLong(pathParts[pathParts.length - 1]);
                        SimplePageComment comment = simplePageToolDao.findCommentById(commentId);

                        String url = simplePageToolDao.getPageUrl(comment.getPageId());

                        if (url != null) {
                            List<String> done = new ArrayList<>();
                            // Alert tutor types.
                            List<User> receivers = securityService.unlockUsers(
                                    SimplePage.PERMISSION_LESSONBUILDER_UPDATE, "/site/" + context);
                            for (User receiver : receivers) {
                                String to = receiver.getId();
                                if (!to.equals(from)) {
                                    doAcademicInsert(from, to, event, ref, "title", context, e.getEventTime(),
                                            url);
                                    done.add(to);
                                    countCache.remove(to);
                                }
                            }

                            // Get all the comments in the same item
                            List<SimplePageComment> comments = simplePageToolDao
                                    .findCommentsOnItems(Arrays.asList(new Long[] { comment.getItemId() }));

                            if (comments.size() > 1) {
                                // Not the first, alert all the other commenters unless they already have been
                                for (SimplePageComment c : comments) {
                                    String to = c.getAuthor();
                                    if (!to.equals(from) && !done.contains(to)) {
                                        doAcademicInsert(from, to, event, ref, "title", context,
                                                e.getEventTime(), url);
                                        done.add(to);
                                        countCache.remove(to);
                                    }
                                }
                            }
                        } else {
                            log.error("null url for page {}", comment.getPageId());
                        }
                    } catch (NumberFormatException nfe) {
                        log.error("Caught number format exception whilst handling events", nfe);
                    }
                } else if (SiteService.EVENT_SITE_PUBLISH.equals(event)) {
                    final String siteId = pathParts[2];

                    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

                    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

                        protected void doInTransactionWithoutResult(TransactionStatus status) {

                            final List<BullhornAlert> deferredAlerts = sessionFactory.getCurrentSession()
                                    .createCriteria(BullhornAlert.class).add(Restrictions.eq("deferred", true))
                                    .add(Restrictions.eq("siteId", siteId)).list();

                            for (BullhornAlert da : deferredAlerts) {
                                da.setDeferred(false);
                                sessionFactory.getCurrentSession().update(da);
                                countCache.remove(da.getToUser());
                            }
                        }
                    });
                }
            } catch (Exception ex) {
                log.error("Caught exception whilst handling events", ex);
            }
        }
    }
}

From source file:org.sakaiproject.portal.service.BullhornServiceImpl.java

private void doAcademicInsert(String from, String to, String event, String ref, String title, String siteId,
        Date eventDate, String url) {

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            BullhornAlert ba = new BullhornAlert();
            ba.setAlertType(ACADEMIC);/*w  ww  .  j  ava 2  s .com*/
            ba.setFromUser(from);
            ba.setToUser(to);
            ba.setEvent(event);
            ba.setRef(ref);
            ba.setTitle(title);
            ba.setSiteId(siteId);
            ba.setEventDate(eventDate.toInstant());
            ba.setUrl(url);
            try {
                ba.setDeferred(!siteService.getSite(siteId).isPublished());
            } catch (IdUnusedException iue) {
                log.warn("Failed to find site with id {} while setting deferred to published", siteId);
            }

            sessionFactory.getCurrentSession().persist(ba);
        }
    });
}

From source file:org.sakaiproject.portal.service.BullhornServiceImpl.java

private void doSocialInsert(String from, String to, String event, String ref, Date eventDate, String url) {

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            BullhornAlert ba = new BullhornAlert();
            ba.setAlertType(SOCIAL);//from  w w  w  .ja v a  2  s.c  o  m
            ba.setFromUser(from);
            ba.setToUser(to);
            ba.setEvent(event);
            ba.setRef(ref);
            ba.setTitle("");
            ba.setSiteId("");
            ba.setEventDate(eventDate.toInstant());
            ba.setUrl(url);
            ba.setDeferred(false);

            sessionFactory.getCurrentSession().persist(ba);
        }
    });
}

From source file:org.sipfoundry.sipxconfig.bulk.RowInserter.java

public final void execute(Object input) {
    T row = (T) input;//w  w  w  .  j  a va2s  .  c  o  m
    String jobDescription = dataToString(row);
    final Serializable jobId = m_jobContext.schedule("Import data: " + jobDescription);

    TransactionTemplate tt = new TransactionTemplate(m_transactionManager);
    try {
        TransactionCallback callback = new JobTransaction(jobId, row);
        tt.execute(callback);
    } catch (UserException e) {
        // ignore user exceptions - just log them
        m_jobContext.failure(jobId, null, e);
    } catch (RuntimeException e) {
        // log and rethrow other exceptions
        m_jobContext.failure(jobId, null, e);
        throw e;
    }
}

From source file:org.springframework.batch.test.DataSourceInitializer.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;/*from  w  w w. j a v a2 s  . co m*/
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
                            logger.debug("DROP script failed (ignoring): " + script);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.springframework.data.neo4j.support.Neo4jTemplate.java

@Override
public <T> T exec(final GraphCallback<T> callback) {
    if (infrastructure.getTransactionManager() == null)
        return doExecute(callback);

    TransactionTemplate template = new TransactionTemplate(infrastructure.getTransactionManager());
    return template.execute(new TransactionCallback<T>() {
        @Override/*from   ww w  . java 2s.c  o m*/
        public T doInTransaction(TransactionStatus status) {
            return doExecute(callback);
        }
    });
}

From source file:org.springframework.integration.endpoint.PseudoTransactionalMessageSourceTests.java

@Test
public void testCommitWithManager() {
    final PollableChannel queueChannel = new QueueChannel();
    TransactionTemplate transactionTemplate = new TransactionTemplate(new PseudoTransactionManager());
    transactionTemplate.execute(status -> {
        SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
        ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = new ExpressionEvaluatingTransactionSynchronizationProcessor();
        syncProcessor.setBeanFactory(mock(BeanFactory.class));
        syncProcessor.setBeforeCommitExpression(new SpelExpressionParser().parseExpression("#bix"));
        syncProcessor.setBeforeCommitChannel(queueChannel);
        syncProcessor.setAfterCommitChannel(queueChannel);
        syncProcessor.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#baz"));

        DefaultTransactionSynchronizationFactory syncFactory = new DefaultTransactionSynchronizationFactory(
                syncProcessor);/*w  ww . j  a  v a 2  s  . c  o  m*/

        adapter.setTransactionSynchronizationFactory(syncFactory);

        QueueChannel outputChannel = new QueueChannel();
        adapter.setOutputChannel(outputChannel);
        adapter.setSource(new MessageSource<String>() {

            @Override
            public Message<String> receive() {
                GenericMessage<String> message = new GenericMessage<String>("foo");
                IntegrationResourceHolder holder = (IntegrationResourceHolder) TransactionSynchronizationManager
                        .getResource(this);
                holder.addAttribute("baz", "qux");
                holder.addAttribute("bix", "qox");
                return message;
            }
        });

        doPoll(adapter);
        return null;
    });
    Message<?> beforeCommitMessage = queueChannel.receive(1000);
    assertNotNull(beforeCommitMessage);
    assertEquals("qox", beforeCommitMessage.getPayload());
    Message<?> afterCommitMessage = queueChannel.receive(1000);
    assertNotNull(afterCommitMessage);
    assertEquals("qux", afterCommitMessage.getPayload());
}