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:ch.tatool.app.service.impl.DataServiceImpl.java

/** Find the last x trials with given property of a given element
 * /*from w  w w  .  j  a v a  2s .co  m*/
 */
@SuppressWarnings("unchecked")
public List<Trial> getTrials(final Module module, final ModuleSession session, final String elementNameLike,
        final String propertyNameLike, final int offset, final int maxResults) {
    final ModuleImpl moduleImpl = (ModuleImpl) module;
    return (List<Trial>) moduleImpl.getTransactionTemplate().execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            return moduleImpl.getTrialDAO().getTrials(moduleImpl, session, elementNameLike, propertyNameLike,
                    offset, maxResults);
        }
    });
}

From source file:org.openvpms.component.business.service.archetype.rule.ArchetypeRuleService.java

/**
 * Executes an operation in a transaction, with before and after rules.
 * <ol>//from w w w  .ja  v a 2s.  com
 * <li>begin transaction
 * <li>execute <em>before</em> rules for each object
 * <li>execute {@code operation}
 * <li>execute <em>after</em> rules for each object
 * <li>commit on success/rollback on failure
 * </ol>
 *
 * @param name    the name of the operation
 * @param objects the object that will be supplied to before and after rules
 * @param op      the operation to execute
 */
private void execute(final String name, final Collection<? extends IMObject> objects, final Runnable op) {
    template.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            for (IMObject object : objects) {
                executeRules(name, object, true);
            }
            op.run();
            for (IMObject object : objects) {
                executeRules(name, object, false);
            }
            return null;
        }
    });
}

From source file:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java

private Document findDocumentToRetrieve() {
    return this.transactionTemplate.execute(new TransactionCallback<Document>() {

        public Document doInTransaction(TransactionStatus txStatus) {
            return DocumentRetrievalTaskImpl.this.documentDao.findAndLockOneDocument(DocumentState.DISCOVERED);
        }/*from  w w w .  j  av a  2  s. c om*/

    });
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceListenerTestCase.java

/**
 * Verifies that callbacks are invoked on transaction rollback.
 *//* w w  w .j av a 2s . c om*/
@Test
public void testTransactionRollback() {
    final IArchetypeService service = getArchetypeService();
    final Party person1 = createPerson();
    final Party person2 = createPerson();
    final Listener listener = new Listener();
    service.addListener("party.customerperson", listener);

    try {
        template.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus status) {
                listener.setInTransaction(true);
                service.save(person1);
                assertTrue(listener.getSaving().contains(person1));

                service.remove(person2);
                assertTrue(listener.getRemoving().contains(person2));
                listener.setInTransaction(false);
                throw new RuntimeException("Force rollback");
            }
        });
    } catch (RuntimeException ignore) {
        // do nothing
    }

    Set<IMObject> saving = listener.getSaving();
    Set<IMObject> removing = listener.getRemoving();

    assertEquals(1, saving.size());
    assertEquals(1, removing.size());

    assertTrue(listener.getSaved().isEmpty());
    assertTrue(listener.getRemoved().isEmpty());

    Set<IMObject> rolledBack = listener.getRolledBack();
    assertEquals(2, rolledBack.size());
    assertTrue(rolledBack.contains(person1));
    assertTrue(rolledBack.contains(person2));
}

From source file:com.thoughtworks.go.server.service.ScheduledPipelineLoaderIntegrationTest.java

@Test
public void shouldLoadPipelineAlongwithBuildCauseHavingMaterialPasswordsPopulated() {
    PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("last",
            new StageConfig(new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterial onDirOne = MaterialsMother.svnMaterial("google.com", "dirOne", "loser", "boozer", false,
            "**/*.html");
    P4Material onDirTwo = MaterialsMother.p4Material("host:987654321", "zoozer", "secret", "through-the-window",
            true);/* ww  w .ja v a2s.  c  o m*/
    onDirTwo.setFolder("dirTwo");
    pipelineConfig.addMaterialConfig(onDirOne.config());
    pipelineConfig.addMaterialConfig(onDirTwo.config());

    configHelper.addPipeline(pipelineConfig);

    Pipeline building = PipelineMother.building(pipelineConfig);
    Pipeline pipeline = dbHelper.savePipelineWithMaterials(building);

    final long jobId = pipeline.getStages().get(0).getJobInstances().get(0).getId();
    Pipeline loadedPipeline = (Pipeline) transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            return loader.pipelineWithPasswordAwareBuildCauseByBuildId(jobId);
        }
    });

    MaterialRevisions revisions = loadedPipeline.getBuildCause().getMaterialRevisions();
    assertThat(((SvnMaterial) revisions.findRevisionFor(onDirOne).getMaterial()).getPassword(), is("boozer"));
    assertThat(((P4Material) revisions.findRevisionFor(onDirTwo).getMaterial()).getPassword(), is("secret"));
}

