Example usage for javax.persistence EntityTransaction rollback

List of usage examples for javax.persistence EntityTransaction rollback

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction rollback.

Prototype

public void rollback();

Source Link

Document

Roll back the current resource transaction.

Usage

From source file:org.opencastproject.messages.MailService.java

public void deleteMessageTemplate(Long id) throws MailServiceException, NotFoundException {
    EntityManager em = null;/*  w w  w  .  j ava  2 s  .  co m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        Option<MessageTemplateDto> templateOption = findMessageTemplateById(id, orgId, em);
        if (templateOption.isNone())
            throw new NotFoundException();
        em.remove(templateOption.get());
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete message template '{}': {}", id, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

public void deleteMessageSignature(Long id) throws MailServiceException, NotFoundException {
    EntityManager em = null;/*  w  ww  . j a  v a  2 s  .com*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        Option<MessageSignatureDto> signatureOption = findMessageSignatureById(id, orgId, em);
        if (signatureOption.isNone())
            throw new NotFoundException();
        em.remove(signatureOption.get());
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete message signature '{}': {}", id, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.clustercontrol.commons.util.JpaTransactionManager.java

/**
 * ?//from  ww w  .  j  a va2s . c  om
 */
public void close() {
    if (!nestedEm && em != null) {
        if (em.isOpen()) {
            try {
                List<JpaTransactionCallback> callbacks = getCallbacks();

                if (!isCallbacked()) {
                    for (JpaTransactionCallback callback : callbacks) {
                        if (m_log.isDebugEnabled()) {
                            m_log.debug("executing callback preClose : " + callback.getClass().getName());
                        }
                        try {
                            setCallbacked();

                            callback.preClose();
                        } catch (Throwable t) {
                            m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                        } finally {
                            unsetCallbacked();
                        }
                    }
                }

                // commit or rollback???close?????????(rollback)?
                // ???connection????????
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    if (m_log.isDebugEnabled()) {
                        StackTraceElement[] eList = Thread.currentThread().getStackTrace();
                        StringBuilder trace = new StringBuilder();
                        for (StackTraceElement e : eList) {
                            if (trace.length() > 0) {
                                trace.append("\n");
                            }
                            trace.append(String.format("%s.%s(%s:%d)", e.getClassName(), e.getMethodName(),
                                    e.getFileName(), e.getLineNumber()));
                        }
                        m_log.debug(
                                "closing uncompleted transaction. this transaction will be rollbacked before closing : "
                                        + trace);
                    }
                    tx.rollback();
                }

                em.close();
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);

                // postClose???innerTransaction????????callback???
                for (JpaTransactionCallback callback : callbacks) {
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("executing callback postClose : " + callback.getClass().getName());
                    }
                    try {
                        callback.postClose();
                    } catch (Throwable t) {
                        m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                    }
                }
            } finally {
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);
            }
        }
        HinemosSessionContext.instance().setProperty(EM, null);
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*w ww . j  ava 2  s  .com*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#finish(String)
 */
