Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

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

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

From source file:org.isatools.isatab.ISATABUnloader.java

public void unload() {
    List<Study> studies = new LinkedList<Study>();

    EntityManager emgr = daoFactory.getEntityManager();
    Session session = (Session) emgr.getDelegate();
    EntityTransaction ts = emgr.getTransaction();

    if (studyAcc != null) {
        StudyDAO dao = daoFactory.getStudyDAO();
        Study study = dao.getByAcc(studyAcc);
        if (study == null) {
            log.warn("Study with accession '" + studyAcc + "' not found, no undeletion performed.");
            return;
        }//from  w ww.  j  a  va  2  s  .  c  o m
        studies.add(study);

        unloadMgr = new UnloadManager(daoFactory, study.getSubmissionTs());
        StudyUnloader unloader = (StudyUnloader) unloadMgr.getUnloader(Study.class);
        unloader.queueByAcc(studyAcc);
    } else {
        studies.addAll(daoFactory.getStudyDAO().getBySubmissionTs(unloadMgr.getSubmissionTs()));
        unloadMgr.queueAll(studies);
    }

    try {
        if (!ts.isActive()) {
            ts.begin();
        }
        unloadMgr.delete();
        ts.commit();
    } catch (HibernateException e) {
        if (ts.isActive()) {
            ts.rollback();
        }
        throw new TabInternalErrorException("Error while performing the unloading:" + e.getMessage());
    } finally {
        session.flush();
    }

    DataFilesDispatcher fileDispatcher = new DataFilesDispatcher(daoFactory.getEntityManager());
    fileDispatcher.undispatch(studies);
}

From source file:com.eucalyptus.objectstorage.entities.upgrade.ObjectStorage400Upgrade.java

private static void generateCanonicaIDs() throws Exception {
    EntityTransaction tran = Entities.get(AccountEntity.class);
    try {//  w w w . ja  v  a 2 s  . c o  m
        List<AccountEntity> accounts = Entities.query(new AccountEntity());
        if (accounts != null && accounts.size() > 0) {
            for (AccountEntity account : accounts) {
                if (account.getCanonicalId() == null || account.getCanonicalId().equals("")) {
                    account.populateCanonicalId();
                    LOG.debug("Assigning canonical id " + account.getCanonicalId() + " for account "
                            + account.getAccountNumber());
                }
            }
        }
        tran.commit();
    } catch (Exception e) {
        LOG.error("Failed to generate and assign canonical ids", e);
        tran.rollback();
        throw e;
    } finally {
        if (tran.isActive()) {
            tran.commit();
        }
    }
}

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

