Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction isActive.

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

From source file:org.apache.juddi.config.Install.java

protected static void install(Configuration config)
        throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException {

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

    UddiEntityPublisher rootPublisher = null;

    try {/*from  ww w .j av  a 2 s. c om*/
        tx.begin();
        boolean seedAlways = config.getBoolean("juddi.seed.always", false);
        boolean alreadyInstalled = alreadyInstalled(config);
        if (!seedAlways && alreadyInstalled)
            new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled"));

        String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER);
        String fileRootTModelKeygen = rootPublisherStr + FILE_TMODELKEYGEN;
        TModel rootTModelKeyGen = (TModel) buildInstallEntity(fileRootTModelKeygen, "org.uddi.api_v3", config);
        String fileRootBusinessEntity = rootPublisherStr + FILE_BUSINESSENTITY;
        org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(
                fileRootBusinessEntity, "org.uddi.api_v3", config);

        String rootPartition = getRootPartition(rootTModelKeyGen);
        String nodeId = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition);

        String fileRootPublisher = rootPublisherStr + FILE_PUBLISHER;
        if (!alreadyInstalled) {
            log.info("Loading the root Publisher from file " + fileRootPublisher);

            rootPublisher = installPublisher(em, fileRootPublisher, config);
            installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId);
            rootBusinessEntity.setBusinessKey(nodeId);
            installBusinessEntity(true, em, rootBusinessEntity, rootPublisher, rootPartition, config);
        } else {
            log.debug("juddi.seed.always reapplies all seed files except for the root data.");
        }

        List<String> juddiPublishers = getPublishers(config);
        for (String publisherStr : juddiPublishers) {
            String filePublisher = publisherStr + FILE_PUBLISHER;
            String fileTModelKeygen = publisherStr + FILE_TMODELKEYGEN;
            TModel tModelKeyGen = (TModel) buildInstallEntity(fileTModelKeygen, "org.uddi.api_v3", config);
            String fileBusinessEntity = publisherStr + FILE_BUSINESSENTITY;
            org.uddi.api_v3.BusinessEntity businessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(
                    fileBusinessEntity, "org.uddi.api_v3", config);
            UddiEntityPublisher publisher = installPublisher(em, filePublisher, config);
            if (publisher == null) {
                throw new ConfigurationException("File " + filePublisher + " not found.");
            } else {
                if (tModelKeyGen != null)
                    installPublisherKeyGen(em, tModelKeyGen, publisher, nodeId);
                if (businessEntity != null)
                    installBusinessEntity(false, em, businessEntity, publisher, null, config);
                String fileTModels = publisherStr + FILE_TMODELS;
                installSaveTModel(em, fileTModels, publisher, nodeId, config);
            }
        }

        tx.commit();
    } catch (DispositionReportFaultMessage dr) {
        log.error(dr.getMessage(), dr);
        tx.rollback();
        throw dr;
    } catch (JAXBException je) {
        log.error(je.getMessage(), je);
        tx.rollback();
        throw je;
    } catch (IOException ie) {
        log.error(ie.getMessage(), ie);
        tx.rollback();
        throw ie;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

/**
 * Internal method to update the service registration state, throwing unwrapped JPA exceptions.
 * /*from  w w w  .  j  a  v  a 2 s. c  o  m*/
 * @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:org.apache.juddi.config.AppConfig.java

private Properties getPersistentConfiguration(Configuration config) throws ConfigurationException {
    Properties result = new Properties();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w w w  .  j ava  2  s.  co  m*/
        boolean seedAlways = config.getBoolean("juddi.seed.always", false);
        if (seedAlways || !Install.alreadyInstalled(config)) {
            if (seedAlways) {
                log.info("Installing UDDI seed data, loading...");
            } else {
                log.info("The 'root' publisher was not found, loading...");
            }
            try {
                Install.install(config);
            } catch (Exception e) {
                throw new ConfigurationException(e);
            } catch (Throwable t) {
                throw new ConfigurationException(t);
            }
        }

        tx.begin();

        String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER);
        UddiEntityPublisher rootPublisher = new UddiEntityPublisher(rootPublisherStr);
        rootPublisher.populateKeyGeneratorKeys(em);
        List<String> rootKeyGenList = rootPublisher.getKeyGeneratorKeys();
        if (rootKeyGenList == null || rootKeyGenList.size() == 0)
            throw new ConfigurationException(
                    "The 'root' publisher key generator was not found.  Please make sure that the application is properly installed.");

        String rootKeyGen = rootKeyGenList.iterator().next();
        //rootKeyGen = rootKeyGen.substring((KeyGenerator.UDDI_SCHEME + KeyGenerator.PARTITION_SEPARATOR).length());
        rootKeyGen = rootKeyGen.substring(0, rootKeyGen.length()
                - (KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).length());
        log.debug("root partition:  " + rootKeyGen);

        result.setProperty(Property.JUDDI_ROOT_PARTITION, rootKeyGen);

        // The node Id is defined as the business key of the business entity categorized as a node.  This entity is saved as part of the install.
        // Only one business entity should be categorized as a node.
        String nodeId = "";
        CategoryBag categoryBag = new CategoryBag();
        KeyedReference keyedRef = new KeyedReference();
        keyedRef.setTModelKey(Constants.NODE_CATEGORY_TMODEL);
        keyedRef.setKeyValue(Constants.NODE_KEYVALUE);
        categoryBag.getKeyedReference().add(keyedRef);
        List<?> keyList = FindBusinessByCategoryQuery.select(em, new FindQualifiers(), categoryBag, null);
        if (keyList != null && keyList.size() > 1)
            throw new ConfigurationException("Only one business entity can be categorized as the node.");

        if (keyList != null && keyList.size() > 0) {
            nodeId = (String) keyList.get(0);
        } else
            throw new ConfigurationException(
                    "A node business entity was not found.  Please make sure that the application is properly installed.");
        result.setProperty(Property.JUDDI_NODE_ID, nodeId);

        //result.setProperty(Property.JUDDI_NODE_ROOT_BUSINESS, nodeId);

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

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/*from   w w  w . ja v a 2s  .  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.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 {/*  w w  w .ja v a  2s.com*/
        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.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//from   www. j  a  v a2s .  co m
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#registerHost(java.lang.String, int)
 */
@Override
public void registerHost(String host, int maxJobs) throws ServiceRegistryException {
    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) {
            hostRegistration = new HostRegistrationJpaImpl(host, maxJobs, true, false);
            em.persist(hostRegistration);
        } else {
            hostRegistration.setMaxJobs(maxJobs);
            hostRegistration.setOnline(true);
            em.merge(hostRegistration);
        }
        logger.info("Registering {} with a maximum load of {}", host, maxJobs);
        tx.commit();
        hostsStatistics.updateHost(hostRegistration);
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.eucalyptus.blockstorage.BlockStorageController.java

/**
 * Checks to see if a new snapshot of size volSize will exceed the quota
 * @param volSize//w w w  . j a  v a2s. c  o  m
 * @param maxSize 
 * @return
 */
private boolean totalSnapshotSizeLimitExceeded(String snapshotId, int volSize, int sizeLimitGB)
        throws EucalyptusCloudException {

    int totalSnapshotSize = 0;
    EntityTransaction dbTrans = Entities.get(SnapshotInfo.class);
    try {
        Criteria query = Entities.createCriteria(SnapshotInfo.class);
        query.setReadOnly(true);

        //Only look for snaps that are not failed and not error
        ImmutableSet<String> excludedStates = ImmutableSet.of(StorageProperties.Status.failed.toString(),
                StorageProperties.Status.error.toString(), StorageProperties.Status.deleted.toString());

        query.add(Restrictions.not(Restrictions.in("status", excludedStates)));

        //The listing may include duplicates (for snapshots cached on multiple clusters), this set ensures each unique snap id is counted only once.
        HashSet<String> idSet = new HashSet<String>();
        List<SnapshotInfo> snapshots = (List<SnapshotInfo>) query.list();
        for (SnapshotInfo snap : snapshots) {
            totalSnapshotSize += (snap.getSizeGb() != null && idSet.add(snap.getSnapshotId()) ? snap.getSizeGb()
                    : 0);
        }
        LOG.debug("Snapshot " + snapshotId + " checking snapshot total size of  " + totalSnapshotSize
                + " against limit of " + sizeLimitGB);
        return (totalSnapshotSize + volSize) > sizeLimitGB;
    } catch (final Throwable e) {
        LOG.error("Error finding total snapshot used size " + e.getMessage());
        throw new EucalyptusCloudException("Failed to check snapshot total size limit", e);
    } finally {
        if (dbTrans.isActive()) {
            dbTrans.rollback();
        }
    }
}

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

/**
 * Find all undispatchable jobs and set them to CANCELED.
 *///from ww w.j a  v a2  s.  c  o m
private void cleanUndispatchableJobs() {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query query = em.createNamedQuery("Job.undispatchable.status");
        List<Status> statuses = new ArrayList<Job.Status>();
        statuses.add(Status.INSTANTIATED);
        statuses.add(Status.RUNNING);
        query.setParameter("statuses", statuses);
        @SuppressWarnings("unchecked")
        List<JobJpaImpl> undispatchableJobs = query.getResultList();
        for (JobJpaImpl job : undispatchableJobs) {
            logger.info("Marking undispatchable job {} as canceled", job);
            job.setStatus(Status.CANCELED);
            em.merge(job);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Unable to clean undispatchable jobs! {}", e.getMessage());
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (em != null)
            em.close();
    }
}

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

/**
 * {@inheritDoc}/*  w ww  .  ja v  a  2 s. c om*/
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#unregisterHost(java.lang.String)
 */
@Override
public void unregisterHost(String host) throws ServiceRegistryException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        HostRegistrationJpaImpl existingHostRegistration = fetchHostRegistration(em, host);
        if (existingHostRegistration == null) {
            throw new ServiceRegistryException(
                    "Host '" + host + "' is not currently registered, so it can not be unregistered");
        } else {
            existingHostRegistration.setOnline(false);
            for (ServiceRegistration serviceRegistration : getServiceRegistrationsByHost(host)) {
                unRegisterService(serviceRegistration.getServiceType(), serviceRegistration.getHost());
            }
            em.merge(existingHostRegistration);
        }
        logger.info("Unregistering {}", host, maxJobs);
        tx.commit();
        hostsStatistics.updateHost(existingHostRegistration);
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(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 {/*w  w  w.j  av a2s.  co m*/
        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();
    }
}