Example usage for org.springframework.transaction.support TransactionCallback TransactionCallback

List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback

Introduction

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

Prototype

TransactionCallback

Source Link

Usage

From source file:org.openvpms.web.component.im.edit.SaveHelper.java

/**
 * Saves an editor in a transaction./*from  w w w.j ava 2 s.c  o m*/
 *
 * @param editor the editor to save
 * @return {@code true} if the object was saved successfully
 */
public static boolean save(final IMObjectEditor editor) {
    Boolean result = null;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        result = template.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                return editor.save();
            }
        });
    } catch (Throwable exception) {
        error(editor, exception);
    }
    return (result != null) && result;
}

From source file:org.openvpms.web.component.im.edit.SaveHelper.java

/**
 * Saves an editor and invokes a callback within a single transaction.
 *
 * @param editor   the editor/*from w w  w . j ava 2s .c  o  m*/
 * @param callback the callback
 * @return {@code true} if the object was saved and the callback returned {@code true}
 */
public static boolean save(final IMObjectEditor editor, final TransactionCallback<Boolean> callback) {
    Boolean result = null;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        result = template.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                boolean result = false;
                if (editor.save()) {
                    Boolean success = callback.doInTransaction(status);
                    result = success != null && success;
                }
                return result;
            }
        });
    } catch (Throwable exception) {
        error(editor, exception);
    }
    return (result != null) && result;
}

From source file:org.openvpms.web.component.im.edit.SaveHelper.java

/**
 * Replace an object, by deleting one instance and inserting another.
 *
 * @param delete the object to delete/*  w  w w . j  a  va2 s  .  c o  m*/
 * @param insert the object to insert
 * @return {@code true} if the operation was successful
 */
public static boolean replace(final IMObject delete, final IMObject insert) {
    Boolean result = null;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        result = template.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                IArchetypeService service = ServiceHelper.getArchetypeService();
                service.remove(delete);
                service.save(insert);
                return true;
            }
        });
    } catch (Throwable exception) {
        String title = Messages.get("imobject.replace.failed.title");
        ErrorHelper.show(title, exception);
    }
    return (result != null) && result;
}

From source file:org.openvpms.web.workspace.admin.lookup.LookupReplaceHelper.java

/**
 * Replaces references to the source lookup with the target lookup, optionally deleting the source lookup.
 *
 * @param source the source lookup//from w  w w. j  a  v a2  s  .com
 * @param target the target lookup
 * @param delete if <tt>true</tt> delete the source lookup
 */
public void replace(final Lookup source, final Lookup target, final boolean delete) {
    TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            doReplace(source, target, delete);
            return null;
        }
    });
}

From source file:org.orcid.core.manager.impl.OrcidProfileManagerReadOnlyImpl.java

@Override
public OrcidProfile retrieveFreshOrcidProfile(final String orcid, final LoadOptions loadOptions) {
    return transactionTemplate.execute(new TransactionCallback<OrcidProfile>() {
        public OrcidProfile doInTransaction(TransactionStatus status) {
            return doRetrieveFreshOrcidProfileInTransaction(orcid, loadOptions);
        }//from  ww w  . j ava 2 s .c  om
    });
}

From source file:org.pentaho.platform.repository2.unified.lifecycle.AbstractBackingRepositoryLifecycleManager.java

public Boolean doesMetadataExists(final String metadataProperty) {
    try {/* www  .j  a  v  a  2s  .c  o m*/
        return (Boolean) txnTemplate.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                return adminJcrTemplate.execute(new JcrCallback() {
                    @Override
                    public Object doInJcr(Session session) throws IOException, RepositoryException {
                        PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
                        String absPath = ServerRepositoryPaths.getPentahoRootFolderPath();
                        RepositoryFile rootFolder = JcrRepositoryFileUtils.getFileByAbsolutePath(session,
                                absPath, pathConversionHelper, null, false, null);
                        if (rootFolder != null) {
                            Map<String, Serializable> metadataMap = JcrRepositoryFileUtils
                                    .getFileMetadata(session, rootFolder.getId());
                            for (Entry<String, Serializable> metadataEntry : metadataMap.entrySet()) {
                                if (metadataEntry.getKey().equals(metadataProperty)) {
                                    return (Boolean) metadataEntry.getValue();
                                }
                            }
                        }
                        return false;
                    }
                });
            }
        });
    } catch (Throwable th) {
        th.printStackTrace();
        return false;
    }
}

From source file:org.projectforge.business.user.UserTest.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test//from w  w  w.  j  a v  a 2  s . c  o m
public void testUniqueUsernameDO() {
    final Serializable[] ids = new Integer[2];
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    txTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            PFUserDO user = createTestUser("42");
            ids[0] = userService.save(user);
            user = createTestUser("100");
            ids[1] = userService.save(user);
            return null;
        }
    });
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    txTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            final PFUserDO user = createTestUser("42");
            assertTrue("Username should already exist.", userService.doesUsernameAlreadyExist(user));
            user.setUsername("5");
            assertFalse("Signature should not exist.", userService.doesUsernameAlreadyExist(user));
            userService.save(user);
            return null;
        }
    });
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    txTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            final PFUserDO dbBook = userService.getById(ids[1]);
            final PFUserDO user = new PFUserDO();
            user.copyValuesFrom(dbBook);
            assertFalse("Signature does not exist.", userService.doesUsernameAlreadyExist(user));
            user.setUsername("42");
            assertTrue("Signature does already exist.", userService.doesUsernameAlreadyExist(user));
            user.setUsername("4711");
            assertFalse("Signature does not exist.", userService.doesUsernameAlreadyExist(user));
            userService.update(user);
            return null;
        }
    });
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    txTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            final PFUserDO user = userService.getById(ids[1]);
            assertFalse("Signature does not exist.", userService.doesUsernameAlreadyExist(user));
            return null;
        }
    });
}

From source file:org.projectforge.core.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:
        public Object doInTransaction(final TransactionStatus status) {
            try {
                hibernate.execute(new HibernateCallback() {
                    public Object doInHibernate(final Session session) throws HibernateException {
                        databaseDao.reindex(clazz, settings, buf);
                        status.setRollbackOnly();
                        return null;
                    }//from w  ww  .  j  a  va2 s .c  o m
                });
            } 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.database.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.
 * @param writer Ziel fr die XML-Datei./*from   www .j a  v  a2 s  .com*/
 * @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() {
        public Object doInTransaction(final TransactionStatus status) {
            hibernate.execute(new HibernateCallback() {
                public Object doInHibernate(final Session session) throws HibernateException {
                    writeObjects(writer, includeHistory, session, preserveIds);
                    status.setRollbackOnly();
                    return null;
                }
            });
            return null;
        }
    });
}

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  va2 s . com*/
        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;
        }
    });
}