Search in sources :

Example 46 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.

the class PluggableSCMMaterialUpdaterIntegrationTest method shouldUpdateMaterialInstanceWhenAdditionalDataIsUpdatedDuringLatestModificationsSince.

@Test
public void shouldUpdateMaterialInstanceWhenAdditionalDataIsUpdatedDuringLatestModificationsSince() throws Exception {
    final PluggableSCMMaterial material = MaterialsMother.pluggableSCMMaterial();
    final MaterialInstance materialInstance = material.createMaterialInstance();
    Map<String, String> oldData = new HashMap<>();
    oldData.put("k1", "v1");
    materialInstance.setAdditionalData(new GsonBuilder().create().toJson(oldData));
    materialRepository.saveOrUpdate(materialInstance);
    Map<String, String> newData = new HashMap<>(oldData);
    newData.put("k2", "v2");
    when(scmExtension.latestModificationSince(any(String.class), any(SCMPropertyConfiguration.class), any(Map.class), any(String.class), any(SCMRevision.class))).thenReturn(new MaterialPollResult(newData, new SCMRevision()));
    mockSCMExtensionInPoller();
    scmMaterialUpdater = new ScmMaterialUpdater(materialRepository, materialChecker, subprocessExecutionContext, materialService);
    pluggableSCMMaterialUpdater = new PluggableSCMMaterialUpdater(materialRepository, scmMaterialUpdater, transactionTemplate);
    transactionTemplate.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus transactionStatus) {
            pluggableSCMMaterialUpdater.insertLatestOrNewModifications(material, materialInstance, new File(""), new Modifications(new Modification()));
            return null;
        }
    });
    MaterialInstance actualInstance = materialRepository.findMaterialInstance(material);
    assertThat(actualInstance.getAdditionalDataMap(), is(newData));
}
Also used : Modification(com.thoughtworks.go.domain.materials.Modification) PluggableSCMMaterial(com.thoughtworks.go.config.materials.PluggableSCMMaterial) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) MaterialPollResult(com.thoughtworks.go.plugin.access.scm.material.MaterialPollResult) TransactionStatus(org.springframework.transaction.TransactionStatus) Modifications(com.thoughtworks.go.domain.materials.Modifications) TransactionCallback(org.springframework.transaction.support.TransactionCallback) SCMRevision(com.thoughtworks.go.plugin.access.scm.revision.SCMRevision) MaterialInstance(com.thoughtworks.go.domain.MaterialInstance) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 47 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project uPortal by Jasig.

the class PortalRawEventsAggregatorImplTest method aggregateRawEventsIncompleteByReturn.

@Test
public void aggregateRawEventsIncompleteByReturn() throws Exception {
    when(transactionOperations.execute(any(TransactionCallback.class))).then(new Answer<EventProcessingResult>() {

        @Override
        public EventProcessingResult answer(InvocationOnMock invocation) throws Throwable {
            final TransactionStatus status = mock(TransactionStatus.class);
            return ((TransactionCallback<EventProcessingResult>) invocation.getArguments()[0]).doInTransaction(status);
        }
    });
    when(clusterLockService.isLockOwner(PortalRawEventsAggregator.AGGREGATION_LOCK_NAME)).thenReturn(true);
    when(portalEventDimensionPopulator.isCheckedDimensions()).thenReturn(true);
    when(eventAggregationManagementDao.getEventAggregatorStatus(ProcessingType.AGGREGATION, true)).thenReturn(eventAggregatorStatus);
    when(portalInfoProvider.getUniqueServerName()).thenReturn("serverName_abcd");
    when(eventAggregatorStatus.getLastEventDate()).thenReturn(new DateTime(1325881376117l));
    when(portalEventDao.aggregatePortalEvents(any(DateTime.class), any(DateTime.class), (int) any(Integer.TYPE), (Function<PortalEvent, Boolean>) any(Function.class))).then(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            return false;
        }
    });
    final EventProcessingResult result = portalEventAggregator.doAggregateRawEvents();
    assertNotNull(result);
    assertEquals(0, result.getProcessed());
    assertEquals(false, result.isComplete());
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) PortalEvent(org.apereo.portal.events.PortalEvent) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TransactionStatus(org.springframework.transaction.TransactionStatus) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 48 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project uPortal by Jasig.

the class PortalRawEventsAggregatorImplTest method aggregateRawEventsIncompleteByProcessCount.

@Test
public void aggregateRawEventsIncompleteByProcessCount() throws Exception {
    when(transactionOperations.execute(any(TransactionCallback.class))).then(new Answer<EventProcessingResult>() {

        @Override
        public EventProcessingResult answer(InvocationOnMock invocation) throws Throwable {
            final TransactionStatus status = mock(TransactionStatus.class);
            return ((TransactionCallback<EventProcessingResult>) invocation.getArguments()[0]).doInTransaction(status);
        }
    });
    when(clusterLockService.isLockOwner(PortalRawEventsAggregator.AGGREGATION_LOCK_NAME)).thenReturn(true);
    when(portalEventDimensionPopulator.isCheckedDimensions()).thenReturn(true);
    when(eventAggregationManagementDao.getEventAggregatorStatus(ProcessingType.AGGREGATION, true)).thenReturn(eventAggregatorStatus);
    when(portalInfoProvider.getUniqueServerName()).thenReturn("serverName_abcd");
    when(eventAggregatorStatus.getLastEventDate()).thenReturn(new DateTime(1325881376117l));
    when(portalEventDao.aggregatePortalEvents(any(DateTime.class), any(DateTime.class), (int) any(Integer.TYPE), (Function<PortalEvent, Boolean>) any(Function.class))).then(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            ((Function<PortalEvent, Boolean>) invocation.getArguments()[3]).apply(new MockPortalEvent(this, "serverName", "eventSessionId", person));
            return false;
        }
    });
    when(eventSessionDao.getEventSession(any(PortalEvent.class))).thenReturn(eventSession);
    this.portalEventAggregator.setEventAggregationBatchSize(1);
    final EventProcessingResult result = portalEventAggregator.doAggregateRawEvents();
    assertNotNull(result);
    assertEquals(1, result.getProcessed());
    assertEquals(false, result.isComplete());
    this.portalEventAggregator.setEventAggregationBatchSize(1000);
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) PortalEvent(org.apereo.portal.events.PortalEvent) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TransactionStatus(org.springframework.transaction.TransactionStatus) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 49 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project uPortal by Jasig.

