Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

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

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

From source file:portal.api.impl.PortalJpaController.java

public void deleteAllMANOproviders() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from  w  w w  .j a v  a2s  . c o  m

    Query q = entityManager.createQuery("DELETE FROM MANOprovider");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

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

/**
 * {@inheritDoc}//from w w w .j  a  va2s .  co m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear(String)
 */
@Override
public void clear(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();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_BY_SOURCE);
            diQuery.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dao.getDataSourceId())
                    .executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing for sessionId: " + sessionId + " with data source "
                        + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing for session id: " + sessionId, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

private void populateSeriesData() throws SearchServiceDatabaseException {
    EntityManager em = null;//from  w  w w. j a  v  a  2s  .  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:name.livitski.tools.persista.TransactionalWork.java

/**
 * Performs the {@link #code database operations} provided by
 * the subclass in JPA transactional brackets. If there is currently
 * no active transaction at the entity manager, a new transaction
 * is started.//from  w  w  w .j  a v  a 2  s  .  co  m
 * If the code finishes normally and does not request the rollback,
 * the transaction is committed if it was started by this method
 * (local transaction).
 * If the implementor's code throws an exception or requests the
 * rollback, the local transaction is rolled back and any ongoing
 * transaction is marked
 * {@link EntityTransaction#setRollbackOnly() rollback-only}.
 * @param db the entity manager the operation will be performed with
 * @return <code>true</code> if the transaction has or may still
 * be committed
 * @throws AbstractStorageException indicates an error during
 * the operation
 * @throws RuntimeException any unchecked implementor's exceptions
 * will be rethrown
 * @see EntityManager#getTransaction()
 */
public boolean exec(final EntityManager db) throws AbstractStorageException {
    final EntityTransaction transaction = db.getTransaction();
    boolean commit = false;
    Exception status = null;
    boolean localTransaction;
    if (transaction.isActive())
        localTransaction = false;
    else {
        transaction.begin();
        localTransaction = true;
    }
    try {
        commit = code(db);
        return commit;
    } catch (AbstractStorageException fault) {
        status = fault;
        throw fault;
    } catch (RuntimeException fault) {
        status = fault;
        throw fault;
    } finally {
        if (!localTransaction) {
            if (commit)
                db.flush();
            else
                transaction.setRollbackOnly();
        } else if (!commit || transaction.getRollbackOnly()) {
            try {
                transaction.rollback();
            } catch (RuntimeException fault) {
                if (null != status)
                    log().error("Transaction rollback failed", fault);
                else
                    throw fault;
            }
        } else // commit local transaction
        {
            try {
                transaction.commit();
            } catch (RuntimeException fault) {
                throw fault;
            }
        }
    }
}

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/* w  w  w  .j  ava2 s .c o  m*/
 * @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.capture.admin.impl.CaptureAgentStateServiceImpl.java

/**
 * Updates or adds an agent to the database.
 * //w w w  .j a  va  2s. c o m
 * @param agent
 *          The Agent you wish to modify or add in the database.
 */
protected void updateAgentInDatabase(AgentImpl agent) {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        AgentImpl existing = getAgentEntity(agent.getName(), agent.getOrganization(), em);
        if (existing == null) {
            em.persist(agent);
        } else {
            existing.setConfiguration(agent.getConfiguration());
            existing.setLastHeardFrom(agent.getLastHeardFrom());
            existing.setState(agent.getState());
            existing.setSchedulerRoles(agent.getSchedulerRoles());
            existing.setUrl(agent.getUrl());
            em.merge(existing);
        }
        tx.commit();
        agentCache.put(agent.getName().concat(DELIMITER).concat(agent.getOrganization()),
                Tuple.tuple(agent.getState(), agent.getConfiguration()));
    } catch (RollbackException e) {
        logger.warn("Unable to commit to DB in updateAgent.");
        throw e;
    } finally {
        if (em != null)
            em.close();
    }
}

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

public void deleteBusiness(DeleteBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from w w  w .  j a  va  2s. c  o m
        tx.begin();

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

        new ValidatePublish(publisher).validateDeleteBusiness(em, body);

        List<String> entityKeyList = body.getBusinessKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey);
            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        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");
    }// ww  w.j  ava  2  s.  c  om

    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:info.san.books.app.model.listener.LivreListener.java

@EventHandler
public void handle(LivreUpdatedEvent e) {
    EntityManager em = Persistence.getInstance().createEntityManager();

    EntityTransaction t = em.getTransaction();

    t.begin();/* w  w  w  .  j  a va2s  .  co  m*/

    LivreEntry entry = em.find(LivreEntry.class, e.getIsbn());
    entry.setEditeur(e.getEditeur());
    entry.setFormat(e.getFormat());
    entry.setImagePath(e.getImagePath());
    entry.setIsbn(e.getIsbn());
    entry.setLangue(e.getLangue());
    entry.setNbPage(e.getNbPage());
    entry.setResume(e.getResume());
    entry.setTitre(e.getTitre());
    entry.setTitreOriginal(e.getTitreOriginal());
    entry.setLu(e.isLu());
    entry.setPossede(e.isPossede());
    try {
        entry.setImageAsBase64(this.getImageAsBase64(e.getImagePath()));
    } catch (IOException ioe) {
        LivreListener.LOGGER.warn("Cannot save the thumbnail in database: ", ioe);
        entry.setImageAsBase64(null);
    }

    if (e.getImagePath() == null || e.getImagePath().isEmpty()) {
        entry.setImageAsBase64(null);
    }

    if (e.getSagaId() != null && !e.getSagaId().trim().isEmpty()) {
        SagaEntry saga = em.getReference(SagaEntry.class, e.getSagaId());
        entry.setSaga(saga);
    } else {
        entry.setSaga(null);
    }

    t.commit();
}

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

/**
 * {@inheritDoc}//from w  w w .  j a  va 2s  . c  o m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear()
 */
@Override
public void clear() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_ALL);
            diQuery.executeUpdate();
            // delete source
            final Query dsQuery = em.createNamedQuery(DataSourceDao.NAMED_QUERY_DELETE_SOURCES);
            dsQuery.executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}