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:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();/*from www  . j  av a  2  s. c  o  m*/
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

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

/**
 * throws if it doesn't exist, returns it if it does
 *
 * @param tmodelKey/*from   w w  w  .  jav  a 2s  . c  o  m*/
 * @return null, or a TModel object
 * @throws ValueNotAllowedException
 * @since 3.3
 */
private TModel verifyTModelKeyExists(String tmodelKey)
        throws ValueNotAllowedException, DispositionReportFaultMessage {
    TModel api = null;
    EntityManager em = PersistenceManager.getEntityManager();
    boolean found = false;
    if (em == null) {
        log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
    } else {
        Tmodel modelTModel = null;
        {
            EntityTransaction tx = em.getTransaction();
            try {

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

                if (modelTModel != null) {
                    found = true;
                    api = new TModel();
                    MappingModelToApi.mapTModel(modelTModel, api);
                }
                tx.commit();

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

        }
    }
    if (!found) {
        throw new ValueNotAllowedException(
                new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey));
    }
    return api;
}

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

/**
 * Validates that a tmodel key is registered Alex O'Ree
 *
 * @param tmodelKey//from   www  .j  av  a2  s.c  om
 * @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

/**
 * Internal method to update a job, throwing unwrapped JPA exceptions.
 * /*from w  w  w.  j  ava  2  s  . c o m*/
 * @param em
 *          the current entity manager
 * @param job
 *          the job to update
 * @return the updated job
 * @throws PersistenceException
 *           if there is an exception thrown while persisting the job via JPA
 * @throws IllegalArgumentException
 */
protected Job updateInternal(EntityManager em, Job job) throws PersistenceException {
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        JobJpaImpl fromDb;
        fromDb = em.find(JobJpaImpl.class, job.getId());
        if (fromDb == null) {
            throw new NoResultException();
        }
        update(fromDb, (JaxbJob) job);

        em.merge(fromDb);
        tx.commit();
        ((JaxbJob) job).setVersion(fromDb.getVersion());
        setJobUri(job);
        return job;
    } catch (PersistenceException e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw e;
    }
}

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 av 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:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//from w w  w.  ja v a2  s .  com
 * 
 * @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.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Find all undispatchable jobs and set them to CANCELED.
 *///from  w ww .  jav a  2  s  .co 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}//from  www  .  j  a  v  a2 s  . c  o 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:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

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

/**
 * {@inheritDoc}// w  w w .ja va 2  s  .co  m
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#disableHost(String)
 */
@Override
public void disableHost(String host) throws ServiceRegistryException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        HostRegistrationJpaImpl hostRegistration = fetchHostRegistration(em, host);
        if (hostRegistration == null) {
            throw new NotFoundException(
                    "Host '" + host + "' is not currently registered, so it can not be disabled");
        } else {
            hostRegistration.setActive(false);
            for (ServiceRegistration serviceRegistration : getServiceRegistrationsByHost(host)) {
                ServiceRegistrationJpaImpl registration = (ServiceRegistrationJpaImpl) serviceRegistration;
                registration.setActive(false);
                em.merge(registration);
                servicesStatistics.updateService(registration);
            }
            em.merge(hostRegistration);
        }
        logger.info("Disabling {}", host);
        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();
    }
}