Example usage for org.hibernate Session saveOrUpdate

List of usage examples for org.hibernate Session saveOrUpdate

Introduction

In this page you can find the example usage for org.hibernate Session saveOrUpdate.

Prototype

void saveOrUpdate(Object object);

Source Link

Document

Either #save(Object) or #update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking).

Usage

From source file:com.globalsight.everest.cvsconfig.CVSServerManagerLocal.java

License:Apache License

public void updateRepository(CVSRepository p_repository) throws RemoteException, CVSConfigException {
    Session session = null;
    Transaction transaction = null;/*from  w w  w.j a  v a2 s .c  om*/

    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        CVSRepository oldRepository = getRepository(p_repository.getId());

        if (oldRepository != null) {
            oldRepository.setName(p_repository.getName());
            oldRepository.setFolderName(p_repository.getFolderName());
            oldRepository.setRepository(p_repository.getRepository());
            oldRepository.setServer(p_repository.getServer());
            oldRepository.setLoginUser(p_repository.getLoginUser());
            oldRepository.setLoginPwd(p_repository.getLoginPwd());
            oldRepository.setCVSRootEnv(p_repository.getCVSRootEnv());

            session.saveOrUpdate(oldRepository);
        }

        transaction.commit();
    } catch (Exception e) {
        try {
            transaction.rollback();
        } catch (Exception e2) {
        }
    }
}

From source file:com.globalsight.everest.cvsconfig.CVSServerManagerLocal.java

License:Apache License

public void updateModule(CVSModule p_module) throws RemoteException, CVSConfigException {
    Session session = null;
    Transaction transaction = null;//from   ww w.  j  a v  a  2s  . co m

    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        CVSModule oldModule = getModule(p_module.getId());

        if (oldModule != null) {
            oldModule.setName(p_module.getName());
            oldModule.setModulename(p_module.getModulename());
            oldModule.setBranch(p_module.getBranch());
            oldModule.setServer(p_module.getServer());

            StringBuilder folderPath = new StringBuilder();
            folderPath.append(p_module.getServer().getSandbox()).append(File.separator);
            folderPath.append(p_module.getName());
            String path = folderPath.toString();
            File fPath = new File(path);
            if (!fPath.exists() || fPath.isFile())
                CVSUtil.createFolder(path);
            oldModule.setRealPath(CVSUtil.getBaseDocRoot().concat(folderPath.toString().replace("\\", "/")));
            oldModule.setLastCheckout(p_module.getLastCheckout());

            session.saveOrUpdate(oldModule);
        }

        transaction.commit();
    } catch (Exception e) {
        try {
            transaction.rollback();
        } catch (Exception e2) {
        }
    }
}

From source file:com.globalsight.everest.edit.offline.upload.UploadApi.java

License:Apache License

private void editIssues(List<IssuesVo> issuesVos) {
    IssueImpl issue = null;/*from   w  ww .j a v a2 s . co m*/

    Session session = HibernateUtil.getSession();
    Transaction tx = HibernateUtil.getTransaction();

    Connection conn = null;
    PreparedStatement stmt = null;
    try {

        conn = DbUtil.getConnection();
        conn.setAutoCommit(false);

        String sqlUpdate = "update ISSUE_HISTORY set DESCRIPTION= ? ," + "REPORTED_DATE = ? "
                + " Where REPORTED_BY = ? and REPORTED_DATE = ?";
        stmt = conn.prepareStatement(sqlUpdate);

        int batchUpdate = 0;
        for (IssuesVo vo : issuesVos) {
            issue = (IssueImpl) session.get(IssueImpl.class, new Long(vo.id));

            issue.setTitle(vo.title);
            issue.setPriority(vo.priority);
            issue.setStatus(vo.commentStatus);
            issue.setCategory(vo.failureType);
            issue.setOverwrite(false);
            issue.setShare(false);

            IssueHistoryImpl ih = (IssueHistoryImpl) issue.getHistory().get(0);

            Date date = ih.dateReportedAsDate();
            Date currentDate = Calendar.getInstance().getTime();

            ih.dateReported(Calendar.getInstance().getTime());
            ih.setComment(vo.comment);
            session.saveOrUpdate(ih);

            stmt.setString(1, vo.comment);
            stmt.setDate(2, new java.sql.Date(currentDate.getTime()));
            stmt.setString(3, vo.userId);
            stmt.setDate(4, new java.sql.Date(date.getTime()));

            batchUpdate++;
            if (batchUpdate > DbUtil.BATCH_INSERT_UNIT) {
                stmt.executeBatch();
                batchUpdate = 0;
            }
        }

        if (batchUpdate > 0) {
            stmt.executeBatch();
        }

        HibernateUtil.commit(tx);
    } catch (Exception ex) {
        HibernateUtil.rollback(tx);
        CATEGORY.error("Failed to edit issue.", ex);
    } finally {
        // session.close();
        DbUtil.silentClose(stmt);
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException e) {
                CATEGORY.error(e);
            }

            DbUtil.silentReturnConnection(conn);
        }
    }
}

