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:nl.b3p.kaartenbalie.reporting.ReportThread.java

public void run() {

    try {/*w  w  w  .ja  va2  s .  co  m*/
        EntityTransaction tx = em.getTransaction();

        long processStart = System.currentTimeMillis();

        Report report = new Report();
        tx = em.getTransaction();
        tx.begin();
        try {
            /*
             * Store all the parameters in the report...
             */
            report.setOrganization(organization);
            report.setStartDate(startDate);
            report.setEndDate(endDate);
            report.setName(name);
            String mime = (String) CastorXmlTransformer.getContentTypes().get(type);
            report.setReportMime(mime);

            em.persist(report);
            em.flush();
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            throw ex;
        }

        try {
            Parameters parameters = new Parameters();
            parameters.setDateEnd(new org.exolab.castor.types.Date(endDate));
            parameters.setDateStart(new org.exolab.castor.types.Date(startDate));
            parameters.setId(Integer.toString(report.getId().intValue()));
            parameters.setOrganization(organization.getName());
            parameters.setTimeStamp(new Date());

            MonitorReport mr = createMonitorReport();

            Long procTime = new Long(System.currentTimeMillis() - processStart);
            parameters.setProcessingTime(procTime.longValue());
            mr.setParameters(parameters);
            report.setProcessingTime(procTime);

            if (type.equalsIgnoreCase(CastorXmlTransformer.HTML)) {
                CastorXmlTransformer cxt = new CastorXmlTransformer(xsl, MyEMFDatabase.localPath());
                report.setReportXML(cxt.createHtml(mr));
            } else {
                CastorXmlTransformer cxt = new CastorXmlTransformer();
                report.setReportXML(cxt.createXml(mr));
            }
        } catch (Exception e) {
            StringBuffer rerror = new StringBuffer();
            rerror.append("<error>");
            rerror.append(e.getLocalizedMessage());

            StackTraceElement[] ste = e.getStackTrace();
            if (ste.length > 0) {
                rerror.append(" at ");
                rerror.append(ste[0].toString());
            }
            rerror.append("</error>");
            report.setReportXML(rerror.toString());
        }

        tx = em.getTransaction();
        tx.begin();
        try {
            em.merge(report);
            em.flush();
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            throw ex;
        }
    } catch (Exception e) {
        log.error("", e);
    } finally {
        log.debug("Closing local entity manager ......");
        if (em != null && em.isOpen()) {
            em.close();
        }
        em = null;
    }
}

From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public void deleteTheme(long id) throws ThemesServiceDatabaseException, NotFoundException {
    EntityManager em = null;/*  w ww . j  a va 2  s .c  o  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        ThemeDto themeDto = getThemeDto(id, em);
        if (themeDto == null)
            throw new NotFoundException("No theme with id=" + id + " exists");

        tx = em.getTransaction();
        tx.begin();
        em.remove(themeDto);
        tx.commit();
        messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue,
                ThemeItem.delete(id));
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete theme '{}': {}", id, ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();
        throw new ThemesServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

@Override
public final <T> void remove(final T entity) throws UnauthorizedAccessAttemptException {
    T managedEntity = entity;/*  www .  ja  va 2s  .co  m*/
    if (!entityManager.contains(managedEntity)) {
        managedEntity = EntityManagerHelper.obtainManagedEntity(entityManager, entity);
    }
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        entityManager.remove(managedEntity);
    } catch (RuntimeException re) {
        LOGGER.error("Failed to remove entity", re);
        throw re;
    } finally {
        finalizeEntityManagerAccess("remove", transaction, entity);
    }
    setIdOfEntity2Null(entity.getClass(), entity);
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

@Override
public final <T> T persist(T entity) throws UnauthorizedAccessAttemptException {
    //persist()//from   w w  w. ja v  a 2 s  .  co m
    //auf internes contains() pruefen, falls "TRUE" throw EntityExistsException() 
    if (contains(entity)) {
        throw new EntityExistsException("Cannot persist existing entity");
    }
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        entityManager.persist(entity);
    } catch (RuntimeException re) {
        LOGGER.error("Failed to persist entity", re);
        throw re;
    } finally {
        finalizeEntityManagerAccess("persist", transaction, entity);
    }
    return entity;
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

@Override
public final <T> T update(T entity) throws UnauthorizedAccessAttemptException, EntityNotFoundException {
    //1. @ID pruefen (wenn NULL dann ist Entity neu, EntityNotFoundException werfen)
    //    setID() als protected in allen Entities um manuelles setzen zu vermeiden!!
    //2. Wenn @ID gesetzt, dann "return merge(Entity)"
    if (!contains(entity)) {
        throw new EntityNotFoundException("Can't update entity '" + entity + "'! Entity is not in database.");
    }// w ww .j a v a  2 s .c om
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        return entityManager.merge(entity);
    } catch (RuntimeException re) {
        LOGGER.error("Failed to update entity", re);
        throw re;
    } finally {
        finalizeEntityManagerAccess("update", transaction, entity);
    }
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

@Override
public final <T> T save(final T entity) throws UnauthorizedAccessAttemptException {
    //1. persist(Entity) falls EntityExistException
    //2. impl.merge(E')
    T savedEntity = entity;/* ww  w.  j  a v  a2 s .  c om*/
    try {
        persist(entity);
    } catch (EntityExistsException eee) {
        EntityTransaction transaction = entityManager.getTransaction();
        try {
            transaction.begin();
            savedEntity = entityManager.merge(entity);
        } catch (RuntimeException re) {
            LOGGER.error("Failed to save entity", re);
            throw re;
        } finally {
            finalizeEntityManagerAccess("save -> merge", transaction, entity);
        }
    }
    return savedEntity;
}

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

/**
 * Completely deletes a tModel from the persistence layer.
 * Administrative privilege required. All entities that reference this tModel
 * will no longer be able to use the tModel if jUDDI Option Enforce referential Integrity is enabled.<br>
 * Required permission, you must be am administrator
 * {@link Property#JUDDI_ENFORCE_REFERENTIAL_INTEGRITY}
 * @param body//from w  w w .j  a v  a2  s  .  co m
 * @throws DispositionReportFaultMessage 
 */
public void adminDeleteTModel(DeleteTModel body) throws DispositionReportFaultMessage {

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

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

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

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

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

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

/**
 * Delete's a client's subscription information. This is typically used for
 * server to server subscriptions/*  ww  w .ja v  a  2  s .c  o m*/
 * Administrative privilege required.
 * @param body
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public void deleteClientSubscriptionInfo(DeleteClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {

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

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

        new ValidateClientSubscriptionInfo(publisher).validateDeleteClientSubscriptionInfo(em, body);

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

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

}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Path("{id}/markAllRead")
public Response markAllRead(@Context SecurityContext context, @PathParam("id") int feedId,
        @QueryParam("allBefore") long timeMillis) {
    EntityManager em;/*from   w  w w  .  jav  a  2s  . co  m*/
    EntityTransaction tx;
    User user;
    Feed feed;
    Date newDate;

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();

    tx.begin();

    try {
        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        newDate = new Date(timeMillis);
        if (feed.getReadAllBefore() == null || feed.getReadAllBefore().before(newDate)) {
            feed.setReadAllBefore(newDate);
            em.persist(feed);
        }

        em.createQuery(
                "delete from FeedItem fi where fi.feed = :feed and fi.data.date < :date and not fi.starred and not fi.exported and size(fi.tags) = 0")
                .setParameter("feed", feed).setParameter("date", newDate).executeUpdate();

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

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//from   w  ww  .  j a v a 2s  . 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();
    }
}