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.apache.juddi.api.impl.UDDIPublicationImpl.java

public void setPublisherAssertions(String authInfo, Holder<List<PublisherAssertion>> publisherAssertion)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

        new ValidatePublish(publisher).validateSetPublisherAssertions(em, publisherAssertion);

        List<?> businessKeysFound = null;
        businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);

        // First, wipe out all previous assertions associated with this publisher
        DeletePublisherAssertionByBusinessQuery.delete(em, businessKeysFound);

        // Slate is clean for all assertions involving this publisher, now we simply need to add the new ones (and they will all be "new").
        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = publisherAssertion.value;
        for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) {

            org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion();

            MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion);

            org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class,
                    modelPubAssertion.getId().getFromKey());
            org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class,
                    modelPubAssertion.getId().getToKey());
            modelPubAssertion.setBusinessEntityByFromKey(beFrom);
            modelPubAssertion.setBusinessEntityByToKey(beTo);

            modelPubAssertion.setFromCheck("false");
            modelPubAssertion.setToCheck("false");

            em.persist(modelPubAssertion);

            if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey()))
                modelPubAssertion.setFromCheck("true");
            if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey()))
                modelPubAssertion.setToCheck("true");

        }

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

From source file:org.apache.juddi.validation.ValidatePublish.java

/**
 * Validates that a tmodel key is registered Alex O'Ree
 *
 * @param tmodelKey//  w  w w .  j  a  v  a2s  .co m
 * @param em
 * @throws ValueNotAllowedException
 * @see org.apache.juddi.config.Install
 * @since 3.1.5
 */
private boolean verifyTModelKeyExistsAndChecked(String tmodelKey, Configuration config)
        throws ValueNotAllowedException {
    boolean checked = true;
    if (tmodelKey == null || tmodelKey.length() == 0) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:types")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:nodes")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_inquiry")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_publication")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_security")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_ownership_transfer")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscription")) {
        return false;
    }
    if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscriptionlistener")) {
        return false;
    }

    if (config == null) {
        log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullConfig"));
        return false;
    }
    boolean checkRef = false;
    try {
        checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false);
    } catch (Exception ex) {
        log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file",
                ex);
    }
    if (checkRef) {
        if (log.isDebugEnabled()) {
            log.debug("verifyTModelKeyExists " + tmodelKey);
        }
        EntityManager em = PersistenceManager.getEntityManager();

        if (em == null) {
            //this is normally the Install class firing up
            log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
        } else {
            //Collections.sort(buildInTmodels);
            //if ((buildInTmodels, tmodelKey) == -1)
            Tmodel modelTModel = null;
            {
                EntityTransaction tx = em.getTransaction();
                try {

                    tx.begin();
                    modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);

                    if (modelTModel == null) {
                        checked = false;
                    } else {
                        for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag()
                                .getKeyedReferences()) {
                            if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getKeyName())) {
                                checked = false;
                                break;
                            }
                        }
                    }

                    tx.commit();

                } finally {
                    if (tx.isActive()) {
                        tx.rollback();
                    }
                    em.close();
                }
                if (modelTModel == null) {
                    throw new ValueNotAllowedException(
                            new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey));
                }
            }
        }
    }
    return checked;
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}/*from w  w w . jav  a  2 s.c  o m*/
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#setMaintenanceStatus(java.lang.String, boolean)
 */
@Override
public void setMaintenanceStatus(String baseUrl, boolean maintenance) throws NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        HostRegistrationJpaImpl reg = fetchHostRegistration(em, baseUrl);
        if (reg == null) {
            throw new NotFoundException("Can not set maintenance mode on a host that has not been registered");
        }
        reg.setMaintenanceMode(maintenance);
        em.merge(reg);
        tx.commit();
        hostsStatistics.updateHost(reg);
    } catch (RollbackException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        if (em != null)
            em.close();
    }
}

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

