Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

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

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

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 {//  w w w.  j  a va  2  s .  c  om
        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:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//from ww  w .j  a  va  2 s . c  om
 * 
 * @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

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

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

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

    File directory = null;//from   w  ww .j a  va  2 s  .c o 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.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  w w .j a  va  2 s  .co m*/
        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.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 w  w .j  ava 2s. 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();
    }
}

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

/**
 * Sets the online status of a service registration.
 * /*from   www. j  av a  2 s.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();
    }
}