From source file:com.bitsofproof.supernode.core.TxHandler.java

public void validateCacheAndSend(final Tx t, final BitcoinPeer peer) throws ValidationException {
    ValidationException exception = network.getStore().runInCacheContext(new BlockStore.CacheContextRunnable() {
        @Override//from  www.  jav  a2s  . c om
        public void run(TxOutCache cache) throws ValidationException {
            synchronized (unconfirmed) {
                if (!unconfirmed.containsKey(t.getHash())) {
                    ValidationException exception = new TransactionTemplate(transactionManager)
                            .execute(new TransactionCallback<ValidationException>() {
                                @Override
                                public ValidationException doInTransaction(TransactionStatus status) {
                                    status.setRollbackOnly();

                                    try {
                                        network.getStore().validateTransaction(t, availableOutput);
                                        sendTransaction(t, peer);
                                        cacheTransaction(t);
                                        notifyListener(t);
                                        if (peer == null) {
                                            synchronized (own) {
                                                own.add(t.getHash());
                                            }
                                        }
                                        return null;
                                    } catch (ValidationException e) {
                                        return e;
                                    }
                                }
                            });
                    if (exception != null) {
                        throw exception;
                    }
                }
            }
        }
    });
    if (exception != null) {
        log.debug("REJECTING transaction " + t.getHash());
        throw exception;
    }
}

From source file:org.jasig.cas.ticket.registry.JpaTicketRegistryTests.java

void deleteTicketInTransaction(final String ticketId) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.deleteTicket(ticketId);
            return null;
        }/*from w  ww .j  ava  2 s.com*/
    });
}

From source file:org.openremote.beehive.configuration.www.CommandsAPI.java

@DELETE
@Path("/{commandId}")
public Response deleteCommand(@PathParam("commandId") Long commandId) {
    final Command existingCommand = device.getCommandById(commandId);

    if (!device.getSensorsReferencingCommand(existingCommand).isEmpty()) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "This command is used by a sensor")).build();
    }//from ww w  . j  a v  a  2s.  c o m

    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus transactionStatus) {
            device.removeCommand(existingCommand);
            commandRepository.delete(existingCommand);
            return null;
        }
    });

    return Response.ok().build();
}

From source file:com.github.rholder.spring.transaction.TransactionBindingSupportTest.java

@Test
public void testListener() throws Exception {
    final List<String> strings = new ArrayList<String>(1);

    // anonymous inner class to test it
    final TransactionListener listener = new TransactionListener() {
        public void beforeCommit(boolean readOnly) {
            strings.add("beforeCommit");
        }/*w  ww.java  2s .c o  m*/

        public void beforeCompletion() {
            strings.add("beforeCompletion");
        }

        public void afterCommit() {
            strings.add("afterCommit");
        }

        public void afterRollback() {
            strings.add("afterRollback");
        }
    };

    // begin a transaction
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            // register it
            TransactionBindingSupport.bindListener(listener);
            return null;
        }
    });

    // test commit after return
    Assert.assertTrue("beforeCommit not called on listener", strings.contains("beforeCommit"));
    Assert.assertTrue("beforeCompletion not called on listener", strings.contains("beforeCompletion"));
    Assert.assertTrue("afterCommit not called on listener", strings.contains("afterCommit"));
    Assert.assertEquals("Unexpected size for collected listener logging", 3, strings.size());

    // reset logging
    strings.clear();

    // begin a transaction
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            // register it
            TransactionBindingSupport.bindListener(listener);

            // rollback
            status.setRollbackOnly();
            return null;
        }
    });

    // test rollback after return
    Assert.assertTrue("beforeCompletion not called on listener", strings.contains("beforeCompletion"));
    Assert.assertTrue("afterRollback not called on listener", strings.contains("afterRollback"));
    Assert.assertEquals("Unexpected size for collected listener logging", 2, strings.size());

}

From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java

public <K, T extends Persistable<K>> Collection<T> find(final Class<T> type, final Binding filter,
        final List<? extends Order> ordering, final Limit limit) {
    Collection<T> p_objects = _executeTx("find", type, filter, new TransactionCallback<Collection<T>>() {
        public Collection<T> doInTransaction(final TransactionStatus status) {
            return getDao(type).find(filter, ordering, limit);
        }//from w  ww.jav  a 2  s  . co  m
    });

    return p_objects;
}