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

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

/**
 * Find all running jobs on this service and set them to RESET or CANCELED.
 * /*from   w  w  w  .  ja  va  2  s.c  om*/
 * @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.
 * /*from w  w  w .  ja  v a 2 s.c om*/
 * @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.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Creates a job on a remote host./* w w  w . ja  v  a  2s.co  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();
    }
}

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

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

}

From source file:de.iai.ilcd.model.dao.SourceDao.java

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

    File directory = null;/* www.j a  v a2 s  .c om*/
    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;
}