Example usage for org.springframework.transaction.support DefaultTransactionDefinition setReadOnly

List of usage examples for org.springframework.transaction.support DefaultTransactionDefinition setReadOnly

Introduction

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

Prototype

public final void setReadOnly(boolean readOnly) 

Source Link

Document

Set whether to optimize as read-only transaction.

Usage

From source file:org.opendatakit.persistence.engine.pgres.DatastoreImpl.java

/**
 * Relation manipulation APIs/*from  www.jav  a 2  s .c  om*/
 */
@Override
public void assertRelation(CommonFieldsBase relation, User user) throws ODKDatastoreException {
    JdbcTemplate jc = getJdbcConnection();
    TransactionStatus status = null;
    try {
        DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition();

        // do serializable read on the information schema...
        paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE);
        paramTransactionDefinition.setReadOnly(true);
        status = tm.getTransaction(paramTransactionDefinition);

        // see if relation already is defined and update it with dimensions...
        if (updateRelation(jc, relation, null)) {
            // it exists -- we're done!
            tm.commit(status);
            status = null;
            return;
        } else {
            tm.commit(status);
            // Try a new transaction to create the table
            paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE);
            paramTransactionDefinition.setReadOnly(false);
            status = tm.getTransaction(paramTransactionDefinition);

            // total number of columns must be less than MAX_BIND_PARAMS
            int countColumns = 0;
            // need to create the table...
            StringBuilder b = new StringBuilder();
            b.append(K_CREATE_TABLE);
            b.append(K_BQ);
            b.append(relation.getSchemaName());
            b.append(K_BQ);
            b.append(".");
            b.append(K_BQ);
            b.append(relation.getTableName());
            b.append(K_BQ);
            b.append(K_OPEN_PAREN);
            boolean firstTime = true;
            for (DataField f : relation.getFieldList()) {
                if (!firstTime) {
                    b.append(K_CS);
                }
                ++countColumns;
                firstTime = false;
                b.append(K_BQ);
                b.append(f.getName());
                b.append(K_BQ);
                DataField.DataType type = f.getDataType();
                switch (type) {
                case BINARY:
                    b.append(" BYTEA");
                    break;
                case LONG_STRING:
                    b.append(" TEXT");// b.append(" CHARACTER SET utf8");
                    break;
                case STRING:
                    b.append(" VARCHAR(");
                    Long len = f.getMaxCharLen();
                    if (len == null) {
                        len = PersistConsts.DEFAULT_MAX_STRING_LENGTH;
                    }
                    b.append(len.toString());
                    b.append(K_CLOSE_PAREN);
                    // b.append(" CHARACTER SET utf8");
                    break;
                case BOOLEAN:
                    b.append(" BOOLEAN");
                    break;
                case INTEGER:
                    Integer int_digits = f.getNumericPrecision();
                    if (int_digits == null) {
                        int_digits = DEFAULT_INT_NUMERIC_PRECISION;
                    }

                    if (int_digits.compareTo(9) > 0) {
                        b.append(" BIGINT");
                    } else {
                        b.append(" INTEGER");
                    }
                    break;
                case DECIMAL:
                    if (f.isDoublePrecision()) {
                        b.append(" FLOAT(53)");
                    } else {
                        Integer dbl_digits = f.getNumericPrecision();
                        Integer dbl_fract = f.getNumericScale();
                        if (dbl_digits == null) {
                            dbl_digits = DEFAULT_DBL_NUMERIC_PRECISION;
                        }
                        if (dbl_fract == null) {
                            dbl_fract = DEFAULT_DBL_NUMERIC_SCALE;
                        }
                        b.append(" DECIMAL(");
                        b.append(dbl_digits.toString());
                        b.append(K_CS);
                        b.append(dbl_fract.toString());
                        b.append(K_CLOSE_PAREN);
                    }
                    break;
                case DATETIME:
                    b.append(" TIMESTAMP WITHOUT TIME ZONE");
                    break;
                case URI:
                    b.append(" VARCHAR(");
                    len = f.getMaxCharLen();
                    if (len == null) {
                        len = PersistConsts.URI_STRING_LEN;
                    }
                    b.append(len.toString());
                    b.append(")");// b.append(" CHARACTER SET utf8");
                    break;
                }

                if (f == relation.primaryKey) {
                    b.append(" UNIQUE ");
                }
                if (f.getNullable()) {
                    b.append(" NULL ");
                } else {
                    b.append(" NOT NULL ");
                }
            }
            b.append(K_CLOSE_PAREN);

            if (countColumns > MAX_BIND_PARAMS) {
                throw new IllegalArgumentException("Table size exceeds bind parameter limit");
            }

            String createTableStmt = b.toString();
            LogFactory.getLog(DatastoreImpl.class).info("Attempting: " + createTableStmt);

            jc.execute(createTableStmt);
            LogFactory.getLog(DatastoreImpl.class)
                    .info("create table success (before updateRelation): " + relation.getTableName());

            String idx;
            // create other indicies
            for (DataField f : relation.getFieldList()) {
                if ((f.getIndexable() != IndexType.NONE) && (f != relation.primaryKey)) {
                    idx = relation.getTableName() + "_" + shortPrefix(f.getName());
                    createIndex(jc, relation, idx, f);
                }
            }

            // and update the relation with actual dimensions...
            updateRelation(jc, relation, createTableStmt);
            tm.commit(status);
        }
    } catch (Exception e) {
        if (status != null) {
            tm.rollback(status);
        }
        throw new ODKDatastoreException(e);
    }
}

