Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

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

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

Usage

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

@Deprecated
private Node getNode(String messageSender) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    try {/*from www. j av a  2  s  .  c  o m*/
        tx = em.getTransaction();
        tx.begin();
        Node api = new Node();
        org.apache.juddi.model.Node find = em.find(org.apache.juddi.model.Node.class, messageSender);
        if (find != null) {
            MappingModelToApi.mapNode(find, api);
        }
        tx.commit();
        return api;
    } catch (Exception ex) {
        log.error("error", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        em.close();
    }
    return null;
}

From source file:de.iai.ilcd.model.dao.SourceDao.java

/**
 * Concrete implementation required for saving of digital files
 *//*  www  . ja v a 2 s  .c o m*/
@Override
public boolean checkAndPersist(Source source, PersistType pType, PrintWriter out) {
    EntityManager em = PersistenceUtil.getEntityManager();

    Source existingSource = this.getByUuid(source.getUuid().getUuid());
    if (existingSource != null) {
        if (pType == PersistType.ONLYNEW) {
            out.println(
                    "Warning: source data set with this uuid already exists in database; will ignore this data set");
            return false;
        }
    }

    EntityTransaction t = em.getTransaction();
    try {
        t.begin();
        if (existingSource != null && (pType == PersistType.MERGE)) {
            // delete first the existing one, we will use the new one
            if (out != null) {
                out.println(
                        "Notice: source data set with this uuid already exists in database; will merge this data set");
            }
            em.remove(existingSource);
            this.deleteDigitalFiles(source);
        }

        em.persist(source);

        t.commit();

        if (!super.setMostRecentVersionFlags(source.getUuidAsString())) {
            return false;
        }

        if (source != null && source.getId() != null) {
            if (!this.saveDigitalFiles(source, out)) {
                if (out != null) {
                    out.println(
                            "Warning: couldn't save all files of this source data set into database file directory: see messages above");
                }
            }
        }
        return true;

    } catch (Exception e) {
        if (out != null) {
            out.println("Can't save source data file to database because of: " + e.getMessage());
        }
        t.rollback();
        return false;
    }
}

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 a  v  a2  s .  c  om
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:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}//from  w  w w.j a  va  2s.c  o m
 */
@Override
public void removeRecord(final String id) throws RecordStorageException {
    if (id == null) {
        throw new RecordStorageException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final RecordDao dao = findRecordDao(em, id);
            if (dao != null) {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    em.remove(dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new RecordStorageException(e, "error removing record id: " + id);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove record id: " + id + ". no record with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java

/**
 * Stores the given BinaryStorageDao, updating an existing one or creating a new one.
 *
 * @param dao//from  w w w.ja  v a 2s.c o  m
 *          the BinaryStorageDao to store
 * @throws BinaryStorageException
 *           if any error occurs
 */
// TODO: don't know if this synchronize is good, was needed to pass the JUNit test TestConcurrentBSSAccessJPA
private synchronized void store(final BinaryStorageDao dao) throws BinaryStorageException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            if (findBinaryStorageDao(em, dao.getId()) == null) {
                em.persist(dao);
            } else {
                em.merge(dao);
            }
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("stored content of id:" + dao.getId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new BinaryStorageException(e, "error storing record id: " + dao.getId());
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java

public void printMetaCats() throws Exception {
    System.out.println("\n\n\n");
    EntityManager em = emf.createEntityManager();
    try {/*from  w  w w  .  ja  v a2 s  .c om*/
        EntityTransaction et = em.getTransaction();
        et.begin();
        Query query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString());
        List<NewsMetaCategory> metaList = query.getResultList();
        for (NewsMetaCategory temp : metaList) {
            System.out.println("META: " + temp.getName() + " / " + temp.getLastmodified());
        }
        et.commit();
    } finally {
        em.close();
    }
    System.out.println("\n\n\n");

}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java

/**
 * Before test.//  w  w  w. j  av a 2  s.c  o  m
 *
 * @throws Exception the exception
 */
@Before
public void beforeTest() throws Exception {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction et = em.getTransaction();
        et.begin();
        Query query = em.createQuery(new StringBuilder().append("SELECT x FROM news x").toString());
        List<News> newsList = query.getResultList();
        for (News news : newsList) {
            em.remove(news);
        }

        query = em.createQuery(new StringBuilder().append("SELECT x FROM category x").toString());
        List<NewsCategory> catList = query.getResultList();
        for (NewsCategory temp : catList) {
            em.remove(temp);
        }

        query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString());
        List<NewsMetaCategory> metaList = query.getResultList();
        for (NewsMetaCategory temp : metaList) {
            em.remove(temp);
        }
        et.commit();
    } finally {
        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 w  ww  . ja  v a 2 s.c o 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();
    }
}

From source file:org.sigmah.server.schedule.export.AutoDeleteJob.java

public void execute(JobExecutionContext executionContext) throws JobExecutionException {
    final JobDataMap dataMap = executionContext.getJobDetail().getJobDataMap();
    final EntityManager em = (EntityManager) dataMap.get("em");
    final Log log = (Log) dataMap.get("log");
    final Injector injector = (Injector) dataMap.get("injector");
    EntityTransaction tx = null;

    try {/*from   w w  w  .  j  a v a2  s. c om*/

        // Open transaction
        /*
         *  NOTE: it is impossible to use @Transactional for this method
         *  The reason is link{TransactionalInterceptor} gets EntityManager 
         *  from the injector; this is server thread, so, EM is out of scope 
         */
        tx = em.getTransaction();
        tx.begin();

        final GlobalExportDAO exportDAO = new GlobalExportHibernateDAO(em);

        final List<GlobalExportSettings> settings = exportDAO.getGlobalExportSettings();
        for (final GlobalExportSettings setting : settings) {

            /*
             * Check for auto delete schedule 
             */

            //skip if no delete schedule is specified
            if (setting.getAutoDeleteFrequency() == null || setting.getAutoDeleteFrequency() < 1)
                continue;

            final Calendar scheduledCalendar = Calendar.getInstance();
            // subtract months from current date 
            scheduledCalendar.add(Calendar.MONTH, 0 - setting.getAutoDeleteFrequency().intValue());

            // get older exports
            List<GlobalExport> exports = exportDAO.getOlderExports(scheduledCalendar.getTime(),
                    setting.getOrganization());
            //delete exports and their contents
            for (final GlobalExport export : exports) {
                final List<GlobalExportContent> contents = export.getContents();
                for (GlobalExportContent content : contents) {
                    em.remove(content);
                }
                em.remove(export);
            }

        }
        tx.commit();

        log.info("Scheduled DELETE of global exports fired");

    } catch (Exception ex) {
        if (tx != null && tx.isActive())
            tx.rollback();
        log.error("Scheduled global export job failed : " + ex.getMessage());
        ex.printStackTrace();
    }
}

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

@Override
public Comment updateComment(String eventId, Comment comment) throws EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w  ww .jav a  2  s .c  o  m*/
        tx.begin();
        CommentDto updatedComment = CommentDatabaseUtils.mergeComment(comment, em);

        EventCommentDto dto = getEventComment(eventId, updatedComment.getId(), em);
        if (dto == null) {
            dto = new EventCommentDto(eventId, updatedComment, securityService.getOrganization().getId());
            em.persist(dto);
        } else {
            dto.setComment(updatedComment);
            em.merge(dto);
        }
        tx.commit();
        comment = updatedComment.toComment(userDirectoryService);
        sendMessageUpdate(eventId);
        return comment;
    } catch (Exception e) {
        logger.error("Could not update or store comment: {}", ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();

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