Example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW

List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW.

Prototype

int PROPAGATION_REQUIRES_NEW

To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW.

Click Source Link

Document

Create a new transaction, suspending the current transaction if one exists.

Usage

From source file:org.springframework.session.jdbc.JdbcOperationsSessionRepository.java

private static TransactionTemplate createTransactionTemplate(PlatformTransactionManager transactionManager) {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    transactionTemplate.afterPropertiesSet();
    return transactionTemplate;
}

From source file:org.springframework.test.context.jdbc.DatabaseInitializerTestExecutionListener.java

/**
 * Execute the SQL scripts configured via the supplied
 * {@link DatabaseInitializer @DatabaseInitializer} for the given
 * {@link ExecutionPhase} and {@link TestContext}.
 *
 * <p>Special care must be taken in order to properly support the
 * {@link DatabaseInitializer#requireNewTransaction requireNewTransaction}
 * flag.//ww  w .j ava  2  s. c  om
 *
 * @param databaseInitializer the {@code @DatabaseInitializer} to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link DatabaseInitializer @DatabaseInitializer}
 * was declared at the class level
 */
@SuppressWarnings("serial")
private void executeDatabaseInitializer(DatabaseInitializer databaseInitializer, ExecutionPhase executionPhase,
        TestContext testContext, boolean classLevel) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                databaseInitializer, executionPhase, testContext));
    }

    if (executionPhase != databaseInitializer.executionPhase()) {
        return;
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(databaseInitializer.encoding());
    populator.setSeparator(databaseInitializer.separator());
    populator.setCommentPrefix(databaseInitializer.commentPrefix());
    populator.setBlockCommentStartDelimiter(databaseInitializer.blockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(databaseInitializer.blockCommentEndDelimiter());
    populator.setContinueOnError(databaseInitializer.continueOnError());
    populator.setIgnoreFailedDrops(databaseInitializer.ignoreFailedDrops());

    String[] scripts = getScripts(databaseInitializer, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    populator.setScripts(
            TestContextResourceUtils.convertToResources(testContext.getApplicationContext(), scripts));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scripts));
    }

    final DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext,
            databaseInitializer.dataSource());
    final PlatformTransactionManager transactionManager = TestContextTransactionUtils
            .retrieveTransactionManager(testContext, databaseInitializer.transactionManager());

    int propagation = databaseInitializer.requireNewTransaction()
            ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
            : TransactionDefinition.PROPAGATION_REQUIRED;

    TransactionAttribute transactionAttribute = TestContextTransactionUtils
            .createDelegatingTransactionAttribute(testContext, new DefaultTransactionAttribute(propagation));

    new TransactionTemplate(transactionManager, transactionAttribute)
            .execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    populator.execute(dataSource);
                };
            });
}

From source file:org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.java

/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.//w w  w  .  j a v a 2  s  .  c  om
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext,
        boolean classLevel) throws Exception {

    if (executionPhase != sql.executionPhase()) {
        return;
    }

    MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                mergedSqlConfig, executionPhase, testContext));
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
    populator.setSeparator(mergedSqlConfig.getSeparator());
    populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
    populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
    populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
    populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

    String[] scripts = getScripts(sql, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    List<Resource> scriptResources = TestContextResourceUtils
            .convertToResourceList(testContext.getApplicationContext(), scripts);
    for (String stmt : sql.statements()) {
        if (StringUtils.hasText(stmt)) {
            stmt = stmt.trim();
            scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
        }
    }
    populator.setScripts(scriptResources.toArray(new Resource[scriptResources.size()]));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
    }

    String dsName = mergedSqlConfig.getDataSource();
    String tmName = mergedSqlConfig.getTransactionManager();
    DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
    PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext,
            tmName);
    boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

    if (txMgr == null) {
        Assert.state(!newTxRequired,
                () -> String.format(
                        "Failed to execute SQL scripts for test context %s: "
                                + "cannot execute SQL scripts using Transaction Mode "
                                + "[%s] without a PlatformTransactionManager.",
                        testContext, TransactionMode.ISOLATED));
        Assert.state(dataSource != null,
                () -> String.format("Failed to execute SQL scripts for test context %s: "
                        + "supply at least a DataSource or PlatformTransactionManager.", testContext));
        // Execute scripts directly against the DataSource
        populator.execute(dataSource);
    } else {
        DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
        // Ensure user configured an appropriate DataSource/TransactionManager pair.
        if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
            throw new IllegalStateException(String.format(
                    "Failed to execute SQL scripts for test context %s: "
                            + "the configured DataSource [%s] (named '%s') is not the one associated with "
                            + "transaction manager [%s] (named '%s').",
                    testContext, dataSource.getClass().getName(), dsName, txMgr.getClass().getName(), tmName));
        }
        if (dataSource == null) {
            dataSource = dataSourceFromTxMgr;
            Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for "
                    + "test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
                    testContext, txMgr.getClass().getName(), tmName));
        }
        final DataSource finalDataSource = dataSource;
        int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                : TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
                testContext, new DefaultTransactionAttribute(propagation));
        new TransactionTemplate(txMgr, txAttr).execute(status -> {
            populator.execute(finalDataSource);
            return null;
        });
    }
}