From source file:org.broadleafcommerce.common.util.TransactionUtils.java

public static TransactionStatus createTransaction(String name, int propagationBehavior, int isolationLevel,
        PlatformTransactionManager transactionManager, boolean isReadOnly) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName(name);/*  w w w.  j  a  va2  s .c o  m*/
    def.setReadOnly(isReadOnly);
    def.setPropagationBehavior(propagationBehavior);
    def.setIsolationLevel(isolationLevel);
    return transactionManager.getTransaction(def);
}

From source file:org.broadleafcommerce.common.util.TransactionUtils.java

public static TransactionStatus createTransaction(int propagationBehavior, int isolationLevel,
        PlatformTransactionManager transactionManager, boolean isReadOnly) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setReadOnly(isReadOnly);
    def.setPropagationBehavior(propagationBehavior);
    def.setIsolationLevel(isolationLevel);
    return transactionManager.getTransaction(def);
}

From source file:org.compass.spring.transaction.SpringSyncTransaction.java

public void begin(PlatformTransactionManager transactionManager, InternalCompassSession session,
        boolean commitBeforeCompletion) {

    this.session = session;
    this.transactionManager = transactionManager;

    // the factory called begin, so we are in charge, if we were not, than
    // it would not call begin (we are in charge of the COMPASS transaction,
    // the spring one is handled later)
    controllingNewTransaction = true;//from  ww  w .  j  a v a  2  s  . com

    if (transactionManager != null) {
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        int timeout = session.getSettings().getSettingAsInt(CompassEnvironment.Transaction.TRANSACTION_TIMEOUT,
                -1);
        if (timeout != -1) {
            transactionDefinition.setTimeout(timeout);
        }
        transactionDefinition.setReadOnly(session.isReadOnly());
        status = transactionManager.getTransaction(transactionDefinition);
    }

    session.getSearchEngine().begin();

    SpringTransactionSynchronization sync;
    if (transactionManager != null) {
        if (log.isDebugEnabled()) {
            if (status.isNewTransaction()) {
                log.debug("Beginning new Spring transaction, and a new compass transaction on thread ["
                        + Thread.currentThread().getName() + "]");
            } else {
                log.debug("Joining Spring transaction, and starting a new compass transaction on thread ["
                        + Thread.currentThread().getName() + "]");
            }
        }
        sync = new SpringTransactionSynchronization(session, status.isNewTransaction(), commitBeforeCompletion,
                transactionFactory);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Joining Spring transaction, and starting a new compass transaction on thread ["
                    + Thread.currentThread().getName() + "]");
        }
        sync = new SpringTransactionSynchronization(session, false, commitBeforeCompletion, transactionFactory);
    }
    TransactionSynchronizationManager.registerSynchronization(sync);

    setBegun(true);
}

