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.projecthandler.ProjectHandlerLocal.java

License:Apache License

/**
 * @see ProjectHandler.addUserToProjects(String, List)
 *//*w w w . j a v a 2 s  .co  m*/
public void addUserToProjects(String p_userId, List p_projects)
        throws RemoteException, ProjectHandlerException {
    StringBuffer projectIdList = new StringBuffer();
    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
        Set s = new TreeSet();
        s.add(p_userId);
        for (Iterator pi = p_projects.iterator(); pi.hasNext();) {
            Project p = (Project) pi.next();
            p.addUserIds(s);
            projectIdList.append(Long.toString(p.getId()));
            if (pi.hasNext()) {
                projectIdList.append(", ");
            }
            session.saveOrUpdate(p);
        }
        // commit all the user additions to projects
        tx.commit();
    } catch (PersistenceException pe) {
        c_category.error("Failed to add user " + p_userId + " to projects " + projectIdList.toString(), pe);
        String[] args = new String[2];
        args[0] = p_userId;
        args[1] = projectIdList.toString();
        throw new ProjectHandlerException(ProjectHandlerException.MSG_FAILED_TO_ADD_USER_TO_PROJECTS, args, pe);
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    }
}

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

License:Apache License

/**
 * @see ProjectHandler.associateUserWithProjectsById(String, List)
 *///from   w w w  .j  a va2s . c  o  m
public void associateUserWithProjectsById(String p_userId, List p_projectIds)
        throws RemoteException, ProjectHandlerException {
    Session session = null;
    Transaction tx = null;
    try {
        // get all the current projects a user is in
        List projects = getProjectsByUser(p_userId);
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
        for (Iterator i = projects.iterator(); i.hasNext();) {
            Project p = (Project) i.next();
            Long pId = p.getIdAsLong();
            if (!p_projectIds.contains(pId)) {
                // deleted user from project and remove from existing id
                // list so it leaves only the NEW ones in the list
                p.removeUserId(p_userId);
                p_projectIds.remove(pId);
                session.saveOrUpdate(p);
            }
        }

        // add the new projects to the user
        for (Iterator pi = p_projectIds.iterator(); pi.hasNext();) {
            long projectId = ((Long) pi.next()).longValue();
            Project p = getProjectById(projectId);
            p.addUserId(p_userId);
            session.saveOrUpdate(p);
        }
        tx.commit();
    } catch (PersistenceException pe) {
        c_category.error("Failed to associate " + p_userId + " with projects " + p_projectIds.toString(), pe);
        String[] args = new String[2];
        args[0] = p_userId;
        args[1] = p_projectIds.toString();
        throw new ProjectHandlerException(ProjectHandlerException.MSG_FAILED_TO_ASSOCIATE_USER_WITH_PROJECTS,
                args, pe);
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    }
}

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

License:Apache License

/**
 * @see ProjectHandler.replaceWorkflowTemplateInL10nProfile(long, long)
 */// w w  w.ja v a  2 s . com
public L10nProfile replaceWorkflowTemplateInL10nProfile(long p_profileId, long p_workflowTemplateInfoId)
        throws RemoteException, ProjectHandlerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
        L10nProfile profile = (L10nProfile) session.get(BasicL10nProfile.class, new Long(p_profileId));
        WorkflowTemplateInfo template = (WorkflowTemplateInfo) session.get(WorkflowTemplateInfo.class,
                new Long(p_workflowTemplateInfoId));
        GlobalSightLocale sourceLocale = profile.getSourceLocale();
        profile.setSourceLocale(sourceLocale);
        GlobalSightLocale targetLocale = template.getTargetLocale();
        template.setSourceLocale(sourceLocale);
        template.setTargetLocale(targetLocale);

        // finally replace the workflow in the specified l10nProfile.
        profile.putWorkflowTemplateInfo(template);
        session.saveOrUpdate(template);
        session.saveOrUpdate(profile);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        c_category.error(
                "Failed to replace workflow " + p_workflowTemplateInfoId + " in L10nProfile " + p_profileId, e);
        String args[] = { Long.toString(p_profileId), Long.toString(p_workflowTemplateInfoId) };
        throw new ProjectHandlerException(ProjectHandlerException.MSG_FAILED_TO_REPLACE_WFI_IN_PROFILE, args,
                e);
    }

    return getL10nProfile(p_profileId);
}

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

