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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an AnnotationStatus//w  ww .  j  a v  a  2  s .co  m
 * @param label
 * @param comment
 * @return
 */
public boolean createAnnotationStatus(String label, String comment, String color, JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            AnnotationStatus annotationstatus = (AnnotationStatus) em
                    .createQuery("from AnnotationStatus where label = ?").setParameter(1, label)
                    .getSingleResult();
            tx.commit();
            if (annotationstatus != null) {
                System.out.println(
                        "[CreateAnnotationStatus.createAnnotationStatus] this status already exists. Status : "
                                + label);
                return false;
            }
        } catch (Exception e) {
            tx.rollback();
            System.out.println(
                    "[CreateAnnotationStatus.createAnnotationStatus] this status doesn't already exist. Status : "
                            + label + " is gonna be created.");
        }
        try {
            tx.begin();
            em.persist(_as);
            tx.commit();
            //    em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}

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

/**
 * Saves publisher(s) to the persistence layer. This method is specific
 * to jUDDI. Administrative privilege required.
 *
 * @param body//from w  ww .  j  a  v  a2s  . c om
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 */
public PublisherDetail savePublisher(SavePublisher body) throws DispositionReportFaultMessage {

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

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

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

        PublisherDetail result = new PublisherDetail();

        List<org.apache.juddi.api_v3.Publisher> apiPublisherList = body.getPublisher();
        for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) {

            org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher();

            MappingApiToModel.mapPublisher(apiPublisher, modelPublisher);

            Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a list of Annotation according to the specified label
 * @param label//  w  w w . j ava 2s .c o  m
 * @return
 */
public List<Annotation> retrieveAnnotation(String label) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        //List docs = em.createQuery("from Annotation where label = '" + label + "'").getResultList();
        List<Annotation> docs = ((List<Annotation>) em.createQuery("from Annotation where label = ?")
                .setParameter(1, label).getResultList());
        tx.commit();
        return docs;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotation] unable to retrieve Annotation" + " label : "
                + label + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

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 2 s  . c om*/
    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 publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required. 
 * @param body// w  w  w. j  av a2  s.com
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage 
 */
public PublisherDetail getPublisherDetail(GetPublisherDetail body) throws DispositionReportFaultMessage {

    new ValidatePublisher(null).validateGetPublisherDetail(body);

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

        this.getEntityPublisher(em, body.getAuthInfo());

        PublisherDetail result = new PublisherDetail();

        List<String> publisherIdList = body.getPublisherId();
        for (String publisherId : publisherIdList) {
            org.apache.juddi.model.Publisher modelPublisher = null;
            try {
                modelPublisher = em.find(org.apache.juddi.model.Publisher.class, publisherId);
            } catch (ClassCastException e) {
            }
            if (modelPublisher == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.PublisherNotFound", publisherId));
            }

            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();
    }

}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an AnnotationStatus that specifies another AnnotationStatus
 * @param label/*  w w w.ja v  a  2s  .co  m*/
 * @param comment
 * @param father
 * @return
 */
public boolean createAnnotationStatusChild(String label, String comment, String color, AnnotationStatus father,
        JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setFather(father);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (father.getId() != null) {
                AnnotationStatus _synchro_father = em.find(AnnotationStatus.class, father.getId());
                if (_synchro_father != null)
                    _as.setFather(_synchro_father);
            }
            em.persist(_as);
            tx.commit();
            //      em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}

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

public void deleteBinding(DeleteBinding body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//ww  w .  j a va2 s.com
        tx.begin();

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

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

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

            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService()
                    .setModifiedIncludingChildren(new Date());
            // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BINDING, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BINDING, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        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  ww.  j  av 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.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from   w  w w .jav a  2 s. c om*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#init(java.lang.String)
 */
@Override
public String init(final String dataSourceID) throws DeltaIndexingException {
    if (dataSourceID == null) {
        throw new DeltaIndexingException("parameter dataSourceID is null");
    }

    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao dao = findDataSourceDao(em, dataSourceID);
            if (dao != null && dao.getSessionId() != null) {
                throw new DeltaIndexingException(
                        "data source " + dataSourceID + " is already locked by another session");
            }

            final String sessionId = UUID.randomUUID().toString();

            final DataSourceDao lockedDao = new DataSourceDao(dataSourceID, sessionId);
            // lock the data source
            if (dao == null) {
                em.persist(lockedDao);
            } else {
                em.merge(lockedDao);
            }

            // reset visited and modified flags
            resetFlags(em, dataSourceID);

            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("created session " + sessionId + " for data source: " + dataSourceID);
            }
            return sessionId;
        } catch (final DeltaIndexingException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error initializing delta indexing for data source: " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * handle the update and save process.//from   w  w  w .ja va 2 s  .  c o  m
 *
 * @param entity the newsdrilldown entity
 * @throws Exception the exception
 */
private void handle(UXBEntity entity) throws Exception {
    /**
     * Due to a hibernate problem when updating or saving a newsdrilldown with
     * related categories we have to perform these step for saving the newsdrilldown
     *
     * 1. save/update all categories and remove them from the newsdrilldown
     *    1.1 save/update all metaCategories and remove them from the categories
     *    1.2 save the categories
     *    1.3 read all metaCategories to the categories
     *    1.4 save the categories again to create the relations
     * 2. save the newsdrilldown
     * 3. read all categories to the newsdrilldown
     */

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        News news = buildNews(entity);
        List<Long> categories = new ArrayList<Long>();

        /*
        * 1. update or save all categories
        * Steps 1.1 - 1.4
        */
        if (news.getCategories() != null && !news.getCategories().isEmpty()) {
            for (NewsCategory cat : news.getCategories()) {
                cat = saveNewsCategory(cat);
                if (!categories.contains(cat.getFs_id())) {
                    categories.add(cat.getFs_id());
                }
            }
            news.setCategories(new ArrayList<NewsCategory>());
        }

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

        // 2. save the newsdrilldown
        news = saveNews(news, em);

        // 3. read all categories to the newsdrilldown
        if (!categories.isEmpty()) {
            for (Long cat : categories) {
                NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em);
                news.getCategories().add(ncat);
            }
        }

        tx.commit();

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}