From source file:org.ednovo.gooru.domain.service.storage.S3ResourceHandler.java

protected TransactionStatus initTransaction(String name, boolean isReadOnly) {

    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName(AUTHENTICATE_USER);/*from w w w. j a  va2s  .  c o m*/
    if (isReadOnly) {
        def.setReadOnly(isReadOnly);
    } else {
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    }

    return getTransactionManager().getTransaction(def);

}

From source file:org.eurekastreams.commons.server.async.AsyncActionController.java

/**
 * Execute the supplied {@link AsyncAction} with the given {@link AsyncActionContext}.
 * //www. ja v a2 s .  c  o  m
 * @param inAsyncActionContext
 *            - instance of the {@link AsyncActionContext} with which to execution the {@link AsyncAction}.
 * @param inAsyncAction
 *            - instance of the {@link AsyncAction} to execute.
 * @return - results from the execution of the AsyncAction.
 * 
 *         - GeneralException - when an unexpected error occurs. - ValidationException - when a
 *         {@link ValidationException} occurs. - ExecutionException - when an {@link ExecutionException} occurs.
 */
public Serializable execute(final AsyncActionContext inAsyncActionContext, final AsyncAction inAsyncAction) {
    Serializable results = null;
    DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
    transDef.setName(inAsyncAction.toString());
    transDef.setReadOnly(inAsyncAction.isReadOnly());
    TransactionStatus transStatus = transMgr.getTransaction(transDef);
    try {
        inAsyncAction.getValidationStrategy().validate(inAsyncActionContext);
        results = inAsyncAction.getExecutionStrategy().execute(inAsyncActionContext);
        transMgr.commit(transStatus);
    } catch (ValidationException vex) {
        onException(transStatus);
        logger.warn("Validation failed for the current action.", vex);
        for (Entry<String, String> currentError : vex.getErrors().entrySet()) {
            logger.warn("Validation key: " + currentError.getKey() + ", value: " + currentError.getValue());
        }
        throw vex;
    } catch (ExecutionException eex) {
        onException(transStatus);
        logger.error("Error occurred during execution.", eex);
        throw eex;
    } catch (Exception ex) {
        onException(transStatus);
        logger.error("Error occurred performing transaction.", ex);
        throw new GeneralException(ex);
    }

    return results;
}

From source file:org.eurekastreams.commons.server.async.AsyncActionController.java

/**
 * This method executes a {@link TaskHandlerAction} with the supplied {@link AsyncActionContext}.
 * /*w  w w.  j  a v  a  2 s . c o m*/
 * @param inAsyncActionContext
 *            - instance of the {@link AsyncActionContext} associated with this request.
 * @param inTaskHandlerAction
 *            - instance of the {@link TaskHandlerAction}.
 * @return - results of the execution.
 * 
 *         - GeneralException - when an unexpected error occurs. - ValidationException - when a
 *         {@link ValidationException} occurs. - ExecutionException - when an {@link ExecutionException} occurs.
 */