From source file:org.springframework.transaction.reactive.AbstractReactiveTransactionManager.java

/**
 * This implementation handles propagation behavior. Delegates to
 * {@code doGetTransaction}, {@code isExistingTransaction}
 * and {@code doBegin}.//from   ww  w.  j a  va 2  s .c  om
 * @see #doGetTransaction
 * @see #isExistingTransaction
 * @see #doBegin
 */
@Override
public final Mono<ReactiveTransaction> getReactiveTransaction(@Nullable TransactionDefinition definition)
        throws TransactionException {

    // Use defaults if no transaction definition given.
    TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());

    return TransactionSynchronizationManager.currentTransaction().flatMap(synchronizationManager -> {

        Object transaction = doGetTransaction(synchronizationManager);

        // Cache debug flag to avoid repeated checks.
        boolean debugEnabled = logger.isDebugEnabled();

        if (isExistingTransaction(transaction)) {
            // Existing transaction found -> check propagation behavior to find out how to behave.
            return handleExistingTransaction(synchronizationManager, def, transaction, debugEnabled);
        }

        // Check definition settings for new transaction.
        if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
            return Mono.error(new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout()));
        }

        // No existing transaction found -> check propagation behavior to find out how to proceed.
        if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
            return Mono.error(new IllegalTransactionStateException(
                    "No existing transaction found for transaction marked with propagation 'mandatory'"));
        } else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED
                || def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW
                || def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {

            return TransactionContextManager.currentContext().map(TransactionSynchronizationManager::new)
                    .flatMap(nestedSynchronizationManager -> suspend(nestedSynchronizationManager, null)
                            .map(Optional::of).defaultIfEmpty(Optional.empty()).flatMap(suspendedResources -> {
                                if (debugEnabled) {
                                    logger.debug("Creating new transaction with name [" + def.getName() + "]: "
                                            + def);
                                }
                                return Mono.defer(() -> {
                                    GenericReactiveTransaction status = newReactiveTransaction(
                                            nestedSynchronizationManager, def, transaction, true, debugEnabled,
                                            suspendedResources.orElse(null));
                                    return doBegin(nestedSynchronizationManager, transaction, def)
                                            .doOnSuccess(ignore -> prepareSynchronization(
                                                    nestedSynchronizationManager, status, def))
                                            .thenReturn(status);
                                }).onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR,
                                        ex -> resume(nestedSynchronizationManager, null,
                                                suspendedResources.orElse(null)).then(Mono.error(ex)));
                            }));
        } else {
            // Create "empty" transaction: no actual transaction, but potentially synchronization.
            if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
                logger.warn("Custom isolation level specified but no actual transaction initiated; "
                        + "isolation level will effectively be ignored: " + def);
            }
            return Mono.just(
                    prepareReactiveTransaction(synchronizationManager, def, null, true, debugEnabled, null));
        }
    });
}

From source file:org.springframework.transaction.reactive.AbstractReactiveTransactionManager.java

/**
 * Create a ReactiveTransaction for an existing transaction.
 *//*from  www  .ja  v a 2 s.c  o m*/