License:Apache License

/**
 * Create a translation memory profile object (contains the translation
 * memory profile designed via the GUI).
 * /* w  w w. j  a v  a  2  s. co m*/
 * @param p_tmProfile
 *            - The translation memory profile to be created.
 * 
 * @exception RemoteException
 *                System or network related exception.
 * @exception ProjectHandlerException
 *                Component specific exception
 */
public void modifyTranslationMemoryProfile(TranslationMemoryProfile p_tmProfile)
        throws RemoteException, ProjectHandlerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
        session.update(p_tmProfile);
        Vector newProjectTMs = p_tmProfile.getNewProjectTMs();
        if (newProjectTMs != null && newProjectTMs.size() != 0) {
            Iterator it2 = newProjectTMs.iterator();

            TranslationMemoryProfile tmProfile = (TranslationMemoryProfile) session
                    .get(TranslationMemoryProfile.class, new Long(p_tmProfile.getId()));
            Iterator it = tmProfile.getProjectTMsToLeverageFrom().iterator();
            while (it.hasNext()) {
                LeverageProjectTM levProjTM = (LeverageProjectTM) it.next();
                session.delete(levProjTM);
            }

            Vector v = new Vector();
            while (it2.hasNext()) {
                LeverageProjectTM levProjTM = (LeverageProjectTM) it2.next();
                levProjTM.setTMProfile(tmProfile);
                v.add(levProjTM);
            }
            tmProfile.setAllLeverageProjectTMs(v);

            session.saveOrUpdate(tmProfile);
        }

        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        String[] args = new String[1];
        args[0] = p_tmProfile.getName();
        throw new ProjectHandlerException(ProjectHandlerException.MSG_FAILED_TO_MODIFY_TMP, args, e);
    }
}

From source file:com.globalsight.everest.request.RequestPersistenceAccessor.java

License:Apache License

public static long insertWorkflowRequest(WorkflowRequest p_workflowRequest, Job p_job,
        Collection p_workflowTemplates) throws RequestHandlerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();

    try {//w w  w  .j av a2  s  . c o  m
        p_workflowRequest.setJob(p_job);
        p_job.addWorkflowRequest(p_workflowRequest);

        for (Iterator it = p_workflowTemplates.iterator(); it.hasNext();) {
            WorkflowTemplateInfo wfTempInfo = (WorkflowTemplateInfo) it.next();
            p_workflowRequest.addWorkflowTemplate(wfTempInfo);
        }

        session.saveOrUpdate(p_workflowRequest);
        tx.commit();

        return p_workflowRequest.getId();
    } catch (Exception e) {
        c_logger.error("Failed to insert the new request " + p_workflowRequest.getId(), e);

        // takes in three arguments - external page id, data
        // source type, data source id
        String[] args = new String[3];
        args[0] = new Long(p_workflowRequest.getId()).toString();

        throw new RequestHandlerException(RequestHandlerException.MSG_FAILED_TO_PERSIST_REQUEST, args, e);
    } finally {
        // session.close();
    }
}

From source file:com.globalsight.everest.request.RequestPersistenceAccessor.java

License:Apache License

public static void setExceptionInRequest(long p_requestId, GeneralException p_exception)
        throws RequestHandlerException {
    try {/* w w  w. j a v  a 2s.co m*/
        c_logger.error("setExceptionInRequest: ", p_exception);

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

        Request request = (Request) session.get(Request.class, new Long(p_requestId));
        request.setException(p_exception);

        session.saveOrUpdate(request);

        tx.commit();
        // session.close();
    } catch (Exception e) {
        c_logger.error("Failed to set an exception in request " + p_requestId, e);

        String[] args = new String[2];
        args[0] = Long.toString(p_requestId);

        try {
            args[1] = p_exception.serialize();
        } catch (Exception ex) {
            args[1] = "(exception could not be deserialized)";
        }

        throw new RequestHandlerException(RequestHandlerException.MSG_FAILED_TO_UPDATE_EXCEPTION_IN_REQUEST,
                args, e);
    }
}