public void saveSubscription(String authInfo, Holder<List<Subscription>> subscription)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w  w w.  j  a v  a  2  s  .c  om*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);
        new ValidateSubscription(publisher).validateSubscriptions(em, subscription.value);

        List<org.uddi.sub_v3.Subscription> apiSubscriptionList = subscription.value;
        for (org.uddi.sub_v3.Subscription apiSubscription : apiSubscriptionList) {

            org.apache.juddi.model.Subscription modelSubscription = new org.apache.juddi.model.Subscription();

            Object existing = em.find(org.apache.juddi.model.Subscription.class,
                    apiSubscription.getSubscriptionKey());
            if (existing != null) {
                org.apache.juddi.model.Subscription existingEntity = (org.apache.juddi.model.Subscription) existing;
                doRenewal(existingEntity, apiSubscription);
                //carrying over the created and last notified dates if this is a renewal.
                modelSubscription.setCreateDate(existingEntity.getCreateDate());
                modelSubscription.setLastNotified(existingEntity.getLastNotified());
                em.remove(existing);
            } else {
                modelSubscription.setCreateDate(new Date());
            }

            doSubscriptionExpirationDate(apiSubscription);

            MappingApiToModel.mapSubscription(apiSubscription, modelSubscription);

            modelSubscription.setAuthorizedName(publisher.getAuthorizedName());

            // Add the matching keys to the match collection
            List<?> keys = getSubscriptionMatches(apiSubscription.getSubscriptionFilter(), em);
            if (keys != null && keys.size() > 0) {
                for (Object key : keys) {
                    SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String) key);
                    modelSubscription.getSubscriptionMatches().add(subMatch);
                }
            }

            em.persist(modelSubscription);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

