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.api.impl.UDDIInquiryImpl.java

public BindingDetail findBinding(FindBinding body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from w w w  . j  av a 2 s  .co  m
        new ValidateInquiry(null).validateFindBinding(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        List<?> keysFound = InquiryHelper.findBinding(body, findQualifiers, em);

        if (keysFound != null && keysFound.size() == 0) {
            if (body.getServiceKey() != null) {
                // Check that we were passed a valid serviceKey per
                // 5.1.12.4 of the UDDI v3 spec
                String serviceKey = body.getServiceKey();
                org.apache.juddi.model.BusinessService modelBusinessService = null;
                try {
                    modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey);
                } catch (ClassCastException e) {
                    logger.info("uh oh!", e);
                }
                if (modelBusinessService == null)
                    throw new InvalidKeyPassedException(
                            new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey));

            }
        }
        BindingDetail result = InquiryHelper.getBindingDetailFromKeys(body, findQualifiers, em, keysFound);
        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.SUCCESS, procTime);

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

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteAllProducts() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();

    Query q = entityManager.createQuery("DELETE FROM Product ");
    q.executeUpdate();//from w w w .j av a2 s  .co m
    entityManager.flush();

    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteAllUsers() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();

    Query q = entityManager.createQuery("DELETE FROM FStoreUser ");
    q.executeUpdate();//from  w w  w . j  a  v  a 2 s  .  co  m
    entityManager.flush();

    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public Product updateProduct(Product bm) {
    logger.info("================= updateProduct ==================");
    logger.info("bmgetId=" + bm.getId());
    logger.info("bm getName= " + bm.getName());
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();
    Product resis = entityManager.merge(bm);
    entityTransaction.commit();//from ww  w .j  ava  2s . co  m

    return resis;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteAllCategories() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();

    Query q = entityManager.createQuery("DELETE FROM Category");
    q.executeUpdate();/* w  ww  .  j a  v a  2  s .c  o  m*/
    entityManager.flush();

    entityTransaction.commit();

}

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

public ServiceList findService(FindService body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from   w  w  w . j  a v  a2 s . c om
        new ValidateInquiry(null).validateFindService(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        List<?> keysFound = InquiryHelper.findService(body, findQualifiers, em);

        if (keysFound.size() == 0) {
            if (body.getBusinessKey() != null) {
                // Check that we were passed a valid businessKey per
                // 5.1.12.4 of the UDDI v3 spec
                String businessKey = body.getBusinessKey();
                org.apache.juddi.model.BusinessEntity modelBusinessEntity = null;
                try {
                    modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey);
                } catch (ClassCastException e) {
                }
                if (modelBusinessEntity == null) {
                    throw new InvalidKeyPassedException(
                            new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey));
                }
            }
        }

        ServiceList result = InquiryHelper.getServiceListFromKeys(body, findQualifiers, em, keysFound);

        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.SUCCESS, procTime);

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

From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req//from   ww  w . j  a v a  2 s  . c  o  m
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
        Object o = parseObject(req);
        if (filterByCreator) {
            String creator = getRequestCreator(req);
            setCreator(o, creator);
        }
        Key key = validateCreate(o);
        // try adding
        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            if (em.find(getObjectClass(), key) != null)
                throw new RequestException(HttpServletResponse.SC_CONFLICT,
                        "object already exists (" + key + ")");
            em.persist(o);
            et.commit();
            logger.info("Added " + o);
        } finally {
            if (et.isActive())
                et.rollback();
            em.close();
        }
        resp.setCharacterEncoding(ENCODING);
        resp.setContentType(JSON_MIME_TYPE);
        Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
        JSONWriter jw = new JSONWriter(w);
        listObject(jw, o);
        w.close();
    } catch (RequestException e) {
        resp.sendError(e.getErrorCode(), e.getMessage());
    } catch (Exception e) {
        logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public UserSession saveUserSession(UserSession userSession) {
    logger.info("Will userSession = " + userSession.getUsername());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();

    FStoreUser u = entityManager.find(FStoreUser.class, userSession.getUser().getId());
    userSession.setUser(u);/*from w w  w .ja  v a 2s  .  c  o  m*/

    logger.info("Will userSession = " + u.toString());

    entityManager.persist(u);
    entityManager.persist(userSession);
    entityManager.flush();
    entityTransaction.commit();

    return userSession;

}

From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

private void populateSeriesData() throws SearchServiceDatabaseException {
    EntityManager em = null;/*from  w w  w .  ja  va 2 s .co  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        TypedQuery<SearchEntity> q = (TypedQuery<SearchEntity>) em.createNamedQuery("Search.getNoSeries");
        List<SearchEntity> seriesList = q.getResultList();
        for (SearchEntity series : seriesList) {
            String mpSeriesId = MediaPackageParser.getFromXml(series.getMediaPackageXML()).getSeries();
            if (StringUtils.isNotBlank(mpSeriesId) && !mpSeriesId.equals(series.getSeriesId())) {
                logger.info("Fixing missing series ID for episode {}, series is {}", series.getMediaPackageId(),
                        mpSeriesId);
                series.setSeriesId(mpSeriesId);
                em.merge(series);
            }
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update media package: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void saveUser(FStoreUser bu) {
    logger.info("Will save FStoreUser = " + bu.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();

    entityManager.persist(bu);/*from w  ww  .ja v  a 2s.c  o m*/
    //      List<ApplicationMetadata> apps = bu.getApps();
    //      for (ApplicationMetadata app : apps) {         
    //         entityManager.persist(app.getCategory());
    //         entityManager.persist(app);
    //      }
    //      
    //      List<BunMetadata> buns = bu.getBuns() ;
    //      for (BunMetadata bun : buns) {         
    //         entityManager.persist(bun.getCategory());
    //         entityManager.persist(bun);
    //      }

    entityManager.flush();
    entityTransaction.commit();

}