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

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

Introduction

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

Prototype

TransactionCallbackWithoutResult

Source Link

Usage

From source file:database.DataLoader.java

/**
 *  ?  ?  ?   /*from   www.j  ava2 s . c  o  m*/
 */
private void moveUsers() throws SQLException, ClassNotFoundException, Exception {
    try {
        //    
        final String modelName = USERS;
        final ResultSet userRes = getFromOldBase(getSelectAll(modelName));
        // ?   
        while (userRes.next()) {

            final TransactionTemplate temp = new TransactionTemplate(transactionManager);
            temp.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus ts) {
                    Long userId = 0L;
                    try {
                        userId = userRes.getLong("id");

                        String email = trim(userRes.getString("email"));
                        String password = trim(userRes.getString("password"));
                        String hash = VuzSecurity.getHash(password);
                        String firstname = "";
                        String lastname = "";
                        String fathername = "";
                        String phone = "";

                        ResultSet userProfileRes = getUserProfile(userId);
                        if (getRowCount(userProfileRes) > 0) {
                            firstname = trim(userProfileRes.getString("firstname"));
                            lastname = trim(userProfileRes.getString("lastname"));
                            fathername = trim(userProfileRes.getString("fathername"));
                            phone = userProfileRes.getString("phone");
                        }

                        ResultSet adminRes = getAdmin(userId);
                        ResultSet subadminSet = getFromOldBase(
                                " select * from " + SUBADMIN + " where id = " + userId);

                        if (ValidatorUtils.isEmail(email)) {
                            if (getRowCount(adminRes) > 0 || getRowCount(subadminSet) > 0) {
                                saveAdmin(email, password, firstname, lastname, fathername, phone, userId,
                                        modelName);
                            } else {
                                Author author = new Author();
                                author.setLogin(email);
                                author.setPassword(password);
                                author.setName(firstname);
                                author.setSurname(lastname);
                                author.setMiddlename(fathername);
                                author.setPhone(phone);
                                author.setWord(password);
                                saveObjectAndLink(author, userId, modelName);
                            }
                        }
                    } catch (Exception e) {
                        ts.setRollbackOnly();
                        String message = "user: " + userId + " " + StringAdapter.getStackExeption(e);
                        log.warn(message);
                        messageList.add(message);
                    }

                }
            });

        }
    } catch (Throwable th) {
        log.warn("moveUsers " + StringAdapter.getStackExeption(th));
    }
}

From source file:org.apache.camel.processor.aggregate.jdbc.OptimisticLockingJdbcAggregationRepository.java

@Override
public void confirm(CamelContext camelContext, String exchangeId) {
    getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override//from  w  w  w .ja v a 2 s . c  om
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            log.debug(String.format("Confirming exchangeId [%s]", exchangeId));

            getJdbcTemplate().update(
                    String.format("DELETE FROM %1$s WHERE %2$s=?", getRepositoryNameCompleted(), ID_KEY),
                    exchangeId);
        }
    });
}

From source file:com.mothsoft.alexis.engine.textual.ParseResponseMessageListener.java

private void updateDocument(final Long documentId, final ParsedContent parsedContent) {
    logger.info("Beginning to update document: " + documentId);

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from   w  w w  .  ja  v a2  s  .c  o  m

    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus txStatus) {
            try {
                CurrentUserUtil.setSystemUserAuthentication();
                final Document attachedDocument = ParseResponseMessageListener.this.documentDao.get(documentId);
                attachedDocument.setParsedContent(parsedContent);
            } finally {
                CurrentUserUtil.clearAuthentication();
            }
        }

    });

    stopWatch.stop();
    logger.info("Document update for ID: " + documentId + " took: " + stopWatch.toString());
}

From source file:org.geowebcache.diskquota.jdbc.JDBCQuotaStore.java

public void renameLayer(final String oldLayerName, final String newLayerName) throws InterruptedException {
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override//from   w w w . j av  a  2s. c  o m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            String sql = dialect.getRenameLayerStatement(schema, "oldName", "newName");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("oldName", oldLayerName);
            params.put("newName", newLayerName);
            int updated = jt.update(sql, params);
            log.info("Updated " + updated + " tile sets after layer rename");
        }
    });
}

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

public void addMessage(final long ownerID, final MailMessage message, String mailboxName) {
    Mailbox mailbox = getMailbox(ownerID, mailboxName);
    if (mailbox == null) {
        mailbox = createMailbox(ownerID, mailboxName);
    }//from  w  w  w  . j a  v a  2s  . com
    final long mailboxID = mailbox.getMailboxID();
    getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        public void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                MessageDao dao = DaoFactory.getMessageDao();
                dao.addMessage(mailboxID, message);
                eventDispatcher.added(mailboxID);
            } catch (DataAccessException ex) {
                status.setRollbackOnly();
                throw ex;
            }
        }
    });
}

