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

/**
 * Deletes publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required.
 *
 * @param body/*from www  .j  ava 2s  .  co 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}//  w  ww  . j a  v  a  2 s.com
 * 
 * @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}/*  www.ja va  2 s  .c o 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:de.iai.ilcd.model.dao.SourceDao.java

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

    File directory = null;//from   www . j a va2 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 {/*w  ww .j ava  2s .  c o  m*/

        // 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();
    }
}

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

public RegisteredInfo getRegisteredInfo(GetRegisteredInfo body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

        new ValidatePublish(publisher).validateRegisteredInfo(body);

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

        List<?> tmodelKeysFound = null;

        if (body.getInfoSelection().equals(InfoSelection.HIDDEN))
            tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound,
                    new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.TRUE,
                            DynamicQuery.PREDICATE_EQUALS));
        else if (body.getInfoSelection().equals(InfoSelection.VISIBLE))
            tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound,
                    new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.FALSE,
                            DynamicQuery.PREDICATE_EQUALS));
        else
            tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound);

        RegisteredInfo result = new RegisteredInfo();

        // Sort and retrieve the final results
        List<?> queryResults = FetchBusinessEntitiesQuery.select(em, new FindQualifiers(), businessKeysFound,
                null, null, null);
        if (queryResults.size() > 0) {
            result.setBusinessInfos(new org.uddi.api_v3.BusinessInfos());

            for (Object item : queryResults) {
                org.apache.juddi.model.BusinessEntity modelBusinessEntity = (org.apache.juddi.model.BusinessEntity) item;
                org.uddi.api_v3.BusinessInfo apiBusinessInfo = new org.uddi.api_v3.BusinessInfo();

                MappingModelToApi.mapBusinessInfo(modelBusinessEntity, apiBusinessInfo);

                result.getBusinessInfos().getBusinessInfo().add(apiBusinessInfo);
            }
        }

        // Sort and retrieve the final results
        queryResults = FetchTModelsQuery.select(em, new FindQualifiers(), tmodelKeysFound, null, null, null);
        if (queryResults.size() > 0) {
            result.setTModelInfos(new org.uddi.api_v3.TModelInfos());

            for (Object item : queryResults) {
                org.apache.juddi.model.Tmodel modelTModel = (org.apache.juddi.model.Tmodel) item;
                org.uddi.api_v3.TModelInfo apiTModelInfo = new org.uddi.api_v3.TModelInfo();

                MappingModelToApi.mapTModelInfo(modelTModel, apiTModelInfo);

                result.getTModelInfos().getTModelInfo().add(apiTModelInfo);
            }
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_REGISTEREDINFO, QueryStatus.SUCCESS, procTime);

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

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

/**
 * Find all running jobs on this service and set them to RESET or CANCELED.
 * /*  w  ww  . j  a  va2s .  com*/
 * @param serviceType
 *          the service type
 * @param baseUrl
 *          the base url
 * @throws ServiceRegistryException
 *           if there is a problem communicating with the jobs database
 */
private void cleanRunningJobs(String serviceType, String baseUrl) throws ServiceRegistryException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query query = em.createNamedQuery("Job.processinghost.status");
        query.setParameter("status", Status.RUNNING);
        query.setParameter("host", baseUrl);
        query.setParameter("serviceType", serviceType);
        @SuppressWarnings("unchecked")
        List<JobJpaImpl> unregisteredJobs = query.getResultList();
        for (JobJpaImpl job : unregisteredJobs) {
            if (job.isDispatchable()) {
                em.refresh(job);
                // If this job has already been treated
                if (Status.CANCELED.equals(job.getStatus()) || Status.RESTART.equals(job.getStatus()))
                    continue;
                if (job.getRootJob() != null && Status.PAUSED.equals(job.getRootJob().getStatus())) {
                    JobJpaImpl rootJob = job.getRootJob();
                    cancelAllChildren(rootJob, em);
                    rootJob.setStatus(Status.RESTART);
                    rootJob.setOperation(START_OPERATION);
                    em.merge(rootJob);
                    continue;
                }

                logger.info("Marking child jobs from job {} as canceled", job);
                cancelAllChildren(job, em);
                logger.info("Rescheduling lost job {}", job);
                job.setStatus(Status.RESTART);
                job.setProcessorServiceRegistration(null);
            } else {
                logger.info("Marking lost job {} as failed", job);
                job.setStatus(Status.FAILED);
            }
            em.merge(job);
        }
        tx.commit();
    } 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

/**
 * Sets the online status of a service registration.
 * //w  w w .  j a  v  a 2s.c o m
 * @param serviceType
 *          The job type
 * @param baseUrl
 *          the host URL
 * @param online
 *          whether the service is online or off
 * @param jobProducer
 *          whether this service produces jobs for long running operations
 * @return the service registration
 */