private Mono<ReactiveTransaction> handleExistingTransaction(
        TransactionSynchronizationManager synchronizationManager, TransactionDefinition definition,
        Object transaction, boolean debugEnabled) throws TransactionException {

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
        return Mono.error(new IllegalTransactionStateException(
                "Existing transaction found for transaction marked with propagation 'never'"));
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction");
        }
        Mono<SuspendedResourcesHolder> suspend = suspend(synchronizationManager, transaction);
        return suspend
                .map(suspendedResources -> prepareReactiveTransaction(synchronizationManager, definition, null,
                        false, debugEnabled, suspendedResources)) //
                .switchIfEmpty(Mono.fromSupplier(() -> prepareReactiveTransaction(synchronizationManager,
                        definition, null, false, debugEnabled, null)))
                .cast(ReactiveTransaction.class);
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction, creating new transaction with name ["
                    + definition.getName() + "]");
        }
        Mono<SuspendedResourcesHolder> suspendedResources = suspend(synchronizationManager, transaction);
        return suspendedResources.flatMap(suspendedResourcesHolder -> {
            GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager, definition,
                    transaction, true, debugEnabled, suspendedResourcesHolder);
            return doBegin(synchronizationManager, transaction, definition)
                    .doOnSuccess(ignore -> prepareSynchronization(synchronizationManager, status, definition))
                    .thenReturn(status).onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR,
                            beginEx -> resumeAfterBeginException(synchronizationManager, transaction,
                                    suspendedResourcesHolder, beginEx).then(Mono.error(beginEx)));
        });
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        if (debugEnabled) {
            logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
        }
        // Nested transaction through nested begin and commit/rollback calls.
        GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager, definition,
                transaction, true, debugEnabled, null);
        return doBegin(synchronizationManager, transaction, definition)
                .doOnSuccess(ignore -> prepareSynchronization(synchronizationManager, status, definition))
                .thenReturn(status);
    }

    // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
    if (debugEnabled) {
        logger.debug("Participating in existing transaction");
    }
    return Mono.just(prepareReactiveTransaction(synchronizationManager, definition, transaction, false,
            debugEnabled, null));
}

From source file:org.springframework.transaction.support.AbstractPlatformTransactionManager.java

/**
 * This implementation handles propagation behavior. Delegates to
 * {@code doGetTransaction}, {@code isExistingTransaction}
 * and {@code doBegin}./*ww w.j  a  v a2s  .  c  om*/
 * @see #doGetTransaction
 * @see #isExistingTransaction
 * @see #doBegin
 */
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
        throws TransactionException {
    Object transaction = doGetTransaction();

    // Cache debug flag to avoid repeated checks.
    boolean debugEnabled = logger.isDebugEnabled();

    if (definition == null) {
        // Use defaults if no transaction definition given.
        definition = new DefaultTransactionDefinition();
    }

    if (isExistingTransaction(transaction)) {
        // Existing transaction found -> check propagation behavior to find out how to behave.
        return handleExistingTransaction(definition, transaction, debugEnabled);
    }

    // Check definition settings for new transaction.
    if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
        throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
    }

    // No existing transaction found -> check propagation behavior to find out how to proceed.
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
        throw new IllegalTransactionStateException(
                "No existing transaction found for transaction marked with propagation 'mandatory'");
    } else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED
            || definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW
            || definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        SuspendedResourcesHolder suspendedResources = suspend(null);
        if (debugEnabled) {
            logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
        }
        try {
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true,
                    newSynchronization, debugEnabled, suspendedResources);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        } catch (RuntimeException | Error ex) {
            resume(null, suspendedResources);
            throw ex;
        }
    } else {
        // Create "empty" transaction: no actual transaction, but potentially synchronization.
        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT
                && logger.isWarnEnabled()) {
            logger.warn("Custom isolation level specified but no actual transaction initiated; "
                    + "isolation level will effectively be ignored: " + definition);
        }
        boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
        return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
    }
}

From source file:org.springframework.transaction.support.AbstractPlatformTransactionManager.java

/**
 * Create a TransactionStatus for an existing transaction.
 *//*from w  w  w  . ja v  a2s .  co m*/
