Example usage for org.springframework.jdbc.datasource DataSourceTransactionManager rollback

List of usage examples for org.springframework.jdbc.datasource DataSourceTransactionManager rollback

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceTransactionManager rollback.

Prototype

@Override
public final void rollback(TransactionStatus status) throws TransactionException 

Source Link

Document

This implementation of rollback handles participating in existing transactions.

Usage

From source file:cn.uncode.dal.internal.shards.transaction.MultiDataSourcesTransactionManager.java

@Override
public void rollback(TransactionStatus status) throws TransactionException {

    Throwable ex = null;//from  www .j a va  2s  . c o  m

    //Cannot deactivate transaction synchronization - not active
    //      Collections.reverse(dataSources);

    for (int i = dataSources.size() - 1; i >= 0; i--) {
        DataSource dataSource = dataSources.get(i);
        try {
            log.debug("Rolling back JDBC transaction");

            rollbackCount.addAndGet(1);

            DataSourceTransactionManager txManager = this.transactionManagers.get(dataSource);
            TransactionStatus currentStatus = ((MultiDataSourcesTransactionStatus) status).get(dataSource);

            txManager.rollback(currentStatus);

            log.info("Roll back JDBC transaction success");
        } catch (Throwable e) {
            log.info("Could not roll back JDBC transaction", e);
            ex = e;
        } finally {
            rollbackCount.addAndGet(-1);
        }
    }

    if (ex != null) {
        throw new RuntimeException(ex);
    }

}

From source file:org.tec.webapp.jdbc.entity.TestUserRole.java

/**
 * create seed user/*from   w  w  w.  j  a  v a2  s .  c  o m*/
 * @return the seed user
 */
protected UserRoleBean testUserRole() {
    DataSourceTransactionManager tmgr = (DataSourceTransactionManager) mAppContext
            .getBean("transactionManager");

    TransactionStatus tranStat = tmgr.getTransaction(new DefaultTransactionDefinition());

    try {
        UserBean user = new User();

        user.setUserName("junit");
        user.setEmail("junit@test.null");

        Long userId = mUserDba.insert(user);
        Assert.assertTrue("id is foobared", userId > 0);

        user.setUserId(userId.intValue());

        UserRoleBean roleBean = new UserRole();

        roleBean.setUser(user);

        roleBean.setRole(RoleType.ROLE_GUEST);

        Long id = mUserRoleDba.insert(roleBean);

        roleBean.setUserRoleId(id.intValue());

        List<UserRoleBean> l = mUserRoleDba.getRoles(new Long(user.getUserId()));

        Assert.assertTrue("should be at least 1 role", l.size() > 0);

        tmgr.commit(tranStat);

        return roleBean;
    } catch (Throwable t) {
        tmgr.rollback(tranStat);
        throw new RuntimeException("failed to create user role", t);
    }
}

From source file:com.foilen.smalltools.upgrader.tasks.AbstractFlywayMigrateOffUpgradeTask.java

