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

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

Introduction

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

Prototype

public DataSourceTransactionManager(DataSource dataSource) 

Source Link

Document

Create a new DataSourceTransactionManager instance.

Usage

From source file:dk.nsi.haiba.lprimporter.config.LPRConfiguration.java

@Bean
public PlatformTransactionManager minipasTransactionManagerMinipas(
        @Qualifier("lprDataSourceMinipas") DataSource ds) {
    return new DataSourceTransactionManager(ds);
}

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

@Override
public void markImageAsProcessed(final UUID imageId) throws DataAccessException {

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Marking an image as processed.");

    try {//from   ww  w. j a  v a 2s.  c  o  m
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            getJdbcTemplate().update("UPDATE url_based_resource " + "SET processed = true " + "WHERE uuid = ?",
                    new Object[] { imageId.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException(
                    "Error executing SQL '" + SQL_DELETE_IMAGE + "' with parameter: " + imageId, e);
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }
    } catch (TransactionException e) {
        throw new DataAccessException("Error while attempting to rollback the transaction.", e);
    }
}

From source file:com.alibaba.cobar.client.transaction.MultipleDataSourcesTransactionManager.java

protected PlatformTransactionManager createTransactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

From source file:cn.cuizuoli.gotour.config.DataSourceConfig.java

@Bean
public PlatformTransactionManager txManager() {
    return new DataSourceTransactionManager(dataSource());
}

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

@Override
public List<Integer> insertSurveys(final String username, final String client, final String campaignUrn,
        final List<SurveyResponse> surveyUploadList, final Map<UUID, Image> bufferedImageMap,
        final Map<String, Video> videoContentsMap, final Map<String, Audio> audioContentsMap)
        throws DataAccessException {

    List<Integer> duplicateIndexList = new ArrayList<Integer>();
    int numberOfSurveys = surveyUploadList.size();

    // The following variables are used in logging messages when errors occur
    SurveyResponse currentSurveyResponse = null;
    PromptResponse currentPromptResponse = null;
    String currentSql = null;/*  ww w  .  j  av  a  2s  .  co m*/

    List<File> fileList = new LinkedList<File>();

    // Wrap all of the inserts in a transaction 
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("survey upload");
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
    TransactionStatus status = transactionManager.getTransaction(def); // begin transaction

    // Use a savepoint to handle nested rollbacks if duplicates are found
    Object savepoint = status.createSavepoint();

    try { // handle TransactionExceptions

        for (int surveyIndex = 0; surveyIndex < numberOfSurveys; surveyIndex++) {

            try { // handle DataAccessExceptions

                final SurveyResponse surveyUpload = surveyUploadList.get(surveyIndex);
                currentSurveyResponse = surveyUpload;
                currentSql = SQL_INSERT_SURVEY_RESPONSE;

                KeyHolder idKeyHolder = new GeneratedKeyHolder();

                // First, insert the survey
                getJdbcTemplate().update(new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(SQL_INSERT_SURVEY_RESPONSE,
                                Statement.RETURN_GENERATED_KEYS);

                        String locationString = null;
                        Location location = surveyUpload.getLocation();
                        if (location != null) {
                            try {
                                locationString = location.toJson(false, LocationColumnKey.ALL_COLUMNS)
                                        .toString();
                            } catch (JSONException e) {
                                throw new SQLException(e);
                            } catch (DomainException e) {
                                throw new SQLException(e);
                            }
                        }

                        ps.setString(1, surveyUpload.getSurveyResponseId().toString());
                        ps.setString(2, username);
                        ps.setString(3, campaignUrn);
                        ps.setLong(4, surveyUpload.getTime());
                        ps.setString(5, surveyUpload.getTimezone().getID());
                        ps.setString(6, surveyUpload.getLocationStatus().toString());
                        ps.setString(7, locationString);
                        ps.setString(8, surveyUpload.getSurvey().getId());
                        try {
                            ps.setString(9,
                                    surveyUpload
                                            .toJson(false, false, false, false, true, true, true, true, true,
                                                    false, false, true, true, true, true, false, false)
                                            .toString());
                        } catch (JSONException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        } catch (DomainException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        }
                        ps.setString(10, client);
                        ps.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
                        try {
                            ps.setString(12, surveyUpload.getLaunchContext().toJson(true).toString());
                        } catch (JSONException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        }
                        try {
                            ps.setString(13, PreferenceCache.instance()
                                    .lookup(PreferenceCache.KEY_DEFAULT_SURVEY_RESPONSE_SHARING_STATE));
                        } catch (CacheMissException e) {
                            throw new SQLException("Error reading from the cache.", e);
                        }
                        return ps;
                    }
                }, idKeyHolder);

                savepoint = status.createSavepoint();

                final Number surveyResponseId = idKeyHolder.getKey(); // the primary key on the survey_response table for the 
                                                                      // just-inserted survey
                currentSql = SQL_INSERT_PROMPT_RESPONSE;

                // Now insert each prompt response from the survey
                Collection<Response> promptUploadList = surveyUpload.getResponses().values();

                createPromptResponse(username, client, surveyResponseId, fileList, promptUploadList, null,
                        bufferedImageMap, videoContentsMap, audioContentsMap, transactionManager, status);

            } catch (DataIntegrityViolationException dive) { // a unique index exists only on the survey_response table

                if (isDuplicate(dive)) {

                    LOGGER.debug("Found a duplicate survey upload message for user " + username);

                    duplicateIndexList.add(surveyIndex);
                    status.rollbackToSavepoint(savepoint);

                } else {

                    // Some other integrity violation occurred - bad!! All 
                    // of the data to be inserted must be validated before 
                    // this query runs so there is either missing validation 
                    // or somehow an auto_incremented key has been duplicated.

                    LOGGER.error("Caught DataAccessException", dive);
                    logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username,
                            campaignUrn);
                    for (File f : fileList) {
                        f.delete();
                    }
                    rollback(transactionManager, status);
                    throw new DataAccessException(dive);
                }

            } catch (org.springframework.dao.DataAccessException dae) {

                // Some other database problem happened that prevented
                // the SQL from completing normally.

                LOGGER.error("caught DataAccessException", dae);
                logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username,
                        campaignUrn);
                for (File f : fileList) {
                    f.delete();
                }
                rollback(transactionManager, status);
                throw new DataAccessException(dae);
            }

        }

        // Finally, commit the transaction
        transactionManager.commit(status);
        LOGGER.info("Completed survey message persistence");
    }

    catch (TransactionException te) {

        LOGGER.error("failed to commit survey upload transaction, attempting to rollback", te);
        rollback(transactionManager, status);
        for (File f : fileList) {
            f.delete();
        }
        logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username, campaignUrn);
        throw new DataAccessException(te);
    }

    LOGGER.info(
            "Finished inserting survey responses and any associated images into the database and the filesystem.");
    return duplicateIndexList;
}