private TransactionStatus handleExistingTransaction(TransactionDefinition definition, Object transaction,
        boolean debugEnabled) throws TransactionException {

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
        throw new IllegalTransactionStateException(
                "Existing transaction found for transaction marked with propagation 'never'");
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction");
        }
        Object suspendedResources = suspend(transaction);
        boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
        return prepareTransactionStatus(definition, null, false, newSynchronization, debugEnabled,
                suspendedResources);
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction, creating new transaction with name ["
                    + definition.getName() + "]");
        }
        SuspendedResourcesHolder suspendedResources = suspend(transaction);
        try {
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true,
                    newSynchronization, debugEnabled, suspendedResources);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        } catch (RuntimeException | Error beginEx) {
            resumeAfterBeginException(transaction, suspendedResources, beginEx);
            throw beginEx;
        }
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        if (!isNestedTransactionAllowed()) {
            throw new NestedTransactionNotSupportedException(
                    "Transaction manager does not allow nested transactions by default - "
                            + "specify 'nestedTransactionAllowed' property with value 'true'");
        }
        if (debugEnabled) {
            logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
        }
        if (useSavepointForNestedTransaction()) {
            // Create savepoint within existing Spring-managed transaction,
            // through the SavepointManager API implemented by TransactionStatus.
            // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
            DefaultTransactionStatus status = prepareTransactionStatus(definition, transaction, false, false,
                    debugEnabled, null);
            status.createAndHoldSavepoint();
            return status;
        } else {
            // Nested transaction through nested begin and commit/rollback calls.
            // Usually only for JTA: Spring synchronization might get activated here
            // in case of a pre-existing JTA transaction.
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true,
                    newSynchronization, debugEnabled, null);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        }
    }

    // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
    if (debugEnabled) {
        logger.debug("Participating in existing transaction");
    }
    if (isValidateExistingTransaction()) {
        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
            Integer currentIsolationLevel = TransactionSynchronizationManager
                    .getCurrentTransactionIsolationLevel();
            if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
                Constants isoConstants = DefaultTransactionDefinition.constants;
                throw new IllegalTransactionStateException("Participating transaction with definition ["
                        + definition
                        + "] specifies isolation level which is incompatible with existing transaction: "
                        + (currentIsolationLevel != null
                                ? isoConstants.toCode(currentIsolationLevel,
                                        DefaultTransactionDefinition.PREFIX_ISOLATION)
                                : "(unknown)"));
            }
        }
        if (!definition.isReadOnly()) {
            if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                throw new IllegalTransactionStateException("Participating transaction with definition ["
                        + definition + "] is not marked as read-only but existing transaction is");
            }
        }
    }
    boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
    return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}

From source file:se.vgregion.service.innovationsslussen.idea.IdeaServiceImpl.java