From source file:com.globalsight.everest.gsedition.GSEditionActivityManagerLocal.java

License:Apache License

public void updateGSEditionActivity(GSEditionActivity p_action) throws RemoteException, GSEditionException {
    Session session = null;
    Transaction transaction = null;/*from w w  w  .  j a  v a 2  s. co m*/
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        GSEditionActivity oldAction = getGSEditionActivityByID(p_action.getId());

        if (oldAction != null) {
            oldAction.setName(p_action.getName());
            oldAction.setFileProfile(p_action.getFileProfile());
            oldAction.setFileProfileName(p_action.getFileProfileName());
            oldAction.setGsEdition(p_action.getGsEdition());
            oldAction.setDescription(p_action.getDescription());
        }

        session.saveOrUpdate(oldAction);
        transaction.commit();
    } catch (Exception e) {
        try {
            transaction.rollback();
        } catch (Exception e2) {
        }
    }
}

From source file:com.globalsight.everest.gsedition.GSEditionManagerLocal.java

License:Apache License

public void updateGSEdition(GSEdition p_action) throws RemoteException, GSEditionException {
    Session session = null;
    Transaction transaction = null;// w  w w  .  j av a  2  s  .  co m
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        GSEdition oldAction = getGSEditionByID(p_action.getId());

        if (oldAction != null) {
            oldAction.setName(p_action.getName());
            oldAction.setHostName(p_action.getHostName());
            oldAction.setHostPort(p_action.getHostPort());
            oldAction.setUserName(p_action.getUserName());
            oldAction.setPassword(p_action.getPassword());
            oldAction.setCompanyID(p_action.getCompanyID());
            oldAction.setDescription(p_action.getDescription());
        }

        session.saveOrUpdate(oldAction);
        transaction.commit();
    } catch (Exception e) {
        try {
            transaction.rollback();
        } catch (Exception e2) {
        }
    }
}

From source file:com.globalsight.everest.jobhandler.JobEventObserverLocal.java

License:Apache License

/**
 * This sets the state of the job to be READY_TO_BE_DISPATCHED
 * //w  w w  .  j a  v a 2s. c om
 * @param Job
 *            p_job
 * @throws JobException,
 *             RemoteException
 */
public void notifyJobReadyToBeDispatchedEvent(Job p_job) throws JobException, RemoteException {
    JobImpl jobImplClone = null;
    Session session = null;
    Transaction transaction = null;
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        jobImplClone = (JobImpl) p_job;
        Iterator it = jobImplClone.getWorkflows().iterator();

        while (it.hasNext()) {
            WorkflowImpl wf = (WorkflowImpl) it.next();
            // only change the state if not cancelled, import failed or
            // if already in the correct state
            if (!wf.getState().equals(Job.READY_TO_BE_DISPATCHED) && !wf.getState().equals(Workflow.CANCELLED)
                    && !wf.getState().equals(Workflow.IMPORT_FAILED)) {
                WorkflowImpl wfClone = (WorkflowImpl) session.get(WorkflowImpl.class, wf.getIdAsLong());
                wfClone.setState(Job.READY_TO_BE_DISPATCHED);
                session.update(wfClone);
            }
        }

        jobImplClone.setState(Job.READY_TO_BE_DISPATCHED);
        session.saveOrUpdate(jobImplClone);

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        throw new JobException(JobException.MSG_FAILED_TO_READY_TO_BE_DISPATCHED, null, e);

    } finally {
        if (session != null) {
            //session.close();
        }
    }
}