From source file:org.opennms.ng.services.collectd.Collectd.java

/**
 * Schedule existing interfaces for data collection.
 *
 * @throws SQLException if database errors encountered.
 *///from   w w w.  ja v a2s .c om
private void scheduleExistingInterfaces() throws SQLException {

    instrumentation().beginScheduleExistingInterfaces();
    try {
        //TODO - throws NPE.
        m_transTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {

                // Loop through collectors and schedule for each one present
                for (String name : getCollectorNames()) {
                    scheduleInterfacesWithService(name);
                }
            }
        });
    } finally {
        instrumentation().endScheduleExistingInterfaces();
    }
}

From source file:com.dianping.lion.service.impl.ConfigReleaseServiceImpl.java

@SuppressWarnings("unchecked")
@Override// ww  w .j  a  va  2s.c  om
public ConfigRollbackResult rollbackSnapshotSet(ConfigSnapshotSet snapshotSet, String[] keys) {
    ConfigRollbackResult rollbackResult = new ConfigRollbackResult();
    final int projectId = snapshotSet.getProjectId();
    final int envId = snapshotSet.getEnvId();
    try {
        List<ConfigSnapshot> configSnapshots = configReleaseDao.findConfigSnapshots(snapshotSet.getId());
        List<ConfigInstanceSnapshot> configInstSnapshots = configReleaseDao
                .findConfigInstSnapshots(snapshotSet.getId());
        List<Config> currentConfigs = configService.findConfigs(projectId);
        List<ConfigInstance> currentConfigInsts = configService.findInstances(projectId, envId);
        Map<Integer, Date> modifyTimes = configService.findModifyTime(projectId, envId);

        Map<String, ConfigSnapshot> configSnapshotMap = new HashMap<String, ConfigSnapshot>(
                configSnapshots.size());
        for (ConfigSnapshot configSnapshot : configSnapshots) {
            configSnapshotMap.put(configSnapshot.getKey(), configSnapshot);
        }
        Map<Integer, List<ConfigInstanceSnapshot>> configInstSnapshotMap = new HashMap<Integer, List<ConfigInstanceSnapshot>>(
                configSnapshots.size());
        for (ConfigInstanceSnapshot configInstSnapshot : configInstSnapshots) {
            List<ConfigInstanceSnapshot> instList = configInstSnapshotMap.get(configInstSnapshot.getConfigId());
            if (instList == null) {
                instList = new ArrayList<ConfigInstanceSnapshot>();
                configInstSnapshotMap.put(configInstSnapshot.getConfigId(), instList);
            }
            instList.add(configInstSnapshot);
        }
        Set<String> configSnapshotKeys = configSnapshotMap.keySet();

        final Map<String, Config> currentConfigMap = new HashMap<String, Config>(currentConfigs.size());
        for (Config currentConfig : currentConfigs) {
            currentConfigMap.put(currentConfig.getKey(), currentConfig);
        }
        Map<Integer, List<ConfigInstance>> currentConfigInstMap = new HashMap<Integer, List<ConfigInstance>>(
                currentConfigInsts.size());
        for (ConfigInstance currentConfigInst : currentConfigInsts) {
            List<ConfigInstance> instList = currentConfigInstMap.get(currentConfigInst.getConfigId());
            if (instList == null) {
                instList = new ArrayList<ConfigInstance>();
                currentConfigInstMap.put(currentConfigInst.getConfigId(), instList);
            }
            instList.add(currentConfigInst);
        }
        Set<String> currentConfigKeys = currentConfigMap.keySet();

        Set<String> notRemovedKeys = new HashSet<String>();
        Set<String> selectedKeys = null;
        if (keys != null) {
            selectedKeys = new HashSet<String>();
            for (String key : keys) {
                selectedKeys.add(key);
            }
        }
        //1. ????
        /* Notice:
         * ???????????
         * 
         */
        Collection<String> configNeedRemoveKeys = CollectionUtils.subtract(currentConfigKeys,
                configSnapshotKeys);
        notRemovedKeys.addAll(configNeedRemoveKeys);
        //      for (final String configNeedRemoveKey : configNeedRemoveKeys) {
        //         this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        //            @Override
        //            protected void doInTransactionWithoutResult(TransactionStatus status) {
        //               Config configNeedRemove = currentConfigMap.get(configNeedRemoveKey);
        //               configService.deleteInstance(configNeedRemove.getId(), envId);
        //            }
        //         });
        //      }

        //2. ??????
        Collection<String> intersectionKeys = CollectionUtils.intersection(currentConfigKeys,
                configSnapshotKeys);
        for (String intersectionKey : intersectionKeys) {
            if (selectedKeys != null && !selectedKeys.contains(intersectionKey))
                continue;
            ConfigSnapshot configSnapshot = configSnapshotMap.get(intersectionKey);
            final Config currentConfig = currentConfigMap.get(intersectionKey);
            final List<ConfigInstanceSnapshot> snapshotInstList = configInstSnapshotMap
                    .get(configSnapshot.getConfigId());
            final List<ConfigInstance> currentInstList = currentConfigInstMap.get(currentConfig.getId());
            boolean snapshotNoInst = snapshotInstList == null || snapshotInstList.isEmpty();
            boolean currentNoInst = currentInstList == null || currentInstList.isEmpty();
            if (snapshotNoInst == true && currentNoInst == false) {
                notRemovedKeys.add(intersectionKey);
            } else if (snapshotNoInst == false && currentNoInst == true) {
                //??configinstanceregister server
                this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        restoreConfigInstSnapshots(currentConfig.getId(), envId, snapshotInstList);
                    }
                });
            } else if (snapshotNoInst == false && currentNoInst == false) {
                Date modifyTime = modifyTimes.get(currentConfig.getId());
                Date recordModifyTime = configSnapshot.getValueModifyTime();
                if (modifyTime == null || recordModifyTime == null || !modifyTime.equals(recordModifyTime)) {
                    boolean onlyOneSnapshotInst = snapshotInstList.size() == 1;
                    boolean onlyOneCurrentInst = currentInstList.size() == 1;
                    if (onlyOneSnapshotInst && onlyOneCurrentInst) {
                        ConfigInstanceSnapshot snapshotInst = snapshotInstList.get(0);
                        ConfigInstance currentInst = currentInstList.get(0);
                        if (snapshotInst.getContext().equals(currentInst.getContext())
                                && snapshotInst.getValue().equals(currentInst.getValue())) {
                            continue;
                        }
                    }
                    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                        @Override
                        protected void doInTransactionWithoutResult(TransactionStatus status) {
                            configDao.deleteInstances(currentConfig.getId(), envId);
                            restoreConfigInstSnapshots(currentConfig.getId(), envId, snapshotInstList);
                        }
                    });
                }
            }
        }

        //3. ???
        Collection<String> configNeedAddKeys = CollectionUtils.subtract(configSnapshotKeys, currentConfigKeys);
        for (final String configNeedAddKey : configNeedAddKeys) {
            if (selectedKeys != null && !selectedKeys.contains(configNeedAddKey))
                continue;
            final ConfigSnapshot configSnapshot = configSnapshotMap.get(configNeedAddKey);
            final List<ConfigInstanceSnapshot> snapshotInstList = configInstSnapshotMap
                    .get(configSnapshot.getConfigId());
            if (snapshotInstList != null && !snapshotInstList.isEmpty()) {
                this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        int configId = configService.createConfig(configSnapshot.toConfig());
                        restoreConfigInstSnapshots(configId, envId, snapshotInstList);
                    }
                });
            }
        }
        rollbackResult.setNotRemovedKeys(notRemovedKeys);
        return rollbackResult;
    } catch (RuntimeException e) {
        Project project = projectService.getProject(projectId);
        logger.error("rollback configs failed with[project=" + project.getName() + ", task="
                + snapshotSet.getTask() + "].", e);
        throw e;
    }
}

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