From source file:com.osrdata.etltoolbox.fileloader.FileSpecification.java

/**
 * Loads specified file into target targetTable. This operation transactional and will rollback any database operations if
 * there are any errors processing the data.
 *
 * @param sourceFile source file to be loaded
 * @throws IOException on error reading file
 * @throws ParseException on error parsing fields from file
 *///ww  w  .  j  av  a2s  . com
public void load(final File sourceFile) throws IOException, ParseException {
    this.sourceFile = sourceFile;
    Matcher matcher = sourcePattern.matcher(sourceFile.getName());
    etlDate = new Date();
    etlType = "I";
    if (matcher.find()) {
        if (dateGroup != null && dateGroup.intValue() <= matcher.groupCount()) {
            etlDate = new SimpleDateFormat(dateFormat).parse(matcher.group(dateGroup.intValue()));
        }
        if (typeGroup != null && typeGroup.intValue() <= matcher.groupCount()) {
            etlType = matcher.group(typeGroup.intValue()).substring(0, 1).toUpperCase();
        }
    }
    recordId = new BigDecimal(new SimpleDateFormat("yyyyMMdd").format(etlDate) + "0000000000");

    DataSourceTransactionManager txManager = new DataSourceTransactionManager(targetDs);
    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
    targetTemplate = new JdbcTemplate(targetDs);

    log.info("Processing source file " + sourceFile.getName());
    numRecords = 0l;
    try {
        txTemplate.execute(new TransactionCallbackWithoutResult() {
            public void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    boolean loadFlag = false;
                    Integer fileId = selectAuditFile();
                    if (fileId != null && replaceExisting) {
                        deleteExisting(fileId);
                        updateAuditFile(fileId);
                        loadFlag = true;
                    } else if (fileId == null) {
                        fileId = insertAuditFile();
                        loadFlag = true;
                    }

                    if (loadFlag) {
                        CSVReader reader = new CSVReader(new FileReader(sourceFile), parserSeparator,
                                parserQuotechar, parserEscape, parserLine, parserStrictQuotes,
                                parserIgnoreLeadingWhiteSpace);
                        String[] values;
                        startTime = System.currentTimeMillis();
                        while ((values = reader.readNext()) != null) {
                            add(values, fileId);
                            numRecords++;
                            if (trace > 0l && numRecords % trace == 0l) {
                                log.info("\tProcessed " + getCount(numRecords) + " records in " + getDuration()
                                        + " (" + getRecordsPerSecond() + " rps)");
                            }
                        }
                        reader.close();
                        insertTarget();
                    } else {
                        log.info("\tSkipping previously loaded file" + sourceFile.getName());
                    }
                } catch (RuntimeException e) {
                    throw e;
                } catch (Throwable e) {
                    log.error("\tError at record " + numRecords + " in " + sourceFile.getName());
                    throw new RuntimeException(e);
                }
            }
        });
    } catch (RuntimeException e) {
        log.error("\tAn exception occurred while processing record " + numRecords + " in "
                + sourceFile.getName() + ". All transactions for this file have been rolled back.", e);
    }
    log.info("\tCompleted processing of " + getCount(numRecords) + " records in " + getDuration() + " ("
            + getRecordsPerSecond() + " rps)");
}