public static ImageInfo lookupImage(String imageId) {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {/* w w w.  j  av  a 2  s  .  co  m*/
        final ImageInfo found = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        db.commit();
        return found;
    } catch (final NoSuchElementException ex) {
        db.rollback();
        throw ex;
    } catch (final Exception ex) {
        db.rollback();
        throw Exceptions.toUndeclared(ex);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}/*from  w  w w. j a  v a  2s  . c om*/
 */
@Override
public void storeRecord(final Record record) throws RecordStorageException {
    if (record == null) {
        throw new RecordStorageException("parameter record is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            final RecordDao dao = new RecordDao(record);
            transaction.begin();
            if (findRecordDao(em, record.getId()) == null) {
                em.persist(dao);
            } else {
                em.merge(dao);
            }
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("stored record Id:" + record.getId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new RecordStorageException(e, "error storing record id: " + record.getId());
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEvent(DublinCoreCatalog event) throws NotFoundException, SchedulerServiceDatabaseException {
    if (event == null) {
        throw new SchedulerServiceDatabaseException("Cannot update <null> event");
    }//from   ww  w.  ja v a2 s .  com
    Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER));
    String dcXML;
    try {
        dcXML = serializeDublinCore(event);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SchedulerServiceDatabaseException(e1);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist.");
        }
        entity.setEventDublinCore(dcXML);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }

}

From source file:org.apache.juddi.replication.ReplicationNotifier.java

/**
 * Note: this is for locally originated changes only, see null null null         {@link org.apache.juddi.api.impl.UDDIReplicationImpl.PullTimerTask#PersistChangeRecord PersistChangeRecord
 * } for how remote changes are processed
 *
 * @param j must be one of the UDDI save APIs
 *
 *///from ww  w.j  ava2  s .  c o  m
protected void ProcessChangeRecord(org.apache.juddi.model.ChangeRecord j) {
    //store and convert the changes to database model

    //TODO need a switch to send the notification without persisting the record
    //this is to support multihop notifications
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        j.setIsAppliedLocally(true);
        em.persist(j);
        j.setOriginatingUSN(j.getId());
        em.merge(j);
        log.info("CR saved locally, it was from " + j.getNodeID() + " USN:" + j.getOriginatingUSN() + " Type:"
                + j.getRecordType().name() + " Key:" + j.getEntityKey() + " Local id:" + j.getId());
        tx.commit();
    } catch (Exception ex) {
        log.fatal("unable to store local change record locally!!", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        JAXB.marshal(MappingModelToApi.mapChangeRecord(j), System.out);
    } finally {
        em.close();
    }

    log.debug("ChangeRecord: " + j.getId() + "," + j.getEntityKey() + "," + j.getNodeID() + ","
            + j.getOriginatingUSN() + "," + j.getRecordType().toString());
    SendNotifications(j.getId(), j.getNodeID(), false);

}

From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req/*from   ww  w.jav a  2s.c o  m*/
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
        Object o = parseObject(req);
        if (filterByCreator) {
            String creator = getRequestCreator(req);
            setCreator(o, creator);
        }
        Key key = validateCreate(o);
        // try adding
        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            if (em.find(getObjectClass(), key) != null)
                throw new RequestException(HttpServletResponse.SC_CONFLICT,
                        "object already exists (" + key + ")");
            em.persist(o);
            et.commit();
            logger.info("Added " + o);
        } finally {
            if (et.isActive())
                et.rollback();
            em.close();
        }
        resp.setCharacterEncoding(ENCODING);
        resp.setContentType(JSON_MIME_TYPE);
        Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
        JSONWriter jw = new JSONWriter(w);
        listObject(jw, o);
        w.close();
    } catch (RequestException e) {
        resp.sendError(e.getErrorCode(), e.getMessage());
    } catch (Exception e) {
        logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Invokes a rollback on an entity transaction and a following {@code begin()},
 * only if it has been marked (using {@code setRollbackOnly()}).
 *
 * @param txParam a transaction to be rewinded
 *///from   w ww.jav a2s  .  c om
private void rewindTransaction(final EntityTransaction txParam) {
    if (txParam.isActive()) {
        if (txParam.getRollbackOnly()) {
            txParam.rollback();
            txParam.begin();
        }
    } else
        txParam.begin();
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEventWithMetadata(long eventId, Properties caProperties)
        throws SchedulerServiceDatabaseException, NotFoundException {
    if (caProperties == null) {
        caProperties = new Properties();
    }/*from   w ww  .j a v a  2  s  .c  om*/
    String caSerialized;
    try {
        caSerialized = serializeProperties(caProperties);
    } catch (IOException e) {
        logger.error("Could not serialize properties: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID: " + eventId + " does not exist");
        }
        entity.setCaptureAgentMetadata(caSerialized);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        logger.error("Event with ID '{}' does not exist", eventId);
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event metadata: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java

@Override
public void deleteComment(String eventId, long commentId)
        throws NotFoundException, EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from   www.  ja v  a 2 s.co m
        tx.begin();
        EventCommentDto event = getEventComment(eventId, commentId, em);
        if (event == null)
            throw new NotFoundException(
                    "Event comment with ID " + eventId + " and " + commentId + " does not exist");

        em.remove(event);
        tx.commit();
        sendMessageUpdate(eventId);
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete event comment: {}", ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();

        throw new EventCommentDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}