@Override
//@Transactional(rollbackFor = BariumException.class)
public UpdateFromBariumResult updateFromBarium(Idea idea) throws UpdateIdeaException {

    // Do the transaction manually since we may run this in a separate thread.
    TransactionStatus transaction = transactionManager
            .getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRES_NEW));

    try {// w w  w.  jav a 2  s  . c  o  m

        UpdateFromBariumResult result = new UpdateFromBariumResult();
        result.setOldIdea(find(idea.getId()));
        result.getOldIdea().getIdeaContentPrivate();
        result.getOldIdea().getIdeaContentPublic();

        LOGGER.info(" Update from Barium, idea: " + idea.getTitle());

        // Idea idea = findIdeaByBariumId(id);
        final String ideaId = idea.getId();

        String oldTitle = idea.getTitle(); // To know whether it has changed, in case we need to update in Barium

        // Make two calls asynchronously and simultaneously to speed up.
        Future<IdeaObjectFields> ideaObjectFieldsFuture = bariumService.asyncGetIdeaObjectFields(ideaId);
        Future<String> bariumIdeaPhase = bariumService.asyncGetIdeaPhaseFuture(ideaId);

        int bariumPhase = 0;
        int currentPhase = Integer.parseInt(idea.getPhase() == null ? "0" : idea.getPhase());
        IdeaStatus oldStatus = idea.getStatus();

        try {
            if (bariumIdeaPhase.get() == null) {
                throw new BariumException("bariumIdeaPhase is null");
            }
            bariumPhase = Integer.parseInt(bariumIdeaPhase.get());

            populateIdea(ideaObjectFieldsFuture.get(), idea);

            //Sync files
            if (idea.getIdeaContentPrivate() != null) {
                populateFile(idea, idea.getIdeaContentPrivate(), LIFERAY_CLOSED_DOCUMENTS);
            }
            if (idea.getIdeaContentPublic() != null) {
                populateFile(idea, idea.getIdeaContentPublic(), LIFERAY_OPEN_DOCUMENTS);
            }

        } catch (InterruptedException e) {
            throw new UpdateIdeaException(e);
        } catch (ExecutionException e) {
            throw new UpdateIdeaException(e);
        }

        result.setChanged(!isIdeasTheSame(idea, result.getOldIdea()));

        final String finalUrlTitle;
        if (!oldTitle.equals(idea.getTitle())) {
            finalUrlTitle = generateNewUrlTitle(idea.getTitle());
            idea.setUrlTitle(finalUrlTitle);
        } else {
            idea.setUrlTitle(result.getOldIdea().getUrlTitle());
            finalUrlTitle = null;
        }

        if (idea.getOriginalUserId() == null) {
            idea.setOriginalUserId(0L);
        }

        idea = ideaRepository.merge(idea);
        result.setNewIdea(idea);

        if (finalUrlTitle != null) {
            final Idea finalIdea = idea;
            // We may just as well do this asynchronously since we don't throw anything and don't return anything
            // from
            // here.
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    // We need to update the ideaSiteLink in Barium.
                    String ideaSiteLink = generateIdeaSiteLink(schemeServerNameUrl, finalUrlTitle);
                    try {
                        bariumService.updateIdea(finalIdea.getId(), "siteLank", ideaSiteLink);
                    } catch (BariumException e) {
                        LOGGER.error("Failed to update idea " + finalIdea.getId() + " with new site link: "
                                + ideaSiteLink, e);
                    }
                }

            });
        }

        if (currentPhase != bariumPhase) {
            idea.setPhase("" + (bariumPhase));
            result.setChanged(true);
        }

        // Add auto-comments to the idea.
        idea = generateAutoComments(idea, oldStatus, currentPhase, bariumPhase);

        // Sync comments count
        idea.setCommentsCount(getPrivateCommentsCount(idea));
        idea = ideaRepository.merge(idea);

        // Sync last comment date
        List<CommentItemVO> privateComments = getComments(idea.getIdeaContentPrivate());
        if (privateComments.size() > 0) {
            Collections.sort(privateComments, new Comparator<CommentItemVO>() {
                @Override
                public int compare(CommentItemVO o1, CommentItemVO o2) {
                    return -o1.getCreateDate().compareTo(o2.getCreateDate());
                }
            });
            idea.setLastPrivateCommentDate(privateComments.get(0).getCreateDate());
        }

        if (transaction.isNewTransaction()) {
            transactionManager.commit(transaction);
        }

        return result;
    } catch (BariumException be) {
        transactionManager.rollback(transaction);
        LOGGER.warn(be.getMessage());
    } finally {
        if (!transaction.isCompleted()) {
            //If this happens, a runtimeexception has likley occurred.
            transactionManager.rollback(transaction);
            LOGGER.warn("Rolledback transaction because of likely RunTimeException");
        }
    }
    return null;
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.xml.exchange.PsiExchangeImpl.java

/**
 * Imports a stream containing PSI XML//from ww  w .  j a  va  2  s .co m
 *
 * @param psiXmlStream the stream to read and import
 * @return report of the import
 *
 * @throws PersisterException thrown if there are problems parsing the stream or persisting the data in the intact-model database
 */
public PersisterStatistics importIntoIntact(InputStream psiXmlStream) throws PersisterException {
    final List<IndexedEntry> indexedEntries;
    try {
        PsimiXmlLightweightReader reader = new PsimiXmlLightweightReader(psiXmlStream);
        indexedEntries = reader.getIndexedEntries();
    } catch (PsimiXmlReaderException e) {
        throw new PsiEnricherException("Problem reading source PSI", e);
    }

    PersisterStatistics stats = new PersisterStatistics();

    for (IndexedEntry indexedEntry : indexedEntries) {
        final TransactionStatus transactionStatus = IntactContext.getCurrentInstance().getDataContext()
                .beginTransaction(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        PersisterStatistics localStats = importIntoIntact(indexedEntry);
        stats = merge(stats, localStats);

        IntactContext.getCurrentInstance().getDataContext().commitTransaction(transactionStatus);
    }

    return stats;
}