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.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 w  w.j a v a  2 s. c om
        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:nl.b3p.kaartenbalie.service.MapFileListener.java

private void saveServiceProvider(String wmsUrl, String name) {
    Object identity = null;/* ww w .  j a v a 2 s.com*/
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);

        EntityTransaction tx = em.getTransaction();
        tx.begin();

        try {
            String getCap = "&service=WMS&request=GetCapabilities&version=1.1.1";

            Long number = getUniqueAbbr(name, em);
            String abbr = name + number;

            ServiceProvider saveServiceProvider = WmsServerAction.saveServiceProvider(wmsUrl + getCap, null,
                    name, abbr, em);
            Organization org = (Organization) em.createQuery("FROM Organization WHERE name = :name")
                    .setParameter("name", organization).getSingleResult();
            WmsServerAction.addAllLayersToGroup(org, saveServiceProvider, em);

            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            log.error("Kan nieuwe server niet posten", ex);
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:de.peterspan.csv2db.converter.location.LocationConverter.java

@Override
protected Void doInBackground() throws Exception {
    EntityTransaction tx = null;
    try {/* w  w w  . ja v  a  2  s .  c om*/
        tx = entityManager.getTransaction();
        tx.begin();
        List<String[]> allLines = readFile();

        double increment = 100.0 / allLines.size();
        double progress = 0.0;
        // Removing the header
        // Remove the empty line
        for (String[] line : allLines) {
            progress = progress + increment;
            setProgress((int) Math.round(progress));
            if (line[0].equals("Standort-Nr.")) {
                continue;
            }
            if (line[0].equals("")) {
                continue;
            }
            readLine(line);

        }

        entityManager.flush();
        tx.commit();
    } catch (HibernateException he) {
        if (tx != null) {
            tx.rollback();
        }
    }

    return null;
}

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   w  w w .  j a  v a2s  .  c  om
    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.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public UserAction addUserTrackingEvent(UserAction a) throws UserTrackingException {
    EntityManager em = null;/* www  .  j a  v  a 2s  . co  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(a);
        tx.commit();
        return a;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *//*from w w w  .  ja v  a 2  s  .  c om*/
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        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
 *
 *//*ww w  .jav  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: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  .j  a  v  a  2  s . c o m*/
        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: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  w w .  ja  v  a2  s  .co m*/
    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:it.infn.ct.futuregateway.apiserver.v1.ApplicationService.java

/**
 * Removes the application. Delete the application only if there are not
 * tasks associated with it because tasks must be associated with an
 * application./* w w w. j a va 2s  . c  o m*/
 * <p>
 * Applications with associated tasks can only be disabled to avoid future
 * execution of new tasks. Nevertheless, a task can be associated with a
 * disabled application and in this case will stay waiting until the
 * application is enabled.
 *
 * @param id Id of the application to remove
 */
@DELETE
public final void deleteApp(@PathParam("id") final String id) {
    Application app;
    EntityManager em = getEntityManager();
    try {
        app = em.find(Application.class, id);
        if (app == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id)
                    .setMaxResults(1).getResultList();
            if (taskForApp == null || taskForApp.isEmpty()) {
                em.remove(app);
            } else {
                log.info("Application " + id + " has tasks and cannot be" + " deleted");
                throw new WebApplicationException(
                        "The application cannot " + "be removed because there are associated tasks",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the application");
            throw new InternalServerErrorException("Error to remove " + "the application " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the application list");
        log.error(re);
        throw new BadRequestException("Application '" + id + "' " + "does not exist!");
    } finally {
        em.close();
    }
}