Example usage for javax.persistence EntityTransaction rollback

List of usage examples for javax.persistence EntityTransaction rollback

Introduction

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

Prototype

public void rollback();

Source Link

Document

Roll back the current resource transaction.

Usage

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

/**
 * {@inheritDoc}/*w  w  w .  jav  a  2 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:com.eucalyptus.blockstorage.BlockStorageController.java

/**
 * Checks to see if a new snapshot of size volSize will exceed the quota
 * @param volSize// w  w  w. ja  v a2  s . com
 * @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.
 *///  w  w  w.java  2s  .  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}/* ww  w. j  a v  a 2  s.c o  m*/
 * 
 * @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 a v a  2  s  . c  o 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();
    }
}

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

/**
 * Deletes publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required.
 *
 * @param body//  w ww  . java2 s  .  c o  m
 * @throws DispositionReportFaultMessage
 */
public void deletePublisher(DeletePublisher body) throws DispositionReportFaultMessage {

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

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

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

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

            //get an authtoken for this publisher so that we can get its registeredInfo
            UDDISecurityImpl security = new UDDISecurityImpl();
            AuthToken authToken = security.getAuthToken(entityKey);

            GetRegisteredInfo r = new GetRegisteredInfo();
            r.setAuthInfo(authToken.getAuthInfo());
            r.setInfoSelection(InfoSelection.ALL);

            log.info("removing all businesses owned by publisher " + entityKey + ".");
            UDDIPublicationImpl publish = new UDDIPublicationImpl();
            RegisteredInfo registeredInfo = publish.getRegisteredInfo(r);
            BusinessInfos businessInfos = registeredInfo.getBusinessInfos();
            if (businessInfos != null && businessInfos.getBusinessInfo() != null) {
                Iterator<BusinessInfo> iter = businessInfos.getBusinessInfo().iterator();
                while (iter.hasNext()) {
                    BusinessInfo businessInfo = iter.next();
                    Object business = em.find(org.apache.juddi.model.BusinessEntity.class,
                            businessInfo.getBusinessKey());
                    em.remove(business);
                }
            }

            log.info("mark all tmodels for publisher " + entityKey + " as deleted.");
            TModelInfos tmodelInfos = registeredInfo.getTModelInfos();
            if (tmodelInfos != null && tmodelInfos.getTModelInfo() != null) {
                Iterator<TModelInfo> iter = tmodelInfos.getTModelInfo().iterator();
                while (iter.hasNext()) {
                    TModelInfo tModelInfo = iter.next();
                    Tmodel tmodel = (Tmodel) em.find(org.apache.juddi.model.Tmodel.class,
                            tModelInfo.getTModelKey());
                    tmodel.setDeleted(true);
                    em.persist(tmodel);
                }
            }
            log.info("remove all persisted AuthTokens for publisher " + entityKey + ".");
            Query q1 = em
                    .createQuery("DELETE FROM AuthToken auth WHERE auth.authorizedName = '" + entityKey + "'");
            q1.executeUpdate();

            log.info("removing publisher " + entityKey + ".");
            //delete the publisher
            em.remove(obj);
        }

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

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