From source file:com.globalsight.everest.taskmanager.TaskManagerLocal.java

License:Apache License

/**
 * @see TaskManager.updateStfCreationState(long, String)
 *//*from  w  w  w .  ja va 2 s.c  o m*/
public void updateStfCreationState(long p_taskId, String p_stfCreationState)
        throws RemoteException, TaskException {

    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    // Task task = TaskPersistenceAccessor.getTask(p_taskId, false);
    Task task = (Task) session.get(TaskImpl.class, new Long(p_taskId));

    try {
        // UnitOfWork uow = PersistenceService.getInstance().
        // acquireUnitOfWork();

        // Task clone =
        // (Task)uow.registerObject(task);

        task.setStfCreationState(p_stfCreationState);
        //for GBS-3331: createSTF regard as exporting
        if (p_stfCreationState.equals("COMPLETED")) {
            WorkflowExportingHelper.setAsNotExporting(task.getWorkflow().getId());
        }

        session.saveOrUpdate(task);
        // uow.commit();
        tx.commit();

        // notify the PM if the stf creation failed
        if (Task.FAILED.equals(p_stfCreationState)) {
            notifyProjectManager(task);
        }
    } catch (Exception e) {
        tx.rollback();
        throw new TaskException(TaskException.MSG_FAILED_TO_UPDATE_TASK, null, e);
    } finally {
        if (session != null) {
            // session.close();
        }
    }
}

From source file:com.globalsight.everest.taskmanager.TaskManagerLocal.java

License:Apache License

private Date createReservedTime(Date p_baseDate, TaskImpl p_clonedTask, long p_taskDuration,
        String p_reservedTimeType, String p_userId, Session p_session) throws Exception {
    UserFluxCalendar userCalendar = ServerProxy.getCalendarManager().findUserCalendarByOwner(p_userId);
    UserFluxCalendar calClone = (UserFluxCalendar) p_session.get(UserFluxCalendar.class,
            userCalendar.getIdAsLong());

    Date estimatedDate = ServerProxy.getEventScheduler().determineDate(p_baseDate, userCalendar,
            p_taskDuration);//from  w  ww.j av a  2s  . co m
    // if calendaring module is not installed, don't create reserved times.
    if (Modules.isCalendaringInstalled()) {
        addReservedTimeToUserCal(p_clonedTask, p_reservedTimeType, p_session, calClone, p_baseDate,
                estimatedDate);
    }
    p_session.saveOrUpdate(calClone);
    return estimatedDate;
}

From source file:com.globalsight.everest.taskmanager.TaskManagerLocal.java

License:Apache License