protected ServiceRegistration setOnlineStatus(String serviceType, String baseUrl, String path, boolean online,
        Boolean jobProducer) throws ServiceRegistryException {
    if (isBlank(serviceType) || isBlank(baseUrl)) {
        throw new IllegalArgumentException("serviceType and baseUrl must not be blank");
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        HostRegistrationJpaImpl hostRegistration = fetchHostRegistration(em, baseUrl);
        if (hostRegistration == null) {
            throw new IllegalStateException(
                    "A service registration can not be updated when it has no associated host registration");
        }
        ServiceRegistrationJpaImpl registration = getServiceRegistration(em, serviceType, baseUrl);
        if (registration == null) {
            if (isBlank(path)) {
                // we can not create a new registration without a path
                throw new IllegalArgumentException("path must not be blank when registering new services");
            }
            if (jobProducer == null) { // if we are not provided a value, consider it to be false
                registration = new ServiceRegistrationJpaImpl(hostRegistration, serviceType, path, false);

            } else {
                registration = new ServiceRegistrationJpaImpl(hostRegistration, serviceType, path, jobProducer);
            }
            em.persist(registration);
        } else {
            if (StringUtils.isNotBlank(path))
                registration.setPath(path);
            registration.setOnline(online);
            if (jobProducer != null) { // if we are not provided a value, don't update the persistent value
                registration.setJobProducer(jobProducer);
            }
            em.merge(registration);
        }
        tx.commit();
        hostsStatistics.updateHost(hostRegistration);
        servicesStatistics.updateService(registration);
        return registration;
    } 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.UDDIPublicationImpl.java

public void addPublisherAssertions(AddPublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

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

        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
        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.PublisherAssertion existingPubAssertion = em
                    .find(modelPubAssertion.getClass(), modelPubAssertion.getId());
            boolean persistNewAssertion = true;
            if (existingPubAssertion != null) {
                if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey())
                        && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName())
                        && modelPubAssertion.getKeyValue()
                                .equalsIgnoreCase(existingPubAssertion.getKeyValue())) {
                    // This pub assertion is already been "asserted".  Simply need to set the "check" value on the existing (and persistent) assertion
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey()))
                        existingPubAssertion.setFromCheck("true");
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey()))
                        existingPubAssertion.setToCheck("true");

                    persistNewAssertion = false;
                } else {
                    // Otherwise, it is a new relationship between these entities.  Remove the old one so the new one can be added.
                    // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as 
                    // many relationships as desired (the differentiator would be the keyedRef values).
                    em.remove(existingPubAssertion);
                }
            }

            if (persistNewAssertion) {
                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.ADD_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

/**
 * Creates a job on a remote host.//from ww w .jav  a2 s.c  o m
 */
public Job createJob(String host, String serviceType, String operation, List<String> arguments, String payload,
        boolean dispatchable, Job parentJob) throws ServiceRegistryException {
    if (StringUtils.isBlank(host)) {
        throw new IllegalArgumentException("Host can't be null");
    }
    if (StringUtils.isBlank(serviceType)) {
        throw new IllegalArgumentException("Service type can't be null");
    }
    if (StringUtils.isBlank(operation)) {
        throw new IllegalArgumentException("Operation can't be null");
    }

    User currentUser = securityService.getUser();
    Organization currentOrganization = securityService.getOrganization();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        ServiceRegistrationJpaImpl creatingService = getServiceRegistration(em, serviceType, host);
        if (creatingService == null) {
            throw new ServiceRegistryException(
                    "No service registration exists for type '" + serviceType + "' on host '" + host + "'");
        }
        if (creatingService.getHostRegistration().isMaintenanceMode()) {
            logger.warn("Creating a job from {}, which is currently in maintenance mode.",
                    creatingService.getHost());
        } else if (!creatingService.getHostRegistration().isActive()) {
            logger.warn("Creating a job from {}, which is currently inactive.", creatingService.getHost());
        }
        JobJpaImpl job = new JobJpaImpl(currentUser, currentOrganization, creatingService, operation, arguments,
                payload, dispatchable);

        // Bind the given parent job to the new job
        if (parentJob != null) {

            // Get the JPA instance of the parent job
            JobJpaImpl jpaParentJob;
            if (parentJob instanceof JobJpaImpl)
                jpaParentJob = (JobJpaImpl) parentJob;
            else {
                try {
                    jpaParentJob = (JobJpaImpl) getJob(parentJob.getId());
                } catch (NotFoundException e) {
                    logger.error("{} not found in the persitence context", parentJob);
                    throw new ServiceRegistryException(e);
                }
            }
            job.setParentJob(jpaParentJob);

            // Get the JPA instance of the root job
            JobJpaImpl jpaRootJob;
            if (parentJob.getRootJobId() == -1L) {
                jpaRootJob = jpaParentJob;
            } else {
                try {
                    jpaRootJob = (JobJpaImpl) getJob(parentJob.getRootJobId());
                } catch (NotFoundException e) {
                    logger.error("job with id {} not found in the persitence context",
                            parentJob.getRootJobId());
                    throw new ServiceRegistryException(e);
                }
            }
            job.setRootJob(jpaRootJob);
        }

        // if this job is not dispatchable, it must be handled by the host that has created it
        if (dispatchable) {
            job.setStatus(Status.QUEUED);
        } else {
            job.setProcessingHost(creatingService.getHost());
        }

        em.persist(job);
        tx.commit();
        setJobUri(job);
        return job;
    } catch (RollbackException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        if (em != null)
            em.close();
    }
}