From source file:com.globalsight.everest.localemgr.LocaleManagerLocal.java

License:Apache License

/**
 * Persist a GlobalSightLocale//  ww w  .  j a v  a 2 s  .  c  om
 * 
 * @param GlobalSightLocale
 * @return GlobalSightLocale that is persisted
 * @exception LocaleManagerException
 *                Specifies the error, probably persistence exception
 * @exception RemoteException
 *                System or network related exception
 */
public GlobalSightLocale addLocale(GlobalSightLocale p_locale) throws LocaleManagerException, RemoteException {
    String language = p_locale.getLanguage();
    String country = p_locale.getCountry();
    addLanguage(language);
    addCountry(country);
    Session session = null;
    Transaction transaction = null;

    GlobalSightLocale locale = null;
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        String hql = "from GlobalSightLocale l where l.language = :lang " + "and l.country = :coun";
        Map<String, String> map = new HashMap<String, String>();
        map.put("lang", language);
        map.put("coun", country);
        List result = HibernateUtil.search(hql, map);
        if (result != null && result.size() > 0) {
            locale = (GlobalSightLocale) result.get(0);
        } else {
            locale = new GlobalSightLocale(p_locale.getLanguage(), p_locale.getCountry(), false);
        }

        session.saveOrUpdate(locale);
        // only commit if all roles added successfully
        transaction.commit();
    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }

        CATEGORY.error("Failed to add locale " + p_locale.toString(), e);
        String args[] = { p_locale.toString() };
        throw new LocaleManagerException(LocaleManagerException.MSG_FAILED_TO_ADD_LOCALE, args, e);
    } finally {
        if (session != null) {
            // //session.close();
        }
    }
    return locale;
}

From source file:com.globalsight.everest.localemgr.LocaleManagerLocal.java

License:Apache License

/**
 * Add a source/target locales pair. After this, the source/target locale
 * pair becomes valid for a localization profile.
 * <p>/*from   w  w w .j a  v a2s . c  o m*/
 * 
 * @param p_source
 *            The source locale
 * @param p_target
 *            The target locale
 * @param companyId
 * @exception LocaleManagerException
 *                Specifies the error, probably persistence exception
 * @exception RemoteException
 *                System or network related exception
 */
public LocalePair addSourceTargetLocalePair(GlobalSightLocale p_source, GlobalSightLocale p_target,
        long companyId) throws LocaleManagerException, RemoteException {
    Session session = null;
    Transaction transaction = null;
    LocalePair lp = null;
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        String hql = "from LocalePair l where l.source.id = :sId "
                + "and l.target.id = :tId and l.companyId = :cId";
        Map map = new HashMap();
        map.put("sId", p_source.getIdAsLong());
        map.put("tId", p_target.getIdAsLong());
        map.put("cId", companyId);
        List result = HibernateUtil.search(hql, map);
        if (result != null && result.size() > 0) {
            lp = (LocalePair) result.get(0);
            lp.setIsActive(true);
        } else {
            lp = new LocalePair(p_source, p_target, companyId);
        }

        session.saveOrUpdate(lp);
        // add all the roles
        addRoles(p_source, p_target);
        // only commit if all roles added successfully
        transaction.commit();
    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }

        CATEGORY.error("Failed to add a locale pair" + p_source.toString() + " : " + p_target.toString(), e);
        String args[] = { p_source.toString(), p_target.toString() };
        throw new LocaleManagerException(LocaleManagerException.MSG_FAILED_TO_ADD_LOCALE_PAIR, args, e);
    } finally {
        if (session != null) {
            // //session.close();
        }
    }

    return lp;
}

From source file:com.globalsight.everest.page.pageexport.ExportEventObserverLocal.java

License:Apache License

/**
 * Updates the exporting page in the specified Export Batch.
 *///  w w w  .j  a v a 2  s . c  om