/**
 * {@inheritDoc}//  www  . j a va 2 s  .c o  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();
    }
}

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

/**
 * {@inheritDoc}//from  w  ww  . j  a v  a 2 s. c  om
 * 
 * @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:de.iai.ilcd.model.dao.SourceDao.java

private boolean saveDigitalFiles(Source source, PrintWriter out) {
    EntityManager em = PersistenceUtil.getEntityManager();

    File directory = null;//from   w  ww  . ja v a  2  s.  co  m
    EntityTransaction t = em.getTransaction();
    try {

        // OK, now let's handle the files if any
        if ((source.getFiles().size() > 0) && (source.getId() > 0)) { // we have files and the source has a valid
            // id
            // first let's check if the source has already a file directory to save binary files
            String directoryPath = source.getFilesDirectory();
            directory = new File(directoryPath);

            if (!directory.exists()) {
                directory.mkdirs(); // OK, create the directory and all parents
            } // OK, now that we verified that we have a directory, let's copy the files to the directory
            for (DigitalFile digitalFile : source.getFiles()) {
                String sourcePath = digitalFile.getFileName();
                logger.info("have to save digital file {}", sourcePath);
                File file = new File(sourcePath);
                if (file.canRead()) {
                    // copy file only if we have a real file and not only a URL
                    File dest = new File(directory, file.getName());
                    if (!file.copyTo(dest)) {
                        if (out != null) {
                            out.println("cannot copy file " + file.getName() + " of source data set "
                                    + source.getName().getDefaultValue() + " to database file firectory");
                        }
                        logger.error("cannot copy digital file {} to source directory {}", file.getName(),
                                directoryPath);
                    }
                    // now, replace name in digitalFile with just the name of the file
                    digitalFile.setFileName(FilenameUtils.getName(sourcePath));
                } else {
                    if (!file.getName().startsWith("http:") || !file.getName().startsWith("https:")) {
                        // there are sometimes URL refs in source which don't have http:// prepended
                        if (!file.getName().matches(".+\\....") && file.getName().contains(".")) {
                            // looks like a URL with no http:// in front; try to fix that
                            digitalFile.setFileName("http://" + file.getName());
                        } else {
                            // we have a file which we cannot find
                            digitalFile.setFileName(FilenameUtils.getName(sourcePath));
                            out.println("warning: digital file " + FilenameUtils.getName(sourcePath)
                                    + " of source data set " + source.getName().getDefaultValue()
                                    + " cannot be found in external_docs directory");
                            logger.warn(
                                    "warning: digital file {} of source data set {} cannot be found in external_docs directory; will be ignored",
                                    file.getName(), source.getName().getDefaultValue());
                        }
                    }
                }
                t.begin();
                em.persist(digitalFile);
                t.commit();
            }
        }
    } catch (Exception e) {
        // OK, let's delete the digital files and rollback the whole transaction to remove database items
        logger.error("cannot save digital file", e);
        if (t.isActive()) {
            t.rollback();
        }
        this.deleteDigitalFiles(source);
        return false;
    }
    return true;
}

From source file:org.sigmah.server.schedule.export.AutoExportJob.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  .  jav a  2  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 which is out of scope 
         */
        tx = em.getTransaction();
        tx.begin();

        final GlobalExportDAO exportDAO = new GlobalExportHibernateDAO(em);
        final GlobalExportDataProvider dataProvider = injector.getInstance(GlobalExportDataProvider.class);

        final List<GlobalExportSettings> settings = exportDAO.getGlobalExportSettings();
        for (final GlobalExportSettings setting : settings) {

            /*
             * Check for auto export schedule 
             */

            //skip if no export schedule is specified
            if (setting.getAutoExportFrequency() == null || setting.getAutoExportFrequency() < 1)
                continue;

            final Calendar systemCalendar = Calendar.getInstance();

            boolean doExport = false;

            if ((setting.getAutoExportFrequency() >= 31) && (setting.getAutoExportFrequency() <= 58)) {
                //Case of Monthly Auto Export
                if ((setting.getAutoExportFrequency() - 30) == systemCalendar.get(Calendar.DAY_OF_MONTH)) {
                    doExport = true;
                }
            } else if ((setting.getAutoExportFrequency() >= 61) && (setting.getAutoExportFrequency() <= 67)) {
                //Case of Weekly Auto Export
                if ((setting.getAutoExportFrequency() - 60) == systemCalendar.get(Calendar.DAY_OF_WEEK)) {
                    doExport = true;
                }

            } else {
                //Regular Auto-Export every N-days

                final Calendar scheduledCalendar = Calendar.getInstance();
                Date lastExportDate = setting.getLastExportDate();
                if (lastExportDate == null) {
                    lastExportDate = systemCalendar.getTime();
                    setting.setLastExportDate(lastExportDate);
                    em.merge(setting);
                } else {
                    scheduledCalendar.setTime(lastExportDate);
                    // add scheduled days to the last exported date
                    scheduledCalendar.add(Calendar.DAY_OF_MONTH, setting.getAutoExportFrequency());
                }

                final Date systemDate = getZeroTimeDate(systemCalendar.getTime());
                final Date scheduledDate = getZeroTimeDate(scheduledCalendar.getTime());

                if (systemDate.compareTo(scheduledDate) >= 0) {
                    doExport = true;
                }
            }

            if (doExport) {
                /*
                 * Start auto export  
                 */

                // persist global export logger
                final GlobalExport globalExport = new GlobalExport();
                globalExport.setOrganization(setting.getOrganization());
                globalExport.setDate(systemCalendar.getTime());
                em.persist(globalExport);

                // generate export content
                final Map<String, List<String[]>> exportData = dataProvider
                        .generateGlobalExportData(setting.getOrganization().getId(), em, setting.getLocale());

                // persist export content
                dataProvider.persistGlobalExportDataAsCsv(globalExport, em, exportData);
            }

        }
        tx.commit();

        log.info("Scheduled EXPORT 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();
    }
}