the class HibernateStyleCounterStore method getNextIdInternal.

private int getNextIdInternal(final Optimizer optimizer, final String counterName) {
    return (Integer) optimizer.generate(new AccessCallback() {

        @Override
        public IntegralDataTypeHolder getNextValue() {
            IntegralDataTypeHolder rslt = null;
            for (int i = 0; rslt == null && i < MAX_ATTEMPTS; i++) {
                rslt = transactionOperations.execute(new TransactionCallback<IntegralDataTypeHolder>() {

                    @Override
                    public IntegralDataTypeHolder doInTransaction(TransactionStatus status) {
                        final IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder(identifierType.getReturnedClass());
                        // Try and load the current value,
                        // returns true if the expected row
                        // exists, null otherwise
                        final boolean selected = jdbcOperations.query(SELECT_QUERY, new ResultSetExtractor<Boolean>() {

                            @Override
                            public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException {
                                if (rs.next()) {
                                    value.initialize(rs, 1);
                                    return true;
                                }
                                return false;
                            }
                        }, counterName);
                        // it
                        if (!selected) {
                            value.initialize(initialValue);
                            jdbcOperations.update(INSERT_QUERY, new PreparedStatementSetter() {

                                @Override
                                public void setValues(PreparedStatement ps) throws SQLException {
                                    ps.setString(1, counterName);
                                    value.bind(ps, 2);
                                }
                            });
                        }
                        // Increment the counter row value
                        final IntegralDataTypeHolder updateValue = value.copy();
                        if (optimizer.applyIncrementSizeToSourceValues()) {
                            updateValue.add(incrementSize);
                        } else {
                            updateValue.increment();
                        }
                        // Update the counter row, if rows
                        // returns 0 the update failed due to a
                        // race condition, it will be retried
                        int rowsAltered = jdbcOperations.update(UPDATE_QUERY, new PreparedStatementSetter() {

                            @Override
                            public void setValues(PreparedStatement ps) throws SQLException {
                                updateValue.bind(ps, 1);
                                ps.setString(2, counterName);
                                value.bind(ps, 3);
                            }
                        });
                        return rowsAltered > 0 ? // Success
                        value : // Failed;  try again...
                        null;
                    }
                });
            }
            if (rslt == null) {
                throw new RuntimeException("Failed to fetch a new batch of sequence values after " + MAX_ATTEMPTS + " tries");
            }
            return rslt;
        }
    });
}
Also used : SQLException(java.sql.SQLException) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement) AccessCallback(org.hibernate.id.enhanced.AccessCallback) TransactionCallback(org.springframework.transaction.support.TransactionCallback) ResultSet(java.sql.ResultSet) IntegralDataTypeHolder(org.hibernate.id.IntegralDataTypeHolder) DataAccessException(org.springframework.dao.DataAccessException)

Example 50 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project spring-framework by spring-projects.

the class WebSphereUowTransactionManagerTests method doTestNewTransactionWithCommit.

private void doTestNewTransactionWithCommit(int propagationBehavior, final int synchMode) {
    MockUOWManager manager = new MockUOWManager();
    WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
    ptm.setTransactionSynchronization(synchMode);
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    definition.setPropagationBehavior(propagationBehavior);
    definition.setReadOnly(true);
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
    assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {

        @Override
        public String doInTransaction(TransactionStatus status) {
            if (synchMode != WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER) {
                assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            } else {
                assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
                assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
                assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            }
            return "result";
        }
    }));
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
    assertEquals(0, manager.getUOWTimeout());
    assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
    assertFalse(manager.getJoined());
    assertFalse(manager.getRollbackOnly());
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionStatus(org.springframework.transaction.TransactionStatus)

Aggregations

TransactionCallback (org.springframework.transaction.support.TransactionCallback)100 TransactionStatus (org.springframework.transaction.TransactionStatus)75 Test (org.junit.Test)28 ArrayList (java.util.ArrayList)16 Test (org.junit.jupiter.api.Test)14 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)10 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)10 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)9 PreparedStatement (java.sql.PreparedStatement)8 List (java.util.List)8 GitMaterial (com.thoughtworks.go.config.materials.git.GitMaterial)7 MaterialInstance (com.thoughtworks.go.domain.MaterialInstance)7 Modification (com.thoughtworks.go.domain.materials.Modification)7 PackageMaterialInstance (com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance)7 PluggableSCMMaterialInstance (com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance)7 Query (org.hibernate.Query)7 BaseDbTest (com.alibaba.otter.node.etl.BaseDbTest)6 DbDialect (com.alibaba.otter.node.etl.common.db.dialect.DbDialect)6 Modifications (com.thoughtworks.go.domain.materials.Modifications)6 HgMaterialInstance (com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance)6