private void initExampleData() throws Exception {
    EntityManager em = emf.createEntityManager();
    try {/*ww w  .  j av a 2  s . c  o  m*/
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        User player1 = new User("student@busimu.com", "ssssss", "s", User.Type.STUDENT);
        player1.setStatus(User.Status.ACTIVE);
        User player2 = new User("zhangsan@busimu.com", "123456", "", User.Type.STUDENT);
        player2.setStatus(User.Status.ACTIVE);
        User player3 = new User("lisi@busimu.com", "123456", "?", User.Type.STUDENT);
        player3.setStatus(User.Status.ACTIVE);
        User teacher = new User("teacher@busimu.com", "tttttt", "t", User.Type.TEACHER);
        teacher.setStatus(User.Status.ACTIVE);
        em.persist(player1);
        em.persist(player2);
        em.persist(player3);
        em.persist(teacher);

        Campaign campaign = teacher.createCampagin("", Campaign.Type.COURSE);
        SimMarket south = campaign.addMarket("??");
        SimMarket central = campaign.addMarket("?");
        SimMarket north = campaign.addMarket("?");
        SimMarket east = campaign.addMarket("?");
        SimMarket west = campaign.addMarket("");
        SimCorporation ibm = south.addCorporation("IBM", new Color(128, 128, 255));
        SimCorporation ericsson = south.addCorporation("Ericsson", Color.BLUE);
        SimCorporation oracle = south.addCorporation("Oracle", Color.RED);
        for (int i = 0; i < 8; i++) {
            campaign.addRound();
        }

        player2.addCampaign(campaign);
        player3.addCampaign(campaign);
        em.persist(campaign);

        Team t1 = new Team("anoym1");
        Team t2 = new Team("anoym2");
        Team t3 = new Team("anoym3");
        t1.addCorporation(ibm);
        t2.addCorporation(ericsson);
        t3.addCorporation(oracle);
        em.persist(t1);
        em.persist(t2);
        em.persist(t3);

        Campaign runningCampaign = teacher.createCampagin("", Campaign.Type.COURSE);
        SimMarket m1 = runningCampaign.addMarket("");
        SimMarket m2 = runningCampaign.addMarket("");
        SimMarket m3 = runningCampaign.addMarket("");
        SimCorporation corp1 = m1.addCorporation("", Color.ORANGE);
        for (int i = 0; i < 3; i++) {
            runningCampaign.addRound();
        }
        player1.addCampaign(runningCampaign);
        player2.addCampaign(runningCampaign);
        player3.addCampaign(runningCampaign);
        runningCampaign.setStatus(Campaign.Status.ONGOING);

        Team t11 = new Team("anoym11");
        t11.addCorporation(corp1);
        t11.addUser(player1);
        t11.addUser(player2);
        t11.addUser(player3);
        em.persist(t11);

        tx.commit();
    } finally {
        em.close();
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Internal method to update the service registration state, throwing unwrapped JPA exceptions.
 * //from   ww  w  .  jav a  2  s .  c om
 * @param em
 *          the current entity manager
 * @param registration
 *          the service registration to update
 * @return the updated service registration
 * @throws PersistenceException
 *           if there is an exception thrown while persisting the job via JPA
 * @throws IllegalArgumentException
 */
private ServiceRegistration updateServiceState(EntityManager em, ServiceRegistrationJpaImpl registration)
        throws PersistenceException {
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        ServiceRegistrationJpaImpl fromDb;
        fromDb = em.find(ServiceRegistrationJpaImpl.class, registration.getId());
        if (fromDb == null) {
            throw new NoResultException();
        }
        fromDb.setServiceState(registration.getServiceState());
        fromDb.setStateChanged(registration.getStateChanged());
        fromDb.setWarningStateTrigger(registration.getWarningStateTrigger());
        fromDb.setErrorStateTrigger(registration.getErrorStateTrigger());
        tx.commit();
        servicesStatistics.updateService(registration);
        return registration;
    } catch (PersistenceException e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw e;
    }
}

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

public void updateExerciseInstanceUsedHints(ExerciseInstance ei, FlagQuestionHint hint) {
    EntityManager em = getHibernateEntityManager();
    EntityTransaction et = em.getTransaction();
    et.begin();/*from www . j  a  v  a 2  s .c  o  m*/
    try {
        em.createNativeQuery("INSERT INTO exerciseInstances_flagQuestionHints "
                + "(ExerciseInstance_idExerciseInstance,usedHints_idFlagQuestionHint) " + "VALUES (?,?)")
                .setParameter(1, ei.getIdExerciseInstance()).setParameter(2, hint.getId()).executeUpdate();
        et.commit();
        em.close();
    } catch (Exception e) {
        et.rollback();
        em.close();
        logger.error("Failed adding hint " + hint.getId() + " to exercise instance "
                + ei.getIdExerciseInstance() + " because of: \n" + e.getMessage());
    }

}

From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java

/** Processes the incoming request and calls the various methods to create the right output stream.
 *
 * @param request servlet request// w  ww  . j a v  a  2  s.c  o  m
 * @param response servlet response
 *
 * @throws ServletException
 * @throws IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long startTime = System.currentTimeMillis();

    StringBuffer baseUrl = createBaseUrl(request, true);
    if (CAPABILITIES_DTD == null) {
        CAPABILITIES_DTD = baseUrl.toString() + "/dtd/capabilities_1_1_1.dtd";
    }
    if (EXCEPTION_DTD == null) {
        EXCEPTION_DTD = baseUrl.toString() + "/dtd/exception_1_1_1.dtd";
    }
    if (DESCRIBELAYER_DTD == null) {
        DESCRIBELAYER_DTD = baseUrl.toString() + "/dtd/WMS_DescribeLayerResponse.dtd";
    }

    DataWrapper data = new DataWrapper(request, response);

    Object identity = null;
    EntityManager em;
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
        em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
        tx = em.getTransaction();
        tx.begin();

        DataMonitoring rr = new DataMonitoring();
        data.setRequestReporting(rr);

        String serviceName = OGCConstants.WMS_SERVICE_WMS;

        try {
            OGCRequest ogcrequest = calcOGCRequest(request);

            String personalCode = null;
            if (ogcrequest != null)
                personalCode = ogcrequest.getPersonalCode();

            data.setOgcrequest(ogcrequest);

            String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE);
            if (serviceParam != null || !"".equals(serviceParam)) {
                serviceName = serviceParam;
            }

            String iUrl = ogcrequest.getUrl();
            rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(),
                    request.getMethod());

            User user = checkLogin(request, personalCode, em);

            ogcrequest.checkRequestURL();

            Organization mainOrg = null;
            String userName = null;

            if (user != null) {
                mainOrg = user.getMainOrganization();
                userName = user.getUsername();
            }

            rr.setUserAndOrganization(user, mainOrg);
            data.setHeader("X-Kaartenbalie-User", userName);

            parseRequestAndData(data, user);

        } catch (AccessDeniedException adex) {
            rr.setClientRequestException(adex);
            response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie");
        } catch (ProviderException pex) {
            log.error("Error while communicating with provider: " + pex.getLocalizedMessage());
            rr.setClientRequestException(pex);
            handleRequestException(pex, data);
        } catch (Exception e) {
            log.error(String.format("Error while handling request for URI %s, query string %s: %s: %s",
                    request.getRequestURI(), request.getQueryString(), e.getClass().getName(), e.getMessage()),
                    e);
            rr.setClientRequestException(e);
            handleRequestException(e, data);
        } finally {
            rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(),
                    System.currentTimeMillis() - startTime);
        }
        if (!tx.getRollbackOnly()) {
            tx.commit();
        }
    } catch (Exception ex) {
        log.error("Error creating EntityManager", ex);
        handleRequestException(ex, data);
    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//from  ww w  . ja v a2s.  co  m
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#enableHost(String)
 */
@Override
public void enableHost(String host) throws ServiceRegistryException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing registrations for this host and if it exists, update it
        HostRegistrationJpaImpl hostRegistration = fetchHostRegistration(em, host);
        if (hostRegistration == null) {
            throw new NotFoundException(
                    "Host '" + host + "' is currently not registered, so it can not be enabled");
        } else {
            hostRegistration.setActive(true);
            em.merge(hostRegistration);
        }
        logger.info("Enabling {}", host);
        tx.commit();
        tx.begin();
        for (ServiceRegistration serviceRegistration : getServiceRegistrationsByHost(host)) {
            ServiceRegistrationJpaImpl registration = (ServiceRegistrationJpaImpl) serviceRegistration;
            registration.setActive(true);
            em.merge(registration);
            servicesStatistics.updateService(registration);
        }
        tx.commit();
        hostsStatistics.updateHost(hostRegistration);
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java

/**
 * Processes the incoming request and calls the various methods to create
 * the right output stream.//from w w w .  j av  a  2  s  .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 *
 * @throws ServletException
 * @throws IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long startTime = System.currentTimeMillis();

    DataWrapper data = new DataWrapper(request, response);

    Object identity = null;
    EntityManager em;
    EntityTransaction tx = null;

    try {
        /*
         * Check IP lock
         */
        checkRemoteIP(request);

        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
        log.debug("Getting entity manager ......");
        em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
        tx = em.getTransaction();
        tx.begin();

        DataMonitoring rr = new DataMonitoring();
        data.setRequestReporting(rr);

        String serviceName = OGCConstants.WMS_SERVICE_WMS;

        try {
            OGCScriptingRequest ogcrequest = calcOGCScriptingRequest(request);

            if (!ogcrequest.containsParameter(OGCScriptingRequest.COMMAND)) {
                throw new Exception("Bad request");
            }

            data.setOgcrequest(ogcrequest);

            String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE);
            if (serviceParam != null || !"".equals(serviceParam)) {
                serviceName = serviceParam;
            }

            String iUrl = ogcrequest.getUrl();
            String pcode = ogcrequest.getPersonalCode();
            rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(),
                    request.getMethod());

            User user = checkLogin(request, em, pcode);

            if (ogcrequest != null) {
                ogcrequest.checkRequestURL();
            }

            rr.setUserAndOrganization(user, user.getMainOrganization());
            data.setHeader("X-Kaartenbalie-User", user.getUsername());

            this.httpRequest = request;

            if (ogcrequest.getParameter(OGCScriptingRequest.COMMAND)
                    .equalsIgnoreCase(OGCScriptingRequest.GET_GROUP_XML)) {
                GroupParser groupParser = new GroupParser();

                groupParser.getGroupsAsXML(response, data.getOutputStream());
            } else {
                parseRequestAndData(data, user);
            }

        } catch (AccessDeniedException adex) {
            log.error("Access denied: " + adex.getLocalizedMessage());
            rr.setClientRequestException(adex);
            response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie");
        } catch (Exception ex) {
            log.error("Error while handling request: ", ex);
            rr.setClientRequestException(ex);
            response.sendError(400, "Bad Request. See API documentation");
        } finally {
            rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(),
                    System.currentTimeMillis() - startTime);
        }
        tx.commit();
    } catch (Exception ex) {
        log.error("Error creating EntityManager: ", ex);
        try {
            tx.rollback();
        } catch (Exception ex2) {
            log.error("Error trying to rollback: ", ex2);
        }
    } finally {
        //log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}