Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

In this page you can find the example usage for javax.persistence EntityManager persist.

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

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/*w  w w. j a  va  2s.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:com.jada.admin.contactus.ContactUsMaintAction.java

public ActionForward save(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {

    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    boolean insertMode = false;
    ContactUsMaintActionForm form = (ContactUsMaintActionForm) actionForm;
    if (form.getMode().equals("C")) {
        insertMode = true;/*from w  ww.j a  v  a 2 s .  c  om*/
    }

    AdminBean adminBean = getAdminBean(request);
    Site site = adminBean.getSite();
    initSiteProfiles(form, site);

    ContactUs contactUs = new ContactUs();
    if (!insertMode) {
        contactUs = ContactUsDAO.load(site.getSiteId(), Format.getLong(form.getContactUsId()));
    }

    ActionMessages errors = validate(form, site.getSiteId());
    if (errors.size() != 0) {
        saveMessages(request, errors);
        initSearchInfo(form, site.getSiteId());
        return mapping.findForward("error");
    }

    if (insertMode) {
        contactUs.setSite(site);
        contactUs.setRecCreateBy(adminBean.getUser().getUserId());
        contactUs.setRecCreateDatetime(new Date(System.currentTimeMillis()));
    }
    contactUs.setActive(new Character(Constants.ACTIVE_NO));
    if (form.getActive() != null && form.getActive().equals(String.valueOf(Constants.ACTIVE_YES))) {
        contactUs.setActive(new Character(Constants.ACTIVE_YES));
    }
    contactUs.setContactUsEmail(form.getContactUsEmail());
    contactUs.setContactUsPhone(form.getContactUsPhone());
    contactUs.setContactUsAddressLine1(form.getContactUsAddressLine1());
    contactUs.setContactUsAddressLine2(form.getContactUsAddressLine2());
    contactUs.setContactUsCityName(form.getContactUsCityName());
    contactUs.setContactUsStateCode(form.getContactUsStateCode());
    String stateName = Utility.getStateName(site.getSiteId(), form.getContactUsStateCode());
    if (stateName == null) {
        stateName = "";
    }
    contactUs.setContactUsStateName(stateName);
    contactUs.setContactUsCountryCode(form.getContactUsCountryCode());
    contactUs.setContactUsCountryName(Utility.getCountryName(site.getSiteId(), form.getContactUsCountryCode()));
    contactUs.setContactUsZipCode(form.getContactUsZipCode());
    if (!Format.isNullOrEmpty(form.getSeqNum())) {
        contactUs.setSeqNum(Format.getIntObj(form.getSeqNum()));
    } else {
        contactUs.setSeqNum(new Integer(0));
    }
    contactUs.setRecUpdateBy(adminBean.getUser().getUserId());
    contactUs.setRecUpdateDatetime(new Date(System.currentTimeMillis()));

    if (form.isSiteProfileClassDefault()) {
        saveDefault(contactUs, form, adminBean);
    } else {
        saveLanguage(contactUs, form, adminBean);
    }

    if (insertMode) {
        em.persist(contactUs);
    } else {
        // em.update(contactUs);
    }
    form.setContactUsId(Format.getLong(contactUs.getContactUsId()));
    form.setMode("U");
    initSearchInfo(form, site.getSiteId());
    FormUtils.setFormDisplayMode(request, form, FormUtils.EDIT_MODE);
    return mapping.findForward("success");
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void cancelJob(int idJob) {
    EntityManager em = null;
    JobInstance ji = null;//from w  w w.j  a va  2s . c o  m
    try {
        em = getEm();
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
        if (ji.getState().equals(State.SUBMITTED)) {
            ji.setState(State.CANCELLED);
        } else {
            throw new NoResultException();
        }
        em.getTransaction().commit();
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException(
                "the job is already running, has already finished or never existed to begin with");
    }

    try {
        em.getTransaction().begin();
        History h = new History();
        h.setId(ji.getId());
        h.setJd(ji.getJd());
        h.setApplicationName(ji.getJd().getApplicationName());
        h.setSessionId(ji.getSessionID());
        h.setQueue(ji.getQueue());
        h.setQueueName(ji.getQueue().getName());
        h.setEnqueueDate(ji.getCreationDate());
        h.setUserName(ji.getUserName());
        h.setEmail(ji.getEmail());
        h.setParentJobId(ji.getParentId());
        h.setApplication(ji.getApplication());
        h.setModule(ji.getModule());
        h.setKeyword1(ji.getKeyword1());
        h.setKeyword2(ji.getKeyword2());
        h.setKeyword3(ji.getKeyword3());
        h.setProgress(ji.getProgress());
        h.setStatus(State.CANCELLED);
        h.setNode(ji.getNode());
        if (ji.getNode() != null) {
            h.setNodeName(ji.getNode().getName());
        }
        em.persist(h);

        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (Exception e) {
        throw new JqmClientException("could not cancel job instance", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:org.rhq.enterprise.server.alert.AlertDefinitionWithComplexNotificationsTest.java

private void prepareDB() {
    executeInTransaction(false, new TransactionCallback() {
        @Override/*from  w w w.j a  v a  2 s. c  o  m*/
        public void execute() throws Exception {
            EntityManager em = getEntityManager();

            agent = new Agent(universalName, "localhost", 0, "foo", "bar");

            server = new Server();
            server.setAddress("localhost");
            server.setName(universalName);
            server.setOperationMode(OperationMode.NORMAL);

            server.setAgents(Collections.singletonList(agent));

            role = new Role(universalName);
            role.addPermission(Permission.MANAGE_INVENTORY);
            role.addPermission(Permission.MANAGE_SETTINGS);

            subject = new Subject(universalName, true, false);
            subject.addRole(role);

            resourceType = new ResourceTypeBuilder().createPlatformResourceType().withId(0)
                    .withName(universalName).withPlugin(universalName).build();
            MeasurementDefinition md = new MeasurementDefinition(universalName, MeasurementCategory.PERFORMANCE,
                    MeasurementUnits.PERCENTAGE, DataType.MEASUREMENT, false, 100000, DisplayType.DETAIL);
            resourceType.addMetricDefinition(md);

            resourceGroup = new ResourceGroup(universalName, resourceType);

            resources = new LinkedHashSet<Resource>();
            for (int i = 0; i < 10; ++i) {
                Resource res = createResourceForTest(universalName + i);

                resources.add(res);

                resourceGroup.addExplicitResource(res);
            }

            templateAlertDefinition = createDefinitionForTest("template", true);
            templateAlertDefinition.setResourceType(resourceType);

            groupAlertDefinition = createDefinitionForTest("group", true);
            groupAlertDefinition.setGroup(resourceGroup);

            resourceAlertDefinition = createDefinitionForTest("resource", true);
            resourceAlertDefinition.setResource(resources.iterator().next());

            em.persist(agent);
            em.persist(server);
            em.persist(role);
            em.persist(subject);
            em.persist(resourceType);
            em.persist(resourceGroup);
            for (Resource r : resources) {
                em.persist(r);
            }
            em.persist(templateAlertDefinition);
            em.persist(groupAlertDefinition);
            em.persist(resourceAlertDefinition);

            //only need this for a short time now, so that we can precreate the plugin structure
            alertSenderService = new TestAlertSenderPluginService(getTempDir());
            prepareCustomServerPluginService(alertSenderService);
            alertSenderService.masterConfig.getPluginDirectory().mkdirs();
            unprepareServerPluginService();

            JavaArchive archive = ShrinkWrap.create(JavaArchive.class);
            archive.addClass(TestAlertSender.class);
            URL res = this.getClass().getClassLoader().getResource("test-alert-sender-serverplugin.xml");
            archive.addAsResource(res, "META-INF/rhq-serverplugin.xml");

            File pluginFile = new File(alertSenderService.masterConfig.getPluginDirectory(),
                    "test-aler-plugin.jar");

            archive.as(ZipExporter.class).exportTo(pluginFile, true);

            //the alert sender plugin manager needs the plugins in the database...
            serverPlugin = TestServerPluginService.getPlugin(pluginFile.toURI().toURL());
            em.persist(serverPlugin);

            em.flush();
        }
    });
}

From source file:org.opencms.db.jpa.CmsProjectDriver.java

/**
 * @see org.opencms.db.I_CmsProjectDriver#log(org.opencms.db.CmsDbContext, java.util.List)
 *//*from www  .j a  v  a2s  .  co m*/
public void log(CmsDbContext dbc, List<CmsLogEntry> logEntries) throws CmsDbSqlException {

    try {

        EntityManager em = m_sqlManager.getEntityManager(dbc);
        em.getTransaction().commit();
        CmsDAOLog daoLog;
        for (CmsLogEntry logEntry : logEntries) {
            em.getTransaction().begin();
            daoLog = new CmsDAOLog();
            daoLog.setUserId(logEntry.getUserId().toString());
            daoLog.setLogDate(logEntry.getDate());
            daoLog.setStructureId(
                    logEntry.getStructureId() == null ? null : logEntry.getStructureId().toString());
            daoLog.setLogType(logEntry.getType().getId());
            daoLog.setLogData(CmsStringUtil.arrayAsString(logEntry.getData(), "|"));
            em.persist(daoLog);
            // here commits on each record, 
            // because there may be a duplicate records
            // and just ignore them
            try {
                if ((em.getTransaction() != null) && em.getTransaction().isActive()) {
                    em.getTransaction().commit();
                }
            } catch (RuntimeException e) {
                if ((em.getTransaction() != null) && em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
            } finally {
                em.clear();
            }
        }
        em.getTransaction().begin();
    } catch (PersistenceException e) {
        throw new CmsDbSqlException(Messages.get().container(Messages.ERR_GENERIC_SQL_1, ""), e);
    }
}

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;/*from   w w w . j av a2s .c  o  m*/

    try {

        // 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:uk.ac.edukapp.service.WidgetProfileService.java

private List<Widgetprofile> getWidgetProfilesForWidgets(List<Widget> widgets) {
    List<Widgetprofile> widgetProfiles = new ArrayList<Widgetprofile>();

    EntityManager entityManager = getEntityManagerFactory().createEntityManager();
    entityManager.getTransaction().begin();

    ////w ww.ja va  2s. co  m
    // For each Widget returned from the search index, correlate with
    // an Edukapp WidgetProfile, if one exists. Otherwise, construct a
    // new profile for it and persist it.
    //
    for (Widget widget : widgets) {
        Widgetprofile widgetProfile = null;

        //
        // Find matching profile
        //
        try {
            Query wpQuery = entityManager.createNamedQuery("Widgetprofile.findByUri");
            wpQuery.setParameter("uri", widget.getUri());
            widgetProfile = (Widgetprofile) wpQuery.getSingleResult();
            //
            // Ensure dependent objects are available when detached
            //
            widgetProfile.getTags();
            widgetProfile.getActivities();
            widgetProfile.getFunctionalities();
            widgetProfile.getCategories();

            // add stats here otherwise we done have them on the searched widget list.
            WidgetStats widgetStats = entityManager.find(WidgetStats.class, widgetProfile.getId());
            if (widgetStats == null) {
                widgetStats = new WidgetStats();
                widgetStats.setWid_id(widgetProfile.getId());
                widgetStats.setDownloads(0);
                widgetStats.setEmbeds(0);
                widgetStats.setViews(0);
            }

            Query q = entityManager.createNamedQuery("Userrating.getAverageValue");
            q.setParameter("widgetprofile", widgetProfile);

            Number average = (Number) q.getSingleResult();
            if (average == null)
                average = 0.0;

            widgetStats.setAverageRating(average);

            q = entityManager.createNamedQuery("Userrating.getCount");
            q.setParameter("widgetprofile", widgetProfile);

            Long count = (Long) q.getSingleResult();
            widgetStats.setTotalRatings(count);

        } catch (NoResultException e) {

            //
            // Create a new profile
            //
            widgetProfile = new Widgetprofile();
            widgetProfile.setName(widget.getTitle());
            widgetProfile.setWidId(widget.getUri());
            widgetProfile.setIcon(widget.getIcon());
            widgetProfile.setCreated(new Date());
            widgetProfile.setUpdated(new Date());
            widgetProfile.setAuthor(widget.getAuthor());
            widgetProfile.setLicense(widget.getLicense());
            entityManager.persist(widgetProfile);

            //
            // Create the widget description
            //
            WidgetDescription widgetDescription = new WidgetDescription();
            widgetDescription.setWid_id(widgetProfile.getId());
            widgetDescription.setDescription(widget.getDescription());
            widgetProfile.setDescription(widgetDescription);

            //
            // Create the widget stats
            //
            WidgetStats widgetStats = new WidgetStats();
            widgetStats.setWid_id(widgetProfile.getId());
            widgetStats.setDownloads(0);
            widgetStats.setEmbeds(0);
            widgetStats.setViews(0);
            entityManager.persist(widgetStats);

        }

        widgetProfiles.add(widgetProfile);
    }

    entityManager.getTransaction().commit();
    entityManager.close();

    return widgetProfiles;
}

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.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;
}

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

/**
 * Sets the online status of a service registration.
 * /* w ww  .ja v  a 2 s  .  com*/
 * @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:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public Object saveFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem item) throws PersistenceException {
    getIdFieldFromFileStorageClass(fileClass);
    TransactionContext tc = null;//  w  w w.  j a  v  a2  s .co m
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Class clazz = Class.forName(fileClass);
        Object o = clazz.newInstance();
        for (PropertyDescriptor pd : propertyDescriptorsByClassName.get(fileClass)) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, item.get());
            }
        }
        em.persist(o);
        tx.commit();
        return idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }

}