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:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void storeEvents(DublinCoreCatalog... events) throws SchedulerServiceDatabaseException {
    EntityManager em = null;/*from   w w w  .ja v a2s.c  o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        for (DublinCoreCatalog event : events) {
            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);
            }
            EventEntity entity = new EventEntity();
            entity.setEventId(eventId);
            entity.setEventDublinCore(dcXML);
            em.persist(entity);
        }
        tx.commit();
    } catch (SchedulerServiceDatabaseException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store events: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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// w ww.ja va2 s.  c o  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.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#storeOrganization(org.opencastproject.security.api.Organization)
 *//*ww  w  .ja  v  a2s .c  o  m*/
@Override
public void storeOrganization(Organization org) throws OrganizationDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organizationEntity = getOrganizationEntity(org.getId());
        if (organizationEntity == null) {
            JpaOrganization organization = new JpaOrganization(org.getId(), org.getName(), org.getServers(),
                    org.getAdminRole(), org.getAnonymousRole(), org.getProperties());
            em.persist(organization);
        } else {
            organizationEntity.setName(org.getName());
            organizationEntity.setAdminRole(org.getAdminRole());
            organizationEntity.setAnonymousRole(org.getAnonymousRole());
            organizationEntity.setServers(org.getServers());
            organizationEntity.setProperties(org.getProperties());
            em.merge(organizationEntity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:nl.b3p.kaartenbalie.reporting.ReportThread.java

public void run() {

    try {/* ww w.  j av a 2s.  c  o  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.apache.juddi.api.impl.UDDIPublicationImpl.java

public List<AssertionStatusItem> getAssertionStatusReport(String authInfo, CompletionStatus completionStatus)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  w w  w  . j  av a  2  s.  co  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        List<org.uddi.api_v3.AssertionStatusItem> result = PublicationHelper
                .getAssertionStatusItemList(publisher, completionStatus, em);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, QueryStatus.SUCCESS, procTime);

        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.opencastproject.userdirectory.JpaGroupRoleProvider.java

/**
 * Adds or updates a group to the persistence.
 *
 * @param group//w ww  .  java 2s  .  c om
 *          the group to add
 */
public void addGroup(final JpaGroup group) {
    Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf);
    JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf);

    JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(),
            roles, group.getMembers());

    // Then save the jpaGroup
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(),
                jpaGroup.getOrganization().getId(), emf);
        if (foundGroup == null) {
            em.persist(jpaGroup);
        } else {
            foundGroup.setName(jpaGroup.getName());
            foundGroup.setDescription(jpaGroup.getDescription());
            foundGroup.setMembers(jpaGroup.getMembers());
            foundGroup.setRoles(roles);
            em.merge(foundGroup);
        }
        tx.commit();
        messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue,
                GroupItem.update(JaxbGroup.fromGroup(jpaGroup)));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:info.san.books.app.model.listener.LivreListener.java

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

    EntityTransaction t = em.getTransaction();

    t.begin();/*from   w w w.j  a  va  2  s .  c  o  m*/

    LivreEntry entry = new LivreEntry();
    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.getSagaId() != null && !e.getSagaId().trim().isEmpty()) {
        SagaEntry saga = em.getReference(SagaEntry.class, e.getSagaId());
        entry.setSaga(saga);
    }

    em.persist(entry);

    t.commit();
}

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

public DeregisterImageResponseType deregister(DeregisterImageType request) throws EucalyptusCloudException {
    DeregisterImageResponseType reply = request.getReply();

    EntityTransaction tx = Entities.get(ImageInfo.class);
    try {//from w  w  w . j  a  va 2s.  c o  m
        ImageInfo imgInfo = Entities
                .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId())));
        if (!canModifyImage(imgInfo)) {
            throw new EucalyptusCloudException("Not authorized to deregister image");
        }
        Images.deregisterImage(imgInfo.getDisplayName());
        tx.commit();
        return reply;
    } catch (NoSuchImageException | NoSuchElementException ex) {
        throw new ClientComputeException("InvalidAMIID.NotFound",
                "The image ID '" + request.getImageId() + "' does not exist");
    } catch (InstanceNotTerminatedException | ConstraintViolationException re) {
        throw new ClientComputeException("InvalidAMIID.Unavailable",
                "The image ID '" + request.getImageId() + "' is no longer available");
    } catch (TransactionException ex) {
        if (ex.getCause() instanceof NoSuchElementException)
            throw new ClientComputeException("InvalidAMIID.NotFound",
                    "The image ID '" + request.getImageId() + "' does not exist");
        else
            throw new EucalyptusCloudException(ex);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
}

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

public void deleteMessageTemplate(Long id) throws MailServiceException, NotFoundException {
    EntityManager em = null;/* w  w  w.  jav a 2 s.com*/
    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 ava2  s .  c o  m*/
    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();
    }
}