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:com.github.rholder.spring.transaction.TransactionBindingSupportTest.java

@Test
public void testResourceHelperSet() throws Exception {

    // run this in a transaction        
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            Set<String> set = TransactionalResourceHelper.getSet("abc");
            Assert.assertNotNull("Set not created", set);
            set.add("ONE");
            Set<String> setCheck = TransactionalResourceHelper.getSet("abc");
            Assert.assertTrue("Same map not retrieved", set == setCheck);
            return null;
        }/*  ww  w.j  a  va2  s.c o  m*/
    });
}

From source file:com.devnexus.ting.core.service.impl.BusinessServiceImpl.java

/**
 * {@inheritDoc}/*from   w  w  w. ja v a  2 s .  c  om*/
 */
@Override
@Cacheable("getSpeakersForEvent")
public List<Speaker> getSpeakersForEvent(Long eventId) {

    final List<Speaker> speakers = transactionTemplate.execute(new TransactionCallback<List<Speaker>>() {
        public List<Speaker> doInTransaction(TransactionStatus status) {
            return speakerDao.getSpeakersForEvent(eventId);
        }
    });

    return speakers;

}

From source file:com.hs.mail.imap.mailbox.DefaultMailboxManager.java

public void resetRecent(final long mailboxID) {
    List<Long> recents = (List<Long>) getTransactionTemplate().execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            try {
                MessageDao dao = DaoFactory.getMessageDao();
                return dao.resetRecent(mailboxID);
            } catch (DataAccessException ex) {
                status.setRollbackOnly();
                throw ex;
            }//from  w w  w  .j av  a 2  s  .com
        }
    });
    if (fdCache != null && CollectionUtils.isNotEmpty(recents)) {
        for (long uid : recents) {
            fdCache.remove(uid);
        }
    }
}

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

/**
 * Verifies that saved but uncommitted acts can be resolved using
 * {@link IArchetypeService#get(IMObjectReference)} in a transaction,
 * even if an identifier hasn't been assigned.
 *///from ww  w  . ja v  a2s .  co  m
@Test
public void testResolveUncommittedActs() {
    // Create 2 acts with the following relationship:
    // act1 -- (parent/child) --> act2
    final Act act1 = createSimpleAct("act1", "IN_PROGRESS");
    final Act act2 = createSimpleAct("act2", "IN_PROGRESS");
    addRelationship(act1, act2, "act1->act2", true);

    assertNull(get(act1.getObjectReference()));
    assertNull(get(act2.getObjectReference()));

    // now try to save each act within a transaction.
    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            save(act1);
            // act has been saved, but the identifier cannot be assigned
            // until the related act is also saved
            assertEquals(-1, act1.getId());

            // verify that the act can be retrieved by reference, and is
            // the same object
            assertSame(act1, get(act1.getObjectReference()));

            assertNull(get(act2.getObjectReference()));
            save(act2);

            // identifiers should have updated
            assertFalse(act1.getId() == -1);
            assertFalse(act2.getId() == -1);

            // verify that the acts can be retrieved by reference, and are
            // the same objects
            assertSame(act1, get(act1.getObjectReference()));
            assertSame(act2, get(act2.getObjectReference()));
            return null;
        }
    });

    IMObject reload1 = get(act1.getObjectReference());
    IMObject reload2 = get(act2.getObjectReference());
    assertNotNull(reload1);
    assertNotNull(reload2);

    // the reloaded acts should now be different objects as it is a
    // different transaction
    assertNotSame(act1, reload1);
    assertNotSame(act2, reload2);
}

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

@Test
public void testResourceHelperTreeSet() throws Exception {

    // run this in a transaction        
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            TreeSet<String> treeSet = TransactionalResourceHelper.getTreeSet("abc");
            Assert.assertNotNull("Map not created", treeSet);
            treeSet.add("ONE");
            TreeSet<String> treeSetCheck = TransactionalResourceHelper.getTreeSet("abc");
            Assert.assertTrue("Same map not retrieved", treeSet == treeSetCheck);
            return null;
        }//from  w w  w . j  a  v a2  s. co  m
    });
}

From source file:com.devnexus.ting.core.service.impl.BusinessServiceImpl.java

/**
 * {@inheritDoc}//  w  w  w  .  ja  va2s. com
 */