/**
 * Tests the use of nested transactions.
 *//* ww  w  .java 2s.co m*/
@Test
public void testNestedTransactions() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    final TransactionTemplate tt = hbc.getTransactionTemplate();

    Serializable empId = tt.execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() {

                @Override
                public Serializable doInTransaction(TransactionStatus nestedStatus) {
                    DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
                    Employee emp = hbc.findFirstByCriteria(empCrit, null, Employee.class);
                    emp.setFirstName("Committed");
                    return emp.getId();
                }
            });
            // asserts that UOW is still active after the end of the nested transaction.
            assertTrue("UOW should still be active since outer TX is ongoing.", hbc.isUnitOfWorkActive());
            // forces rollback of outer TX.
            status.setRollbackOnly();
            return id;
        }
    });
    DetachedCriteria empById = DetachedCriteria.forClass(Employee.class);
    empById.add(Restrictions.eq(IEntity.ID, empId));
    Employee emp = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    assertTrue("Inner transaction should have been committed", "Committed".equals(emp.getFirstName()));

    Serializable emp2Id = tt.execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() {

                @Override
                public Serializable doInTransaction(TransactionStatus nestedStatus) {
                    DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
                    Employee emp2 = hbc.findFirstByCriteria(empCrit, null, Employee.class);
                    emp2.setFirstName("Rollbacked");
                    return emp2.getId();
                }
            });
            // forces rollback of outer TX.
            status.setRollbackOnly();
            return id;
        }
    });
    DetachedCriteria emp2ById = DetachedCriteria.forClass(Employee.class);
    emp2ById.add(Restrictions.eq(IEntity.ID, emp2Id));
    Employee emp2 = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    assertFalse("Inner transaction should have been rollbacked", "Rollbacked".equals(emp2.getFirstName()));

    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            City newCity = hbc.getEntityFactory().createEntityInstance(City.class);
            newCity.setName("Test City");

            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            String testZip = nestedTT.execute(new TransactionCallback<String>() {

                @Override
                public String doInTransaction(TransactionStatus nestedStatus) {
                    return "12345";
                }
            });
            newCity.setZip(testZip);
            hbc.registerForUpdate(newCity);
        }
    });

    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            final City randomCity = hbc.findFirstByCriteria(DetachedCriteria.forClass(City.class),
                    EMergeMode.MERGE_KEEP, City.class);
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            nestedTT.execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus nestedStatus) {
                    DetachedCriteria cityById = DetachedCriteria.forClass(City.class);
                    cityById.add(Restrictions.eq(IEntity.ID, randomCity.getId()));
                    City innerRandomCity = (City) cityById.getExecutableCriteria(hbc.getHibernateSession())
                            .uniqueResult();
                    // If we reach this point without exception, there is no mix between the inner TX and the outer UOW.
                    // See bug #1118
                }
            });
        }
    });
}