@SuppressWarnings("unchecked")
public Serializable execute(final AsyncActionContext inAsyncActionContext,
        final TaskHandlerAction inTaskHandlerAction) {
    Serializable results = null;

    DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
    transDef.setName(inTaskHandlerAction.toString());
    transDef.setReadOnly(inTaskHandlerAction.isReadOnly());
    TransactionStatus transStatus = transMgr.getTransaction(transDef);

    // Assemble special context for TaskHandler actions.
    TaskHandlerActionContext<ActionContext> taskHandlerContext = new TaskHandlerActionContext<ActionContext>(
            inAsyncActionContext, new ArrayList<UserActionRequest>());
    try {
        inTaskHandlerAction.getValidationStrategy().validate(inAsyncActionContext);
        results = inTaskHandlerAction.getExecutionStrategy().execute(taskHandlerContext);
        transMgr.commit(transStatus);
    } catch (ValidationException vex) {
        onException(transStatus);
        logger.warn("Validation failed for the current action.", vex);
        for (Entry<String, String> currentError : vex.getErrors().entrySet()) {
            logger.warn("Validation key: " + currentError.getKey() + ", value: " + currentError.getValue());
        }
        throw vex;
    } catch (ExecutionException eex) {
        onException(transStatus);
        logger.error("Error occurred during execution.", eex);
        throw eex;
    } catch (Exception ex) {
        onException(transStatus);
        logger.error("Error occurred performing transaction.", ex);
        throw new GeneralException(ex);
    }

    // Submit the TaskRequests gathered from the execution strategy into the TaskHandlerContext to the TaskHandler.
    try {
        TaskHandler currentTaskHandler = inTaskHandlerAction.getTaskHandler();
        for (UserActionRequest currentRequest : taskHandlerContext.getUserActionRequests()) {
            currentTaskHandler.handleTask(currentRequest);
        }
    } catch (Exception ex) {
        logger.error("Error occurred posting UserActionRequests to the queue.", ex);
        throw (new GeneralException("Error occurred posting UserActionRequests to the queue.", ex));
    }

    return results;
}

From source file:org.eurekastreams.commons.server.service.ServiceActionController.java

/**
 * Execute the supplied {@link ServiceAction} with the given {@link PrincipalActionContext}.
 *
 * @param inServiceActionContext//from   ww w  .  j a v  a  2s  .  c o  m
 *            - instance of the {@link PrincipalActionContext} with which to execution the {@link ServiceAction}.
 * @param inServiceAction
 *            - instance of the {@link ServiceAction} to execute.
 * @return - results from the execution of the ServiceAction.
 *
 *         - GeneralException - when an unexpected error occurs. - ValidationException - when a
 *         {@link ValidationException} occurs. - AuthorizationException - when an {@link AuthorizationException}
 *         occurs. - ExecutionException - when an {@link ExecutionException} occurs.
 */
public Serializable execute(final PrincipalActionContext inServiceActionContext,
        final ServiceAction inServiceAction) {
    Serializable results = null;
    DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
    transDef.setName(inServiceAction.toString());
    transDef.setReadOnly(inServiceAction.isReadOnly());
    TransactionStatus transStatus = transMgr.getTransaction(transDef);
    try {
        inServiceAction.getValidationStrategy().validate(inServiceActionContext);
        inServiceAction.getAuthorizationStrategy().authorize(inServiceActionContext);
        results = inServiceAction.getExecutionStrategy().execute(inServiceActionContext);
        transMgr.commit(transStatus);
    } catch (ValidationException vex) {
        onException(transStatus);
        logger.warn("Validation failed for the current action.", vex);
        for (Entry<String, String> currentError : vex.getErrors().entrySet()) {
            logger.warn("Validation key: " + currentError.getKey() + ", value: " + currentError.getValue());
        }
        throw vex;
    } catch (AuthorizationException aex) {
        onException(transStatus);
        logger.warn("Authorization failed for the current action.", aex);
        throw aex;
    } catch (ExecutionException eex) {
        onException(transStatus);
        logger.error("Error occurred during execution.", eex);
        throw eex;
    } catch (Exception ex) {
        onException(transStatus);
        logger.error("Error occurred performing transaction.", ex);
        throw new GeneralException(ex);
    }

    return results;
}

From source file:org.eurekastreams.commons.server.service.ServiceActionController.java

/**
 * This method executes a {@link TaskHandlerAction} with the supplied {@link PrincipalActionContext}.
 *
 * @param inServiceActionContext//from  w w w.ja  v  a  2s .  co m
 *            - instance of the {@link PrincipalActionContext} associated with this request.
 * @param inTaskHandlerAction
 *            - instance of the {@link TaskHandlerAction}.
 * @return - results of the execution.
 *
 *         - GeneralException - when an unexpected error occurs. - ValidationException - when a
 *         {@link ValidationException} occurs. - AuthorizationException - when an {@link AuthorizationException}
 *         occurs. - ExecutionException - when an {@link ExecutionException} occurs.
 */