private boolean updateExportingPage(long p_batchId, String p_pageId, HttpServletRequest p_request)
        throws ExportEventObserverException {
    ExportingPage page = null;

    Session session = null;
    Transaction transaction = null;
    try {

        s_logger.debug("Looking up export batch id: " + p_batchId + ", pageId: " + p_pageId);

        String responseType = p_request.getParameter(ExportConstants.RESPONSE_TYPE);
        String newState = responseType.equals(ExportConstants.SUCCESS) ? ExportingPage.EXPORTED
                : ExportingPage.EXPORT_FAIL;
        long endTime = Long.parseLong(p_request.getParameter(ExportConstants.EXPORTED_TIME));
        String details = p_request.getParameter(ExportConstants.RESPONSE_DETAILS);
        String exportPath = p_request.getParameter(ExportConstants.ABSOLUTE_EXPORT_PATH);
        String isComponentPage = p_request.getParameter(ExportConstants.IS_COMPONENT_PAGE);

        page = getExportingPageById(p_batchId, Long.parseLong(p_pageId), false);

        if (page != null) {
            session = HibernateUtil.getSession();
            transaction = session.beginTransaction();
            session.evict(page);
            page = (ExportingPage) session.get(ExportingPage.class, page.getIdAsLong());
            page.setEndTime(endTime);
            page.setErrorMessage(details);
            page.setState(newState);
            page.setExportPath(exportPath);
            char isComp = (isComponentPage == null || isComponentPage.equalsIgnoreCase("false")) ? 'N' : 'Y';
            page.setComponentPage(isComp);

            session.saveOrUpdate(page);
            transaction.commit();

            s_logger.debug("updateExportingPage: ExportBatchId " + p_batchId
                    + " was found and the results were recorded " + "for pageId " + p_pageId);

            return true;
        } else {
            s_logger.warn("updateExportingPage: PageId " + p_pageId + " in ExportBatch " + p_batchId
                    + " was NOT found. Either the BatchId or the PageId are not valid.");
            return false;
        }
    } catch (Exception ex) {
        if (transaction != null) {
            transaction.rollback();
        }

        // just warn, but do not throw an exception
        s_logger.warn("updateExportingPage: PageId " + p_pageId + "in ExportBatch " + p_batchId
                + " was NOT found. Either the BatchId or the PageId are not valid.");
    } finally {
        if (session != null) {
            // session.close();
        }
    }

    return false;
}

From source file:com.globalsight.everest.projecthandler.ProjectHandlerLocal.java

License:Apache License

/**
 * Modify an existing localization profile in the system.
 * <p>//  w ww  .  j a v  a2 s.  c  om
 * The original localization profile is left as is. Instead we create a new
 * localization profile which has a new profile sequence number (PK). This
 * will allow for executing references to original profile intact an
 * operational.
 * <p>
 * An entry in profile version table is made which contains a pair of
 * original and modified profile sequence number. This allows for building a
 * version tree in future.
 * <p>
 * 
 * @param p_l10nProfile
 *            The modified localization profile.
 * @exception RemoteException
 *                System or network related exception.
 * @exception ProjectHandlerException
 *                Failed to modify the profile; the cause is indicated by
 *                the exception code.
 */