private void unacceptTask(Task task, List wfTaskInfos, Date p_completedby, String p_userId,
        String p_rejectComment) throws Exception {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {//from  ww w  . j a v a 2 s.com
        TaskImpl task_temp = (TaskImpl) session.get(TaskImpl.class, new Long(task.getId()));
        task_temp.setWorkflowTask(((TaskImpl) task).getWorkflowTask());
        task_temp.setAcceptor(null);
        task_temp.setAcceptedDate(null);
        task_temp.setState(Task.STATE_ACTIVE);

        if (p_completedby == null) {
            p_completedby = ServerProxy.getEventScheduler().determineDate(
                    task_temp.getEstimatedAcceptanceDate(), ServerProxy.getCalendarManager()
                            .findDefaultCalendar(String.valueOf(task_temp.getCompanyId())),
                    task_temp.getTaskDuration());
        }
        task_temp.setEstimatedCompletionDate(p_completedby);
        // only during a rejection of a task
        if (p_rejectComment != null) {
            Comment taskComment = new CommentImpl(new Date(), p_userId, p_rejectComment, task_temp);
            task_temp.addTaskComment(taskComment);
        }

        Workflow wf = (Workflow) session.get(WorkflowImpl.class, task_temp.getWorkflow().getIdAsLong());
        // now update the estimated acceptance/completion for the rest
        // of the tasks in the default path (following the accepted
        // task) and the workflow's completion time.
        updateDefaultPathTasks(p_completedby, wfTaskInfos, wf, task_temp.getId(), session);

        // at this point we should create a proposed reserved time for
        // assigness
        // with a 'de-active' state (since the work item will be assigned to
        // them).
        WorkflowTaskInstance wft = m_workflowServer.getWorkflowTaskInstance(p_userId, task_temp.getId(),
                WorkflowConstants.TASK_ALL_STATES);
        Vector workItems = wft.getWorkItems();
        Date baseDate = new Date();

        int size = workItems == null ? -1 : workItems.size();
        for (int i = 0; i < size; i++) {
            EnvoyWorkItem ewi = (EnvoyWorkItem) workItems.get(i);
            if (ewi.getWorkItemState() == WorkflowConstants.TASK_DEACTIVE) {
                createReservedTime(baseDate, task_temp,
                        task_temp.getTaskAcceptDuration() + task_temp.getTaskDuration(),
                        ReservedTime.TYPE_PROPOSED, ewi.getAssignee(), session);
            }
        }

        session.saveOrUpdate(wf);
        session.saveOrUpdate(task_temp);
        tx.commit();
        // now remove the reserved time from the user's calendar.
        // This does not need to be part of the same transaction
        removeScheduledActivity(task_temp.getId(), p_userId);
    } catch (Exception e) {
        tx.rollback();
        // e.printStackTrace();
        CATEGORY.error(e.getMessage(), e);
    } finally {
        if (session != null) {
            // session.close();
        }
    }
}

From source file:com.globalsight.everest.taskmanager.TaskManagerLocal.java

License:Apache License

private void updateDefaultPathTasks(Date p_baseDate, List p_wfTaskInfos, Workflow p_wfClone,
        long p_acceptedTaskId, Session p_session) throws Exception {
    int size = p_wfTaskInfos.size();
    Hashtable ht = p_wfClone.getTasks();
    FluxCalendar calendar = ServerProxy.getCalendarManager()
            .findDefaultCalendar(String.valueOf(p_wfClone.getCompanyId()));
    Date estimatedDate = p_baseDate;
    boolean found = false;
    // loop thru the tasks following the given start task for updating
    // the estimated dates for the tasks and possibly workflow.
    for (int i = 0; i < size; i++) {
        WfTaskInfo wfTaskInfo = (WfTaskInfo) p_wfTaskInfos.get(i);

        TaskImpl task = (TaskImpl) ht.get(new Long(wfTaskInfo.getId()));
        if (!found) {
            found = p_acceptedTaskId == wfTaskInfo.getId();
        } else {//from   w ww  . j  a  va  2 s. c  o m
            TaskImpl task_temp = (TaskImpl) p_session.get(TaskImpl.class, task.getIdAsLong());
            Date acceptBy = ServerProxy.getEventScheduler().determineDate(estimatedDate, calendar,
                    wfTaskInfo.getAcceptanceDuration());
            task_temp.setEstimatedAcceptanceDate(acceptBy);

            Date completeBy = ServerProxy.getEventScheduler().determineDate(estimatedDate, calendar,
                    wfTaskInfo.getTotalDuration());

            task_temp.setEstimatedCompletionDate(completeBy);
            estimatedDate = completeBy;
            p_session.saveOrUpdate(task_temp);
        }
    }

    // For sla report issue
    if (!p_wfClone.isEstimatedCompletionDateOverrided()) {
        p_wfClone.setEstimatedCompletionDate(estimatedDate);
    }
    // For sla report issue
    p_wfClone.updateTranslationCompletedDates();
}