public Serializable execute(final PrincipalActionContext inServiceActionContext,
        final TaskHandlerAction inTaskHandlerAction) {
    Serializable results = null;
    DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
    transDef.setName(inTaskHandlerAction.toString());
    transDef.setReadOnly(inTaskHandlerAction.isReadOnly());
    TransactionStatus transStatus = transMgr.getTransaction(transDef);
    TaskHandlerActionContext<PrincipalActionContext> taskHandlerContext = // \n
            new TaskHandlerActionContext<PrincipalActionContext>(inServiceActionContext,
                    new ArrayList<UserActionRequest>());
    try {
        inTaskHandlerAction.getValidationStrategy().validate(inServiceActionContext);
        inTaskHandlerAction.getAuthorizationStrategy().authorize(inServiceActionContext);
        results = inTaskHandlerAction.getExecutionStrategy().execute(taskHandlerContext);
        transMgr.commit(transStatus);
    } catch (ValidationException vex) {
        onException(transStatus);
        logger.warn("Validation failed for the current action.", vex);
        for (Entry<String, String> currentError : vex.getErrors().entrySet()) {
            logger.warn("Validation key: " + currentError.getKey() + ", value: " + currentError.getValue());
        }
        throw vex;
    } catch (AuthorizationException aex) {
        onException(transStatus);
        logger.warn("Authorization failed for the current action.", aex);
        throw aex;
    } catch (ExecutionException eex) {
        onException(transStatus);
        logger.error("Error occurred during execution.", eex);
        throw eex;
    } catch (Exception ex) {
        onException(transStatus);
        logger.error("Error occurred performing transaction.", ex);
        throw new GeneralException(ex);
    }

    // Submit the TaskRequests gathered from the execution strategy into the TaskHandlerContext to the TaskHandler.
    try {
        TaskHandler currentTaskHandler = inTaskHandlerAction.getTaskHandler();
        for (UserActionRequest currentRequest : taskHandlerContext.getUserActionRequests()) {
            currentTaskHandler.handleTask(currentRequest);
        }
    } catch (Exception ex) {
        logger.error("Error occurred posting UserActionRequests to the queue.", ex);
        throw (new GeneralException("Error occurred posting UserActionRequests to the queue.", ex));
    }

    return results;
}

From source file:org.eurekastreams.server.service.restlets.StreamIdValidationResource.java

/**
 * Handle GET requests./*  w w  w.j ava 2  s  .c o  m*/
 * 
 * @param variant
 *            the variant to be retrieved.
 * @throws ResourceException
 *             thrown if a representation cannot be provided
 * @return a representation of the resource
 */
@Override
public Representation represent(final Variant variant) throws ResourceException {
    DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
    transDef.setReadOnly(true);
    TransactionStatus currentStatus = transManager.getTransaction(transDef);

    boolean isValid;
    String typeString = WordUtils.capitalizeFully(type.toString());
    try {
        switch (type) {
        case PERSON:
            PersonModelView pmv = getPersonMVByAccountId.execute(uniqueKey);
            isValid = pmv != null;
            break;
        case GROUP:
            List<DomainGroupModelView> groups = groupByShortNameDAO
                    .execute(Collections.singletonList(uniqueKey));
            isValid = groups.size() == 1;
            break;
        default:
            typeString = "Type";
            throw new RuntimeException("only accepts person and group types.");
        }
        transManager.commit(currentStatus);
    } catch (Exception e) {
        log.warn("Error validating id", e);
        transManager.rollback(currentStatus);
        isValid = false;
    }

    String styleColor = isValid ? "green" : "red";
    String responseString = isValid ? "Valid " : "Invalid ";

    // style the response
    String styledResponse = "<div style=\"color:" + styleColor + "; font-family:Arial; font-size:smaller\">"
            + responseString + typeString + "</div>";

    Representation rep = new StringRepresentation(styledResponse, MediaType.TEXT_HTML);
    rep.setExpirationDate(new Date(0L));
    return rep;
}