@Override
public void finish(final String sessionId) throws DeltaIndexingSessionException, DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final DataSourceDao dao = assertSession(sessionId);
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao unlockedDao = new DataSourceDao(dao.getDataSourceId(), null);
            em.merge(unlockedDao);
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("finished session " + sessionId + " with data source: " + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error finishing delta indexing for data source: " + dao.getDataSourceId(), e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Retrieves all publisher from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required. Use caution when calling, result
 * set is not bound. If there are many publishers, it is possible to have a 
 * result set that is too large//  ww w .  ja  v  a2s . com
 * @param body
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
@SuppressWarnings("unchecked")
public PublisherDetail getAllPublisherDetail(GetAllPublisherDetail body)
        throws DispositionReportFaultMessage, RemoteException {

    new ValidatePublisher(null).validateGetAllPublisherDetail(body);

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        this.getEntityPublisher(em, body.getAuthInfo());

        PublisherDetail result = new PublisherDetail();

        Query query = em.createQuery("SELECT p from Publisher as p");
        List<Publisher> modelPublisherList = query.getResultList();

        for (Publisher modelPublisher : modelPublisherList) {

            org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher();

            MappingModelToApi.mapPublisher(modelPublisher, apiPublisher);

            result.getPublisher().add(apiPublisher);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

public EmailConfiguration updateEmailConfiguration(EmailConfiguration emailConfiguration)
        throws MailServiceException {
    EntityManager em = null;/*from   ww w  . ja  va  2  s . c o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        EmailConfigurationDto emailConfig = mergeEmailConfiguration(emailConfiguration, orgId, em);
        tx.commit();
        EmailConfiguration updatedEmailConfiguration = emailConfig.toEmailConfiguration();
        updateSmtpConfiguration(updatedEmailConfiguration);
        return updatedEmailConfiguration;
    } catch (Exception e) {
        logger.error("Could not update email configuration '{}': {}", emailConfiguration, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImplExt.java

public BusinessDetail saveBusinessFudge(SaveBusiness body, String nodeID) throws DispositionReportFaultMessage {

    if (!body.getBusinessEntity().isEmpty()) {
        log.debug("Inbound save business Fudger request for key "
                + body.getBusinessEntity().get(0).getBusinessKey());
    }//from  ww w.  java 2 s.co m
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        ValidatePublish validator = new ValidatePublish(publisher);
        validator.validateSaveBusiness(em, body, null);

        BusinessDetail result = new BusinessDetail();

        List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
        for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) {

            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();

            MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity);
            nodeId = nodeID;

            setOperationalInfo(em, modelBusinessEntity, publisher);

            em.persist(modelBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

        //check how many business this publisher owns.
        validator.validateSaveBusinessMax(em);

        tx.commit();

        return result;
    } catch (DispositionReportFaultMessage drfm) {

        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

private void populateSeriesData() throws SearchServiceDatabaseException {
    EntityManager em = null;// w ww . ja  v  a 2 s . co  m
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        TypedQuery<SearchEntity> q = (TypedQuery<SearchEntity>) em.createNamedQuery("Search.getNoSeries");
        List<SearchEntity> seriesList = q.getResultList();
        for (SearchEntity series : seriesList) {
            String mpSeriesId = MediaPackageParser.getFromXml(series.getMediaPackageXML()).getSeries();
            if (StringUtils.isNotBlank(mpSeriesId) && !mpSeriesId.equals(series.getSeriesId())) {
                logger.info("Fixing missing series ID for episode {}, series is {}", series.getMediaPackageId(),
                        mpSeriesId);
                series.setSeriesId(mpSeriesId);
                em.merge(series);
            }
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update media package: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.eucalyptus.blockstorage.san.common.SANManager.java

public SANManager() {
    Component sc = Components.lookup(Storage.class);
    if (sc == null) {
        throw Exceptions.toUndeclared("Cannot instantiate SANManager, no SC component found");
    }//from ww w .  j  a v a 2  s .c o m

    ServiceConfiguration scConfig = sc.getLocalServiceConfiguration();
    if (scConfig == null) {
        throw Exceptions.toUndeclared("Cannot instantiate SANManager without SC service configuration");
    }

    String sanProvider = null;
    EntityTransaction trans = Entities.get(StorageControllerConfiguration.class);
    try {
        StorageControllerConfiguration config = Entities
                .uniqueResult((StorageControllerConfiguration) scConfig);
        sanProvider = config.getBlockStorageManager();
        trans.commit();
    } catch (Exception e) {
        throw Exceptions.toUndeclared("Cannot get backend configuration for SC.");
    } finally {
        trans.rollback();
    }

    if (sanProvider == null) {
        throw Exceptions.toUndeclared("Cannot instantiate SAN Provider, none specified");
    }

    Class providerClass = StorageManagers.lookupProvider(sanProvider);
    if (providerClass != null && SANProvider.class.isAssignableFrom(providerClass)) {
        try {
            connectionManager = (SANProvider) providerClass.newInstance();
        } catch (IllegalAccessException e) {
            throw Exceptions.toUndeclared("Cannot create SANManager.", e);
        } catch (InstantiationException e) {
            throw Exceptions.toUndeclared("Cannot create SANManager. Cannot instantiate the SAN Provider", e);
        }
    } else {
        throw Exceptions.toUndeclared("Provider not of correct type or not found.");
    }
}

From source file:com.eucalyptus.images.Images.java

public static ImageInfo createFromDeviceMapping(final UserFullName userFullName, final String imageName,
        final String imageDescription, final ImageMetadata.Platform platform, String eki, String eri,
        final String rootDeviceName, final List<BlockDeviceMappingItemType> blockDeviceMappings)
        throws EucalyptusCloudException {
    final ImageMetadata.Architecture imageArch = ImageMetadata.Architecture.x86_64;//TODO:GRZE:OMGFIXME: track parent vol info; needed here 
    final ImageMetadata.Platform imagePlatform = platform;
    if (ImageMetadata.Platform.windows.equals(imagePlatform)) {
        eki = null;/*from w  w  w  .ja  v  a 2  s  .  c  o  m*/
        eri = null;
    }
    // Block device mappings have been verified before control gets here. 
    // If anything has changed with regard to the snapshot state, it will be caught while data structures for the image.
    final BlockDeviceMappingItemType rootBlockDevice = Iterables.find(blockDeviceMappings,
            findEbsRoot(rootDeviceName), null);
    if (rootBlockDevice == null) {
        throw new EucalyptusCloudException(
                "Failed to create image, root device mapping not found: " + rootDeviceName);
    }

    final String snapshotId = ResourceIdentifiers.tryNormalize()
            .apply(rootBlockDevice.getEbs().getSnapshotId());
    Snapshot snap;
    try {
        snap = Transactions.one(Snapshot.named(userFullName.asAccountFullName(), snapshotId),
                RestrictedTypes.filterPrivileged(), Functions.<Snapshot>identity());
    } catch (NoSuchElementException ex) {
        throw new EucalyptusCloudException("Failed to create image from specified block device mapping: "
                + rootBlockDevice + " because of: Snapshot not found " + snapshotId);
    } catch (TransactionExecutionException ex) {
        throw new EucalyptusCloudException("Failed to create image from specified block device mapping: "
                + rootBlockDevice + " because of: " + ex.getMessage());
    } catch (ExecutionException ex) {
        LOG.error(ex, ex);
        throw new EucalyptusCloudException("Failed to create image from specified block device mapping: "
                + rootBlockDevice + " because of: " + ex.getMessage());
    }

    final Integer suppliedVolumeSize = rootBlockDevice.getEbs().getVolumeSize() != null
            ? rootBlockDevice.getEbs().getVolumeSize()
            : snap.getVolumeSize();
    final Long imageSizeBytes = suppliedVolumeSize * 1024l * 1024l * 1024l;
    final Boolean targetDeleteOnTermination = Boolean.TRUE
            .equals(rootBlockDevice.getEbs().getDeleteOnTermination());
    final String imageId = ResourceIdentifiers.generateString(ImageMetadata.Type.machine.getTypePrefix());

    final boolean mapRoot = DEFAULT_PARTITIONED_ROOT_DEVICE.equals(rootDeviceName);
    BlockStorageImageInfo ret = new BlockStorageImageInfo(userFullName, imageId, imageName, imageDescription,
            imageSizeBytes, imageArch, imagePlatform, eki, eri, snap.getDisplayName(),
            targetDeleteOnTermination, mapRoot ? DEFAULT_ROOT_DEVICE : rootDeviceName);
    final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class);
    try {
        ret = Entities.merge(ret);
        Iterables.addAll(ret.getDeviceMappings(),
                Iterables.transform(blockDeviceMappings,
                        Images.deviceMappingGenerator(ret, suppliedVolumeSize, mapRoot
                                ? Collections.singletonMap(DEFAULT_PARTITIONED_ROOT_DEVICE, DEFAULT_ROOT_DEVICE)
                                : Collections.<String, String>emptyMap())));
        ret.setImageFormat(ImageMetadata.ImageFormat.fulldisk.toString());
        ret.setState(ImageMetadata.State.available);
        tx.commit();
        LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + userFullName);
    } catch (Exception e) {
        throw new EucalyptusCloudException(
                "Failed to register image using snapshot: " + snapshotId + " because of: " + e.getMessage(), e);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }

    return ret;
}