@Override
public Organizer saveOrganizer(Organizer organizer) {
    final Organizer savedOrganizer = transactionTemplate.execute(new TransactionCallback<Organizer>() {
        public Organizer doInTransaction(TransactionStatus status) {
            return organizerDao.save(organizer);
        }
    });
    return savedOrganizer;
}

From source file:dao.FlowsDAO.java

public static ObjectNode getPagedFlowsByProject(String applicationName, String project, int page, int size) {
    ObjectNode result;//  w w w  .  ja va  2s .  c o  m

    if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(project)) {
        result = Json.newObject();
        result.put("count", 0);
        result.put("page", page);
        result.put("itemsPerPage", size);
        result.put("totalPages", 0);
        result.set("flows", Json.toJson(""));
        return result;
    }

    String application = applicationName.replace(".", " ");

    Integer appID = getApplicationIDByName(applicationName);
    if (appID != 0) {
        javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
        DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
        TransactionTemplate txTemplate = new TransactionTemplate(tm);
        final int applicationID = appID;
        result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
            public ObjectNode doInTransaction(TransactionStatus status) {
                ObjectNode resultNode = Json.newObject();
                long count = 0;
                List<Flow> pagedFlows = new ArrayList<Flow>();
                List<Map<String, Object>> rows = null;
                if (StringUtils.isNotBlank(project) && (!project.equalsIgnoreCase("root"))) {
                    rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS_BY_APP_ID_AND_PROJECT_NAME,
                            applicationID, project, (page - 1) * size, size);
                } else {
                    rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS_WITHOUT_PROJECT_BY_APP_ID,
                            applicationID, (page - 1) * size, size);
                }

                try {
                    count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
                } catch (EmptyResultDataAccessException e) {
                    Logger.error("Exception = " + e.getMessage());
                }
                for (Map row : rows) {
                    Flow flow = new Flow();
                    flow.id = (Long) row.get("flow_id");
                    flow.level = (Integer) row.get("flow_level");
                    flow.name = (String) row.get("flow_name");
                    flow.path = (String) row.get("flow_path");
                    flow.appCode = (String) row.get("app_code");
                    flow.group = project;
                    if (StringUtils.isNotBlank(flow.path)) {
                        int index = flow.path.indexOf(":");
                        if (index != -1) {
                            flow.path = flow.path.substring(0, index);
                        }
                    }
                    Object created = row.get("created_time");
                    if (created != null) {
                        flow.created = DateFormat.format(created.toString());
                    }
                    Object modified = row.get("modified_time");
                    if (modified != null) {
                        flow.modified = DateFormat.format(row.get("modified_time").toString());
                    }

                    int jobCount = 0;

                    if (flow.id != null && flow.id != 0) {
                        try {
                            jobCount = getJdbcTemplate().queryForObject(GET_JOB_COUNT_BY_APP_ID_AND_FLOW_ID,
                                    new Object[] { appID, flow.id }, Integer.class);
                            flow.jobCount = jobCount;
                        } catch (EmptyResultDataAccessException e) {
                            Logger.error("Exception = " + e.getMessage());
                        }
                    }
                    pagedFlows.add(flow);
                }
                resultNode.set("flows", Json.toJson(pagedFlows));
                resultNode.put("count", count);
                resultNode.put("page", page);
                resultNode.put("itemsPerPage", size);
                resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));

                return resultNode;
            }
        });
        return result;
    }

    result = Json.newObject();
    result.put("count", 0);
    result.put("page", page);
    result.put("itemsPerPage", size);
    result.put("totalPages", 0);
    result.set("flows", Json.toJson(""));
    return result;
}

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