public void modifyL10nProfile(L10nProfile p_l10nProfile, Vector<WorkflowInfos> workflowInfos,
        long originalLocId) throws RemoteException, ProjectHandlerException {
    // Clone the modified profile so that it can be inserted to
    // system. The modified profile is created with a new profile id.
    BasicL10nProfile modifiedProfile = null;
    // if this is a modify or copy/duplication
    BasicL10nProfile originalProfile = null;
    // "false" = copy/duplication

    org.hibernate.Session session = null;
    Transaction transaction = null;
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();

        modifiedProfile = (BasicL10nProfile) p_l10nProfile;

        if (c_category.isDebugEnabled()) {
            c_category.debug("The value of tm choice in p_l10nProfile is " + p_l10nProfile.getTmChoice());
            c_category.debug("The modified l10n profile is " + modifiedProfile.toDebugString());
            c_category.debug("The value of tm choice is " + modifiedProfile.getTmChoice());
        }

        modifiedProfile.setId(-1L);
        session.saveOrUpdate(modifiedProfile);

        // Now create a version node in profile version table
        if (c_category.isDebugEnabled()) {
            c_category.debug("ProfileID Before = " + originalLocId + " Modified == " + modifiedProfile.getId());
        }

        L10nProfileVersion versionInfo = new L10nProfileVersion(originalLocId, modifiedProfile.getId());
        session.save(versionInfo);

        // delete the old version of it (logically deleted)
        // this is a modification so get the original profile.
        originalProfile = (BasicL10nProfile) session.get(BasicL10nProfile.class, new Long(originalLocId));

        if (originalProfile != null) {
            originalProfile.deactivate();
            session.update(originalProfile);
        }

        // Update those objects dependant on a modified l10nProfile.
        String hql = "from FileProfileImpl f where f.isActive = 'Y' and " + "f.l10nProfileId = :lId";
        Map<String, Long> map = new HashMap<String, Long>();
        map.put("lId", new Long(originalLocId));
        List fProfiles = HibernateUtil.search(hql, map);

        for (int i = 0; i < fProfiles.size(); i++) {
            FileProfileImpl fProfile = (FileProfileImpl) fProfiles.get(i);
            fProfile.setL10nProfileId(modifiedProfile.getId());
            // Need update the "L10N_PROFILE_ID" for reference file profile
            // of XLZ (in fact it is XLF file profile).
            if (fProfile.getReferenceFP() > 0) {
                long refFPId = fProfile.getReferenceFP();
                FileProfileImpl refXlzFP = HibernateUtil.get(FileProfileImpl.class, refFPId, false);
                refXlzFP.setL10nProfileId(modifiedProfile.getId());
            }
        }

        Iterator<?> iterator = fProfiles.iterator();
        while (iterator.hasNext()) {
            session.update(iterator.next());
        }
        // HibernateUtil.update(fProfiles);

        hql = "from DatabaseProfileImpl d where d.l10nProfileId = :lId";
        List dProfiles = HibernateUtil.search(hql, map);

        for (int i = 0; i < dProfiles.size(); i++) {
            DatabaseProfileImpl dProfile = (DatabaseProfileImpl) dProfiles.get(i);
            dProfile.setL10nProfileId(modifiedProfile.getId());
        }

        iterator = dProfiles.iterator();
        while (iterator.hasNext()) {
            session.update(iterator.next());
        }

        // HibernateUtil.update(dProfiles);
        ProjectHandler ph = ServerProxy.getProjectHandler();

        for (int i = 0; i < workflowInfos.size(); i++) {
            L10nProfileWFTemplateInfo l10nProfileWFTemplateInfo = new L10nProfileWFTemplateInfo();
            L10nProfileWFTemplateInfoKey l10nProfileWFTemplateInfoKey = new L10nProfileWFTemplateInfoKey();
            l10nProfileWFTemplateInfoKey.setL10nProfileId(modifiedProfile.getId());
            l10nProfileWFTemplateInfoKey.setWfTemplateId(workflowInfos.get(i).getWfId());
            l10nProfileWFTemplateInfoKey.setMtProfileId(workflowInfos.get(i).getMtProfileId());
            l10nProfileWFTemplateInfo.setKey(l10nProfileWFTemplateInfoKey);
            l10nProfileWFTemplateInfo.setIsActive(workflowInfos.get(i).isActive());

            if (ph.isPrimaryKeyExist(modifiedProfile.getId(), workflowInfos.get(i).getWfId())) {
                updateL10nProfileWfTemplateInfo(session, l10nProfileWFTemplateInfo);
            } else {
                saveL10nProfileWfTemplateInfo(session, l10nProfileWFTemplateInfo);
            }
        }

        transaction.commit();
    } catch (Exception pe) {
        if (transaction != null) {
            transaction.rollback();
        }

        c_category.error(p_l10nProfile.toString() + " " + pe.getMessage(), pe);
        String[] args = new String[1];
        args[0] = Long.toString(originalLocId);
        throw new ProjectHandlerException(ProjectHandlerException.MSG_FAILED_TO_MODIFY_PROFILE, args, pe);
    }
}