From source file:com.dianping.lion.service.impl.ConfigServiceImpl.java

@Override
public ConfigDeleteResult deleteConfig(int configId) {
    final ConfigDeleteResult result = new ConfigDeleteResult();
    final Config config = getConfig(configId);
    if (config != null) {
        result.setConfig(config);//from w  ww  . j a  v  a  2 s  .  c  o m
        List<Environment> environments = environmentService.findAll();
        for (final Environment environment : environments) {
            try {
                this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        deleteInstances(config, environment.getId());
                    }
                });
            } catch (RuntimeException e) {
                logger.error("Delete config[" + config.getKey() + "] in environment[" + environment.getLabel()
                        + "] failed.", e);
                result.addFailedEnv(environment.getLabel());
                if (e instanceof ReferencedConfigForbidDeleteException) {
                    result.setHasReference(true);
                }
            }
        }
        if (result.isSucceed()) {
            configDao.deleteConfig(configId);
            cacheClient.remove(ServiceConstants.CACHE_CONFIG_PREFIX + configId);
            cacheClient.remove(ServiceConstants.CACHE_CONFIG_PREFIX + config.getKey());
        }
    }
    return result;
}

From source file:nl.clockwork.mule.ebms.dao.postgresql.EbMSDAOImpl.java

@Override
public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status) throws DAOException {
    try {/*from w  ww.  ja  v  a 2  s  .c  o m*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    Date timestamp = new Date();
                    Long key = (Long) jdbcTemplate.query(new EbMSMessagePreparedStatement(timestamp,
                            message.getMessageHeader().getCPAId(),
                            message.getMessageHeader().getConversationId(),
                            message.getMessageOrder() == null ? null
                                    : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                            message.getMessageHeader().getMessageData().getMessageId(),
                            message.getMessageHeader().getMessageData().getRefToMessageId(),
                            message.getMessageHeader().getFrom().getRole(),
                            message.getMessageHeader().getTo().getRole(),
                            message.getMessageHeader().getService().getType(),
                            message.getMessageHeader().getService().getValue(),
                            message.getMessageHeader().getAction(), message.getOriginal(),
                            XMLMessageBuilder.getInstance(SignatureType.class)
                                    .handle(new ObjectFactory().createSignature(message.getSignature())),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(message.getMessageHeader()),
                            XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                            XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                            XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                            XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()),
                            status), new IdExtractor());

                    for (DataSource attachment : message.getAttachments()) {
                        simpleJdbcTemplate.update(
                                "insert into ebms_attachment (" + "ebms_message_id," + "name," + "content_type,"
                                        + "content" + ") values (?,?,?,?)",
                                key,
                                attachment.getName() == null ? Constants.DEFAULT_FILENAME
                                        : attachment.getName(),
                                attachment.getContentType().split(";")[0].trim(),
                                IOUtils.toByteArray(attachment.getInputStream()));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        });
    } catch (Exception e) {
        throw new DAOException(e);
    }
}