@Test
public void shouldSetAServerHealthMessageWhenMaterialForPipelineWithBuildCauseIsNotFound()
        throws IllegalArtifactLocationException, IOException {
    PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("last",
            new StageConfig(new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterialConfig onDirOne = MaterialConfigsMother.svnMaterialConfig("google.com", "dirOne", "loser",
            "boozer", false, "**/*.html");
    final P4MaterialConfig onDirTwo = MaterialConfigsMother.p4MaterialConfig("host:987654321", "zoozer",
            "secret", "through-the-window", true);
    onDirTwo.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "dirTwo"));
    pipelineConfig.addMaterialConfig(onDirOne);
    pipelineConfig.addMaterialConfig(onDirTwo);

    configHelper.addPipeline(pipelineConfig);

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

    CruiseConfig cruiseConfig = configHelper.currentConfig();
    PipelineConfig cfg = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("last"));
    cfg.removeMaterialConfig(cfg.materialConfigs().get(1));
    configHelper.writeConfigFile(cruiseConfig);

    assertThat(serverHealthService.filterByScope(HealthStateScope.forPipeline("last")).size(), is(0));

    final long jobId = pipeline.getStages().get(0).getJobInstances().get(0).getId();

    Date currentTime = new Date(System.currentTimeMillis() - 1);
    Pipeline loadedPipeline = (Pipeline) transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            Pipeline loadedPipeline = null;
            try {
                loadedPipeline = loader.pipelineWithPasswordAwareBuildCauseByBuildId(jobId);
                fail("should not have loaded pipeline with build-cause as one of the necessary materials was not found");
            } catch (Exception e) {
                assertThat(e, is(instanceOf(StaleMaterialsOnBuildCause.class)));
                assertThat(e.getMessage(), is("Cannot load job 'last/" + pipeline.getCounter()
                        + "/stage/1/job-one' because material " + onDirTwo + " was not found in config."));
            }/*w w  w  .j a  v  a  2 s .  c  o  m*/
            return loadedPipeline;
        }
    });

    assertThat(loadedPipeline, is(nullValue()));

    JobInstance reloadedJobInstance = jobInstanceService.buildById(jobId);
    assertThat(reloadedJobInstance.getState(), is(JobState.Completed));
    assertThat(reloadedJobInstance.getResult(), is(JobResult.Failed));

    assertThat(serverHealthService.filterByScope(HealthStateScope.forJob("last", "stage", "job-one")).size(),
            is(1));
    ServerHealthState error = serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one")).get(0);
    assertThat(error, is(ServerHealthState.error(
            "Cannot load job 'last/" + pipeline.getCounter() + "/stage/1/job-one' because material " + onDirTwo
                    + " was not found in config.",
            "Job for pipeline 'last/" + pipeline.getCounter()
                    + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed.",
            HealthStateType.general(HealthStateScope.forJob("last", "stage", "job-one")))));
    DateTime expiryTime = (DateTime) ReflectionUtil.getField(error, "expiryTime");
    assertThat(expiryTime.toDate().after(currentTime), is(true));
    assertThat(expiryTime.toDate().before(new Date(System.currentTimeMillis() + 5 * 60 * 1000 + 1)), is(true));

    String logText = FileUtils
            .readFileToString(consoleService.consoleLogArtifact(reloadedJobInstance.getIdentifier()), UTF_8);
    assertThat(logText, containsString("Cannot load job 'last/" + pipeline.getCounter()
            + "/stage/1/job-one' because material " + onDirTwo + " was not found in config."));
    assertThat(logText, containsString("Job for pipeline 'last/" + pipeline.getCounter()
            + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed."));
}

From source file:com.goodhuddle.huddle.service.impl.MemberServiceImpl.java

@Override
public ImportMembersResults importMembers(MultipartFile multipartFile, Long[] tagIds) {
    final ImportMembersResults results = new ImportMembersResults();
    results.setSuccess(true);/* w  w  w. ja v a  2s  .  c om*/

    try {
        final Huddle huddle = huddleService.getHuddle();

        if (!multipartFile.isEmpty()) {

            File file = fileStore.getTempFile(fileStore.createTempFile(multipartFile.getBytes()));

            final CSVReader reader = new CSVReader(new FileReader(file));
            if (reader.readNext() != null) {
                // skipped header row

                final List<Tag> tags = new ArrayList<>();
                if (tagIds != null) {
                    for (Long tagId : tagIds) {
                        tags.add(tagRepository.findByHuddleAndId(huddle, tagId));
                    }
                }

                boolean done = false;
                while (!done) {
                    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
                    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    done = txTemplate.execute(new TransactionCallback<Boolean>() {

                        @Override
                        public Boolean doInTransaction(TransactionStatus status) {
                            try {
                                int i = 0;
                                String[] nextLine;
                                while ((nextLine = reader.readNext()) != null) {
                                    String email = nextLine[0];
                                    String firstName = nextLine[1];
                                    String lastName = nextLine[2];
                                    String postCode = nextLine[3];
                                    String phone = nextLine[4];

                                    Member member = memberRepository.findByHuddleAndEmailIgnoreCase(huddle,
                                            email);
                                    if (member != null) {
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        List<Tag> memberTags = member.getTags();
                                        if (memberTags == null) {
                                            memberTags = new ArrayList<>();
                                        }
                                        outer: for (Tag tag : tags) {
                                            for (Tag memberTag : memberTags) {
                                                if (memberTag.getId() == member.getId()) {
                                                    break outer;
                                                }
                                            }
                                            memberTags.add(tag);
                                        }
                                        member.setTags(memberTags);
                                        memberRepository.save(member);
                                        results.setNumUpdated(results.getNumUpdated() + 1);
                                    } else {
                                        member = new Member();
                                        member.setHuddle(huddle);
                                        member.setEmail(email);
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        member.setTags(tags);
                                        memberRepository.save(member);
                                        results.setNumImported(results.getNumImported() + 1);
                                    }

                                    if (i++ > 30) {
                                        return false;
                                    }
                                }
                                return true;
                            } catch (IOException e) {
                                log.error("Error importing file: " + e, e);
                                results.setSuccess(false);
                                results.setErrorMessage("Error importing file: " + e);
                                return true;
                            }
                        }
                    });
                }

            }

        } else {
            log.info("Empty file was uploaded");
            results.setSuccess(false);
            results.setErrorMessage("Empty file was uploaded");
        }
    } catch (IOException e) {
        results.setSuccess(false);
        results.setErrorMessage("Error uploading file: " + e);
    }

    return results;
}

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Tests in TX collection element update with // optimistic locking.
 *///from  www  . j av  a  2 s. c  o  m
@Test
public void testInTXCollectionElementUpdate() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();

    final AtomicInteger countDown = new AtomicInteger(10);
    ExecutorService es = Executors.newFixedThreadPool(countDown.get());
    List<Future<Set<String>>> futures = new ArrayList<Future<Set<String>>>();
    for (int t = countDown.intValue(); t > 0; t--) {
        futures.add(es.submit(new Callable<Set<String>>() {

            @Override
            public Set<String> call() throws Exception {
                final HibernateBackendController threadHbc = getApplicationContext()
                        .getBean("applicationBackController", HibernateBackendController.class);
                final TransactionTemplate threadTT = threadHbc.getTransactionTemplate();
                threadHbc.start(hbc.getLocale(), hbc.getClientTimeZone());
                threadHbc.setApplicationSession(hbc.getApplicationSession());
                BackendControllerHolder.setThreadBackendController(threadHbc);
                return threadTT.execute(new TransactionCallback<Set<String>>() {

                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Set<String> doInTransaction(TransactionStatus status) {
                        DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class);
                        Set<String> names = new HashSet<String>();
                        Company c = (Company) compCrit.getExecutableCriteria(threadHbc.getHibernateSession())
                                .list().iterator().next();

                        synchronized (countDown) {
                            countDown.decrementAndGet();
                            // wait for all threads to arrive here so that we are sure they
                            // have all read the same data.
                            try {
                                countDown.wait();
                            } catch (InterruptedException ex) {
                                throw new BackendException("Test has been interrupted");
                            }
                        }

                        if (c.getName().startsWith("TX_")) {
                            throw new BackendException("Wrong data read from DB");
                        }
                        c.setName("TX_" + Long.toHexString(System.currentTimeMillis()));
                        names.add(c.getName());
                        for (Department d : c.getDepartments()) {
                            d.setName(Long.toHexString(System.currentTimeMillis()));
                            names.add(d.getName());
                        }
                        return names;
                    }
                });
            }
        }));
    }
    while (countDown.get() > 0) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            throw new BackendException("Test has been interrupted");
        }
    }
    synchronized (countDown) {
        countDown.notifyAll();
    }
    int successfullTxCount = 0;
    Set<String> names = new HashSet<String>();
    for (Future<Set<String>> f : futures) {
        try {
            names = f.get();
            successfullTxCount++;
        } catch (Exception ex) {
            if (ex.getCause() instanceof OptimisticLockingFailureException) {
                // safely ignore since this is what we are testing.
            } else {
                throw new BackendException(ex);
            }
        }
    }
    es.shutdown();
    assertTrue("Only 1 TX succeeded", successfullTxCount == 1);

    DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class);
    Company c = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_LAZY, Company.class);
    assertTrue("the company name is the one of the successfull TX", names.contains(c.getName()));
    for (Department d : c.getDepartments()) {
        assertTrue("the department name is the one of the successfull TX", names.contains(d.getName()));
    }
}