@Override
public void execute() {
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(
            jdbcTemplate.getDataSource());

    // Check if the schema_version table exists
    List<String> tableNames = mysqlTablesFindAll();
    List<String> executed;
    if (tableNames.contains("schema_version")) {
        executed = jdbcTemplate.queryForList("SELECT script FROM schema_version WHERE success = 1",
                String.class);
        jdbcTemplate.update("DELETE FROM schema_version WHERE success = 0");
    } else {/*from   w w  w .j  a  v  a  2 s  .co m*/
        executed = new ArrayList<>();
        logger.info("Flyway table does not exists. Creating it");
        updateFromResource("flyway-schema_version.sql", AbstractFlywayMigrateOffUpgradeTask.class);
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    AntPathMatcher pathMatcher = new AntPathMatcher();
    resolver.setPathMatcher(pathMatcher);
    Resource[] resources;
    try {
        resources = resolver.getResources("classpath:db/migration/*.sql");
    } catch (IOException e) {
        throw new SmallToolsException("Problem getting the sql files", e);
    }

    int rank = executed.size() + 1;
    List<String> scriptNames = Arrays.asList(resources).stream() //
            .map(Resource::getFilename) //
            .sorted() //
            .collect(Collectors.toList());
    for (String scriptName : scriptNames) {
        boolean needRetry = true;
        if (executed.contains(scriptName)) {
            logger.info("[{}] Already executed. Skip", scriptName);
        } else {
            logger.info("[{}] To execute", scriptName);
            for (int retryCount = 0; needRetry; ++retryCount) {
                needRetry = false;
                TransactionStatus transactionStatus = transactionManager
                        .getTransaction(new DefaultTransactionDefinition());
                try {
                    // Do the update
                    updateFromResource("/db/migration/" + scriptName);

                    // Save in schema_version
                    jdbcTemplate.update("INSERT INTO schema_version " //
                            + "(version_rank, installed_rank, version, description, type, script, installed_by, execution_time, success) " //
                            + "VALUES (?,?,?,'','SQL',?,'upgrader',1, 1)", //
                            rank, rank, //
                            scriptName.substring(0, Math.min(50, scriptName.length())), //
                            scriptName //
                    );
                    ++rank;
                    transactionManager.commit(transactionStatus);
                } catch (Exception e) {
                    logger.warn("[{}] Problem executing script. Will purge the connections and retry",
                            scriptName);
                    transactionManager.rollback(transactionStatus);
                    needRetry = true;
                    purgeConnections();
                    if (retryCount > 5) {
                        throw new SmallToolsException("Problem executing script: " + scriptName, e);
                    }
                }

            }
        }
    }

    if (deleteSchemaTable) {
        logger.info("Deleting the Flyway schema_version table");
        jdbcTemplate.update("DROP TABLE schema_version");
    }

}

From source file:org.ohmage.query.impl.SurveyUploadQuery.java

/**
 * Creates the prompt response entry in the corresponding table and saves
 * any attached files, images, videos, etc..
 * /*www  . ja  v  a2  s  .c  o  m*/
 * @param username
 *        The username of the user saving this prompt response.
 * 
 * @param client
 *        The name of the device used to generate the response.
 * 
 * @param surveyResponseId
 *        The unique identifier for this survey response.
 * 
 * @param fileList
 *        The list of files saved to the disk, which should be a reference
 *        to a list that will be populated by this function.
 * 
 * @param promptUploadList
 *        The collection of prompt responses to store.
 * 
 * @param repeatableSetIteration
 *        If these prompt responses were part of a repeatable set, this is
 *        the iteration of that repeatable set; otherwise, null.
 * 
 * @param bufferedImageMap
 *        The map of image IDs to their contents.
 * 
 * @param videoContentsMap
 *        The map of video IDs to their contents.
 * 
 * @param transactionManager
 *        The manager for this transaction.
 * 
 * @param status
 *        The status of this transaction.
 * 
 * @throws DataAccessException
 *         There was an error saving the information.
 */
private void createPromptResponse(final String username, final String client, final Number surveyResponseId,
        final List<File> fileList, final Collection<Response> promptUploadList,
        final Integer repeatableSetIteration, final Map<UUID, Image> bufferedImageMap,
        final Map<String, Video> videoContentsMap, final Map<String, Audio> audioContentsMap,
        final DataSourceTransactionManager transactionManager, final TransactionStatus status)
        throws DataAccessException {

    for (Response response : promptUploadList) {
        if (response instanceof RepeatableSetResponse) {
            Map<Integer, Map<Integer, Response>> iterationToResponse = ((RepeatableSetResponse) response)
                    .getResponseGroups();

            for (Integer iteration : iterationToResponse.keySet()) {
                createPromptResponse(username, client, surveyResponseId, fileList,
                        iterationToResponse.get(iteration).values(), iteration, bufferedImageMap,
                        videoContentsMap, audioContentsMap, transactionManager, status);
            }
            continue;
        }
        final PromptResponse promptResponse = (PromptResponse) response;

        getJdbcTemplate().update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(SQL_INSERT_PROMPT_RESPONSE);
                ps.setLong(1, surveyResponseId.longValue());

                RepeatableSet parent = promptResponse.getPrompt().getParent();
                if (parent == null) {
                    ps.setNull(2, java.sql.Types.NULL);
                    ps.setNull(3, java.sql.Types.NULL);
                } else {
                    ps.setString(2, parent.getId());
                    ps.setInt(3, repeatableSetIteration);
                }
                ps.setString(4, promptResponse.getPrompt().getType().toString());
                ps.setString(5, promptResponse.getPrompt().getId());

                Object response = promptResponse.getResponse();
                if (response instanceof DateTime) {
                    ps.setString(6, DateTimeUtils.getW3cIso8601DateString((DateTime) response, true));
                } else if ((promptResponse instanceof MultiChoiceCustomPromptResponse)
                        && (response instanceof Collection)) {
                    JSONArray json = new JSONArray();

                    for (Object currResponse : (Collection<?>) response) {
                        json.put(currResponse);
                    }

                    ps.setString(6, json.toString());
                } else {
                    ps.setString(6, response.toString());
                }

                return ps;
            }
        });

        if (promptResponse instanceof PhotoPromptResponse) {
            // Grab the associated image and save it
            String imageId = promptResponse.getResponse().toString();

            // If it wasn't skipped and it was displayed, save the
            // associated images.
            if (!JsonInputKeys.PROMPT_SKIPPED.equals(imageId)
                    && !JsonInputKeys.PROMPT_NOT_DISPLAYED.equals(imageId)
                    && !JsonInputKeys.IMAGE_NOT_UPLOADED.equals(imageId)) {

                // Get the directory to save the image and save it.
                File originalFile;
                try {
                    originalFile = bufferedImageMap.get(UUID.fromString(imageId)).saveImage(getDirectory());
                } catch (DomainException e) {
                    rollback(transactionManager, status);
                    throw new DataAccessException("Error saving the images.", e);
                }

                // Get the image's URL.
                String url = "file://" + originalFile.getAbsolutePath();
                // Insert the image URL into the database.
                try {
                    getJdbcTemplate().update(SQL_INSERT_IMAGE, new Object[] { username, client, imageId, url });
                } catch (org.springframework.dao.DataAccessException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_INSERT_IMAGE
                            + "' with parameters: " + username + ", " + client + ", " + imageId + ", " + url,
                            e);
                }
            }
        }
        // Save the video.
        else if (promptResponse instanceof VideoPromptResponse) {
            // Make sure the response contains an actual video response.
            Object responseValue = promptResponse.getResponse();
            if (!((responseValue instanceof NoResponse) || (responseValue instanceof NoResponseMedia))) {

                // Attempt to write it to the file system.
                try {
                    // Get the current video directory.
                    File currVideoDirectory = VideoDirectoryCache.getDirectory();

                    // Get the video ID.
                    String responseValueString = responseValue.toString();

                    // Get the video object.
                    Video video = videoContentsMap.get(responseValueString);

                    // Get the file.
                    File videoFile = new File(currVideoDirectory.getAbsolutePath() + "/" + responseValueString
                            + "." + video.getType());

                    // Get the video contents.
                    InputStream content = video.getContentStream();
                    if (content == null) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("The video contents did not exist in the map.");
                    }

                    // Write the video contents to disk.
                    FileOutputStream fos = new FileOutputStream(videoFile);

                    // Write the content to the output stream.
                    int bytesRead;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = content.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                    fos.close();

                    // Store the file reference in the video list.
                    fileList.add(videoFile);

                    // Get the video's URL.
                    String url = "file://" + videoFile.getAbsolutePath();

                    // Insert the video URL into the database.
                    try {
                        getJdbcTemplate().update(SQL_INSERT_IMAGE,
                                new Object[] { username, client, responseValueString, url });
                    } catch (org.springframework.dao.DataAccessException e) {
                        videoFile.delete();
                        transactionManager.rollback(status);
                        throw new DataAccessException(
                                "Error executing SQL '" + SQL_INSERT_IMAGE + "' with parameters: " + username
                                        + ", " + client + ", " + responseValueString + ", " + url,
                                e);
                    }
                }
                // If it fails, roll back the transaction.
                catch (DomainException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not get the video directory.", e);
                } catch (IOException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not write the file.", e);
                }
            }
        } else if (promptResponse instanceof AudioPromptResponse) {
            // Make sure the response contains an actual audio response.
            Object responseValue = promptResponse.getResponse();
            if (!((responseValue instanceof NoResponse) || (responseValue instanceof NoResponseMedia))) {

                // Attempt to write it to the file system.
                try {
                    // Get the current audio directory.
                    File currAudioDirectory = AudioDirectoryCache.getDirectory();

                    // Get the audio ID.
                    String responseValueString = responseValue.toString();

                    // Get the audio object.
                    Audio audio = audioContentsMap.get(responseValueString);

                    // Get the file.
                    File audioFile = new File(currAudioDirectory.getAbsolutePath() + "/" + responseValueString
                            + "." + audio.getType());

                    // Get the video contents.
                    InputStream content = audio.getContentStream();
                    if (content == null) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("The audio contents did not exist in the map.");
                    }

                    // Write the video contents to disk.
                    FileOutputStream fos = new FileOutputStream(audioFile);

                    // Write the content to the output stream.
                    int bytesRead;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = content.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                    fos.close();

                    // Store the file reference in the video list.
                    fileList.add(audioFile);

                    // Get the video's URL.
                    String url = "file://" + audioFile.getAbsolutePath();

                    // Insert the video URL into the database.
                    try {
                        getJdbcTemplate().update(SQL_INSERT_IMAGE,
                                new Object[] { username, client, responseValueString, url });
                    } catch (org.springframework.dao.DataAccessException e) {
                        audioFile.delete();
                        transactionManager.rollback(status);
                        throw new DataAccessException(
                                "Error executing SQL '" + SQL_INSERT_IMAGE + "' with parameters: " + username
                                        + ", " + client + ", " + responseValueString + ", " + url,
                                e);
                    }
                }
                // If it fails, roll back the transaction.
                catch (DomainException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not get the video directory.", e);
                } catch (IOException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not write the file.", e);
                }
            }
        }
    }
}