From source file:org.joyrest.oauth2.initializer.OAuth2Initializer.java

private DefaultTokenServices txProxiedTokenServices(DefaultTokenServices tokenServices, DataSource dataSource) {
    AnnotationTransactionAttributeSource attrSource = new AnnotationTransactionAttributeSource();
    DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource);
    TransactionInterceptor txInterceptor = transactionInterceptor(attrSource, txManager);
    BeanFactoryTransactionAttributeSourceAdvisor txAdvisor = transactionAdvisor(attrSource, txInterceptor);
    ClassLoader classLoader = ClassUtils.getDefaultClassLoader();

    ProxyFactory proxyFactory = new ProxyFactory(tokenServices);
    proxyFactory.addAdvice(txInterceptor);
    proxyFactory.addAdvisor(txAdvisor);// w  ww.j a  v  a2 s. com
    proxyFactory.setInterfaces(ClassUtils
            .getAllInterfacesForClass(new SingletonTargetSource(tokenServices).getTargetClass(), classLoader));

    return (DefaultTokenServices) proxyFactory.getProxy(classLoader);
}

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

@Override
public void deleteImage(UUID imageId) throws DataAccessException {
    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Deleting an image.");

    try {//from  ww  w.  j  a  va 2s. c  o m
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        URL imageUrl = getImageUrl(imageId);

        try {
            getJdbcTemplate().update(SQL_DELETE_IMAGE, new Object[] { imageId.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException(
                    "Error executing SQL '" + SQL_DELETE_IMAGE + "' with parameter: " + imageId, e);
        }

        if (imageUrl != null) {
            deleteImageDiskOnly(imageUrl);
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }
    } catch (TransactionException e) {
        throw new DataAccessException("Error while attempting to rollback the transaction.", e);
    }
}

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

@Override
public void createAudit(final RequestServlet.RequestType requestType, final String uri, final String client,
        final String requestId, final String deviceId, final Map<String, String[]> parameters,
        final Map<String, String[]> extras, final String response, final long receivedMillis,
        final long respondMillis) throws DataAccessException {

    if (requestType == null) {
        throw new IllegalArgumentException("The request type is required and cannot be null.");
    } else if (uri == null) {
        throw new IllegalArgumentException("The request URI is required and cannot be null.");
    } else if (response == null) {
        throw new IllegalArgumentException("The response is required and cannot be null.");
    }/*from www . j  a  va  2s.com*/

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Creating a request audit.");

    try {
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Create a key holder that will be responsible for referencing 
        // which row was just inserted.
        KeyHolder keyHolder = new GeneratedKeyHolder();

        // Insert the audit entry.
        try {
            getJdbcTemplate().update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(SQL_INSERT_AUDIT, new String[] { "id" });

                    ps.setString(1, requestType.name().toLowerCase());
                    ps.setString(2, uri);
                    ps.setString(3, client);
                    ps.setString(4, requestId);
                    ps.setString(5, deviceId);
                    ps.setString(6, response);
                    ps.setLong(7, receivedMillis);
                    ps.setLong(8, respondMillis);

                    return ps;
                }
            }, keyHolder);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_AUDIT
                    + "' with parameters: " + requestType.name().toLowerCase() + ", " + uri + ", " + client
                    + ", " + deviceId + ", " + response + ", " + receivedMillis + ", " + respondMillis, e);
        }

        // Add all of the parameters.
        if (parameters != null) {
            for (String key : parameters.keySet()) {
                for (String value : parameters.get(key)) {
                    try {
                        getJdbcTemplate().update(SQL_INSERT_PARAMETER, keyHolder.getKey().longValue(), key,
                                value);
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException(
                                "Error while executing SQL '" + SQL_INSERT_PARAMETER + "' with parameters: "
                                        + keyHolder.getKey().longValue() + ", " + key + ", " + value,
                                e);
                    }
                }
            }
        }

        // Add all of the extras.
        if (extras != null) {
            for (String key : extras.keySet()) {
                for (String value : extras.get(key)) {
                    try {
                        getJdbcTemplate().update(SQL_INSERT_EXTRA, keyHolder.getKey().longValue(), key, value);
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException(
                                "Error while executing SQL '" + SQL_INSERT_EXTRA + "' with parameters: "
                                        + keyHolder.getKey().longValue() + ", " + key + ", " + value,
                                e);
                    }
                }
            }
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }
    } catch (TransactionException e) {
        throw new DataAccessException("Error while attempting to rollback the transaction.", e);
    }
}