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.tuv.TuvEventObserverLocal.java

License:Apache License

private static void createTaskTuvs(Collection p_targetTuvs, long p_taskId) throws TuvException {
    TaskTuv taskTuv = null;// www.j  a  va  2s. c  o  m
    ArrayList newTaskTuvs = new ArrayList(3);

    Session session = null;
    Transaction transaction = null;
    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        Task task = (Task) HibernateUtil.get(TaskImpl.class, p_taskId);

        Iterator it = p_targetTuvs.iterator();
        TaskTuv previousTaskTuv = null;
        while (it.hasNext()) {
            TuvImpl tuvImpl = (TuvImpl) it.next();
            List previousTaskTuvs = TUV_MANAGER_LOCAL.getPreviousTaskTuvs(tuvImpl.getId(), 1);
            if (!previousTaskTuvs.isEmpty()) {
                previousTaskTuv = (TaskTuv) previousTaskTuvs.get(0);
            }
            // copy the current Tuv, store as previous Tuv with new ID
            TuvImpl copyTuvImplClone = new TuvImpl(tuvImpl);
            copyTuvImplClone.setState(TuvState.OUT_OF_DATE);
            session.saveOrUpdate(copyTuvImplClone);
            taskTuv = new TaskTuv(tuvImpl, copyTuvImplClone,
                    (previousTaskTuv != null ? previousTaskTuv.getVersion() + 1 : 1), task);
            newTaskTuvs.add(taskTuv);
            session.save(taskTuv);
        }
        transaction.commit();
    } catch (Exception ex) {
        if (transaction != null) {
            transaction.rollback();
        }

        Collection ids = null;
        try {
            ids = TuvPersistenceHelper.getIds(p_targetTuvs);
        } catch (Throwable e) {
            CATEGORY.error("createTaskTuvs " + e.toString(), e);
            ids = p_targetTuvs;
        }
        CATEGORY.error("createTaskTuvs " + " newTaskTuvs="
                + (newTaskTuvs != null ? newTaskTuvs.toString() : "null") + " " + ids.toString(), ex);
        throw new TuvException(ex.toString(), ex);
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.JobWorkflowsHandler.java

License:Apache License

@Override
public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession httpSession = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) httpSession.getAttribute(SESSION_MANAGER);
    JobSummaryHelper jobSummaryHelper = new JobSummaryHelper();
    Job job = jobSummaryHelper.getJobByRequest(p_request);
    String scorecardFlag = "";
    // deal with ajax request.Start.
    if (p_request.getParameter("obtainTime") != null) {
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        out.write(getLeftTime(p_request, job));
        out.close();//from ww w  . j ava2 s  . c  om
        return;
    } else if (p_request.getParameter("changePriority") != null) {
        long wfId = Long.parseLong(p_request.getParameter("wfId"));
        int priority = Integer.parseInt(p_request.getParameter("priority" + wfId));
        WorkflowManagerLocal wfManager = new WorkflowManagerLocal();
        wfManager.updatePriority(wfId, priority);
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        out.write("OK");
        out.close();
        return;
    } else if (p_request.getParameter("checkIsUploadingForExport") != null) {
        String[] wfIds = p_request.getParameter("wfId").split(" ");
        for (String wfIdStr : wfIds) {
            long wfId = Long.parseLong(wfIdStr);
            Workflow workflow = WorkflowHandlerHelper.getWorkflowById(wfId);
            Hashtable<Long, Task> tasks = workflow.getTasks();
            String result = "";
            for (Long taskKey : tasks.keySet()) {
                if (tasks.get(taskKey).getIsUploading() == 'Y') {
                    result = "uploading";
                    break;
                }
            }

            if (result.length() > 0) {
                PrintWriter out = p_response.getWriter();
                p_response.setContentType("text/html");
                out.write(result);
                out.close();
                break;
            }
        }
        return;
    } else if ("getUpdateWCPercentage".equals(p_request.getParameter("action"))) {
        getUpdateWordCountsPercentage(p_response, job.getJobId());
        return;
    } else if ("jobPageCount".equals(p_request.getParameter("action"))) {
        // Clicked on Save on the Edit Pages screen, do the processing, then
        // send them to JobDetails
        // to see the updated value
        int p_unitOfWork = 3;
        long p_jobId = Long.parseLong(p_request.getParameter("jobId"));
        int numPages = Integer.parseInt(p_request.getParameter("pageCount"));
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        try {
            JobHandler jh = ServerProxy.getJobHandler();
            jh.updatePageCount(job, numPages);
            ServerProxy.getCostingEngine().setEstimatedAmountOfWorkInJob(p_jobId, p_unitOfWork, numPages);
            out.write("OK");
        } catch (Exception e) {
            out.write("Error");
            throw new EnvoyServletException(EnvoyServletException.EX_GENERAL, e);
        } finally {
            out.close();
        }
        return;
    } else if (("updateScorecard".equals(p_request.getParameter("action")))) {
        List<Select> categoryList = ScorecardScoreHelper.initSelectList(job.getCompanyId(),
                PageHandler.getBundle(p_request.getSession()));

        String userId = (String) p_request.getSession().getAttribute(WebAppConstants.USER_NAME);
        Long workflowId = Long.parseLong(p_request.getParameter("savedWorkflowId"));

        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        try {
            for (Workflow workflow : job.getWorkflows()) {
                if (workflow.getId() != workflowId)
                    continue;
                storeScores(workflowId, session);
                for (Select select : categoryList) {
                    ScorecardScore score = new ScorecardScore();
                    score.setScorecardCategory(select.getValue());
                    score.setScore(Integer
                            .parseInt(p_request.getParameter(workflow.getId() + "." + select.getValue())));
                    score.setWorkflowId(workflow.getId());
                    score.setJobId(job.getId());
                    score.setCompanyId(job.getCompanyId());
                    score.setModifyUserId(userId);
                    session.saveOrUpdate(score);
                }
                WorkflowImpl workflowImpl = (WorkflowImpl) workflow;
                String comment = p_request.getParameter(workflow.getId() + ".scoreComment");
                if (!comment.equals(workflowImpl.getScorecardComment())) {
                    workflowImpl.setScorecardComment(comment);
                    session.saveOrUpdate(workflowImpl);
                }
            }
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            e.printStackTrace();
        }

        scorecardFlag = "scorecard";
    }

    if ("scorecard".equals(p_request.getParameter("action")) || "scorecard".equals(scorecardFlag)) {
        List<Select> categoryList = ScorecardScoreHelper.initSelectList(job.getCompanyId(),
                PageHandler.getBundle(p_request.getSession()));

        HashMap<String, ScorecardScore> scoreMap = new HashMap<String, ScorecardScore>();
        setScore(job.getJobId(), scoreMap);

        HashMap<String, String> tmpScoreMap = new HashMap<String, String>();
        List<ScorecardData> scorecardDataList = new ArrayList<ScorecardData>();
        HashMap<String, String> avgScoreMap = new HashMap<String, String>();
        HashMap<String, Integer> avgScoreSum = new HashMap<String, Integer>();
        HashMap<String, Integer> avgScoreNum = new HashMap<String, Integer>();
        DecimalFormat numFormat = new DecimalFormat("#.00");
        List<Workflow> workflows = new ArrayList<Workflow>(job.getWorkflows());
        Collections.sort(workflows,
                new WorkflowComparator(WorkflowComparator.TARG_LOCALE_SIMPLE, Locale.getDefault()));
        for (Workflow workflow : workflows) {
            if (workflow.getScorecardShowType() == -1)
                continue;

            ScorecardData scoreData = new ScorecardData();
            scoreData.setWorkflowId(workflow.getId());
            scoreData.setLocaleDisplayname(workflow.getTargetLocale().toString());
            if (StringUtil.isEmpty(((WorkflowImpl) workflow).getScorecardComment())) {
                scoreData.setScoreComment("");
            } else {
                scoreData.setScoreComment(((WorkflowImpl) workflow).getScorecardComment());
            }

            int localeSocreNum = 0;
            int localeScoreSum = 0;
            for (Select category : categoryList) {
                String mapKey = workflow.getId() + "." + category.getValue();
                if (scoreMap.get(mapKey) == null) {
                    tmpScoreMap.put(mapKey, "--");
                } else {
                    localeSocreNum++;
                    localeScoreSum = localeScoreSum + scoreMap.get(mapKey).getScore();
                    if (avgScoreSum.get(category.getValue()) == null) {
                        avgScoreSum.put(category.getValue(), scoreMap.get(mapKey).getScore());
                        avgScoreNum.put(category.getValue(), 1);
                    } else {
                        avgScoreSum.put(category.getValue(),
                                avgScoreSum.get(category.getValue()) + scoreMap.get(mapKey).getScore());
                        avgScoreNum.put(category.getValue(), avgScoreNum.get(category.getValue()) + 1);
                    }
                    tmpScoreMap.put(mapKey, scoreMap.get(mapKey).getScore() + "");
                }
            }

            if (localeSocreNum > 0) {
                Double avgScore = (double) localeScoreSum / localeSocreNum;
                scoreData.setAvgScore(numFormat.format(avgScore));
            } else {
                scoreData.setAvgScore("--");
            }
            scorecardDataList.add(scoreData);
        }

        int totalScoreSum = 0;
        int totalScoreNum = 0;
        for (Select category : categoryList) {
            if (avgScoreSum.get(category.getValue()) != null) {
                Double avgScore = (double) avgScoreSum.get(category.getValue())
                        / avgScoreNum.get(category.getValue());
                totalScoreSum = totalScoreSum + avgScoreSum.get(category.getValue());
                totalScoreNum = totalScoreNum + avgScoreNum.get(category.getValue());
                avgScoreMap.put(category.getValue(), numFormat.format(avgScore));
            } else {
                avgScoreMap.put(category.getValue(), "--");
            }
        }
        if (totalScoreSum > 0) {
            Double avgScore = (double) totalScoreSum / totalScoreNum;
            avgScoreMap.put("avgScore", numFormat.format(avgScore));
        } else {
            avgScoreMap.put("avgScore", "--");
        }

        sessionMgr.setAttribute("avgScoreMap", avgScoreMap);
        sessionMgr.setAttribute("categoryList", categoryList);
        sessionMgr.setAttribute("scorecardDataList", scorecardDataList);
        sessionMgr.setAttribute("tmpScoreMap", tmpScoreMap);
    } else if ("checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String[] wfIds = p_request.getParameter("wfId").split(" ");
        String jobId = p_request.getParameter("jobId");
        long companyId = job.getCompanyId();
        boolean checkQA = checkQAReport(sessionMgr, companyId, jobId, wfIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap<String, Object>();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if ("downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    } else if ("retrieveTranslatedText".equals(p_request.getParameter("action"))) {
        String workflowId = p_request.getParameter("workflowId");
        Workflow workflow = ServerProxy.getWorkflowManager().getWorkflowById(Long.parseLong(workflowId));
        int percentage = 0;
        JSONObject jsonObject = null;
        Task task = (Task) workflow.getTasks().values().iterator().next();
        percentage = SegmentTuvUtil.getTranslatedPercentageForTask(task);
        jsonObject = new JSONObject();
        jsonObject.put("workflowId", Long.parseLong(workflowId));
        jsonObject.put("percent", percentage);

        p_response.getWriter().write(jsonObject.toJSONString());
        return;
    } else if ("updatePriority".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobId = p_request.getParameter("jobId");
        String selectOption = p_request.getParameter("selectOption");
        JobImpl jobImpl = HibernateUtil.get(JobImpl.class, Long.parseLong(jobId));
        jobImpl.setPriority(Integer.parseInt(selectOption));
        HibernateUtil.merge(job);

        Map<String, Object> returnValue = new HashMap<String, Object>();
        returnValue.put("newPriority", jobImpl.getPriority());
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    }
    // deal with ajax request.End.

    boolean isOk = jobSummaryHelper.packJobSummaryInfoView(p_request, p_response, p_context, job);
    if (!isOk) {
        return;
    }
    parseRequestParameterDistribute(p_request, job);
    packJobWorkflowInfoView(p_request, job);
    packSessionMgrAttr(p_request);

    if (Job.CANCELLED.equals(job.getState())) {
        jobSummaryHelper.jobNotFound(p_request, p_response, p_context, job);
        return;
    }
    // Update the session with this most recently used job
    jobSummaryHelper.updateMRUJob(p_request, job, p_response);
    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * @see WorkflowManager.cancel(String, Workflow)
 *///from   ww w. j  ava 2s .  c o m
public void cancel(String p_idOfUserRequestingCancel, Workflow p_workflow)
        throws RemoteException, WorkflowManagerException {
    String nameOfUserRequestingCancel = UserUtil.getUserNameById(p_idOfUserRequestingCancel);
    if (allowedToCancelWorkflows(p_idOfUserRequestingCancel)) {
        validateStateOfPages(p_workflow);

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

        try {
            wf = (Workflow) session.get(WorkflowImpl.class, p_workflow.getIdAsLong());

            boolean isDispatched = WF_DISPATCHED.equals(wf.getState());
            String oldWorkflowState = wf.getState();
            wf.setState(WF_CANCELLED);

            JobImpl job = (JobImpl) wf.getJob();
            String oldJobState = job.getState();
            resetJobState(session, job, job.getWorkflows());
            session.saveOrUpdate(job);
            session.saveOrUpdate(wf);

            tx.commit();

            ArrayList msg = new ArrayList();
            msg.add(p_workflow.getIdAsLong());
            msg.add(isDispatched);
            msg.add(oldJobState);
            msg.add(oldWorkflowState);
            JmsHelper.sendMessageToQueue(msg, JmsHelper.JMS_CANCEL_WORKFLOW_QUEUE);

            s_logger.info(
                    "Workflow " + p_workflow.getId() + " was cancelled by user " + nameOfUserRequestingCancel);
        } catch (Exception we) {
            tx.rollback();
            s_logger.error("WorkflowManagerLocal::cancel(Workflow)", we);
            String[] args = new String[1];
            args[0] = new Long(p_workflow.getId()).toString();
            throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_CANCEL_WORKFLOW, args,
                    we);
        }
    } else {
        s_logger.error("The user " + nameOfUserRequestingCancel
                + " doesn't have the permission to cancel the workflow.");
        String[] args = { Long.toString(p_workflow.getId()), nameOfUserRequestingCancel };
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_CANCEL_USER_NOT_ALLOWED, args,
                null);
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * @see WorkflowManager.cancel(String, Job, String, boolean)
 *//*from  w  ww. j  av a2  s  .  c  o  m*/
public void cancel(String p_idOfUserRequestingCancel, Job p_job, String p_state, boolean p_reimport)
        throws RemoteException, WorkflowManagerException {
    if (p_state == null) {
        cancel(p_job, p_reimport);
        return;
    }

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

    String nameOfUserRequestingCancel = UserUtil.getUserNameById(p_idOfUserRequestingCancel);
    if (allowedToCancelJobs(p_idOfUserRequestingCancel)) {
        validateStateOfPagesInJob(p_job);
        try {
            Collection<Workflow> wfs = new ArrayList<Workflow>();
            Iterator<Workflow> it = p_job.getWorkflows().iterator();
            Object[] tasks = null;
            List<Object[]> taskList = new ArrayList<Object[]>();
            while (it.hasNext()) {
                Workflow wf = (Workflow) it.next();

                boolean updateIFlow = wf.getState().equals(Workflow.DISPATCHED);

                // if the states are equal - or no state was specified so
                // cancel all workflows
                if (p_state == null || p_state.equals(wf.getState())
                        || (p_state.equals(Job.PENDING) && wf.getState().equals(Workflow.IMPORT_FAILED))) {
                    Workflow wfClone = (Workflow) session.get(WorkflowImpl.class, wf.getIdAsLong());
                    wfClone.setState(WF_CANCELLED);

                    // only update the target page state if not LOCALIZED or
                    // EXPORTED yet
                    if ((wf.getState().equals(Workflow.PENDING))
                            || (wf.getState().equals(Workflow.IMPORT_FAILED))
                            || (wf.getState().equals(Workflow.READY_TO_BE_DISPATCHED))
                            || (wf.getState().equals(Workflow.DISPATCHED))
                            || (wf.getState().equals(Workflow.BATCHRESERVED))) {
                        updatePageState(session, wfClone.getTargetPages(), PG_NOT_LOCALIZED);
                        // also update the secondary target files (if any)
                        updateSecondaryTargetFileState(session, wfClone.getSecondaryTargetFiles(),
                                SecondaryTargetFileState.CANCELLED);
                    }
                    if (updateIFlow) {

                        Map activeTasks = getWFServer().getActiveTasksForWorkflow(wf.getId());
                        if (activeTasks != null) {
                            tasks = activeTasks.values().toArray();
                            taskList.add(tasks);
                            updateTaskState(session, tasks, wfClone.getTasks(), Task.STATE_DEACTIVE);

                            removeReservedTimes(tasks);
                        }
                        WorkflowTemplateInfo wfti = p_job.getL10nProfile()
                                .getWorkflowTemplateInfo(wfClone.getTargetLocale());

                        TaskEmailInfo emailInfo = new TaskEmailInfo(
                                p_job.getL10nProfile().getProject().getProjectManagerId(),
                                wf.getWorkflowOwnerIdsByType(Permission.GROUP_WORKFLOW_MANAGER),
                                wfti.notifyProjectManager(), p_job.getPriority());
                        emailInfo.setJobName(p_job.getJobName());
                        emailInfo.setProjectIdAsLong(new Long(p_job.getL10nProfile().getProjectId()));
                        emailInfo.setSourceLocale(wfClone.getJob().getSourceLocale().toString());
                        emailInfo.setTargetLocale(wfClone.getTargetLocale().toString());
                        emailInfo.setCompanyId(String.valueOf(p_job.getCompanyId()));

                        getWFServer().suspendWorkflow(wfClone.getId(), emailInfo);
                    }
                    wfs.add(wfClone);
                    session.saveOrUpdate(wfClone);
                } else {
                    wfs.add(wf);
                }
            }

            JobImpl jobClone = (JobImpl) session.get(JobImpl.class, new Long(p_job.getId()));
            String lastJobState = resetJobState(session, jobClone, wfs, p_reimport);
            session.saveOrUpdate(jobClone);

            tx.commit();

            // for gbs-1302, cancel interim activities
            // TaskInterimPersistenceAccessor.cancelInterimActivities(taskList);

            if (Job.CANCELLED.equals(lastJobState)) {
                // cleanCorpus(jobId);
                // deleteInProgressTmData(jobClone);
                // GBS-2915, discard a job to remove all job data
                CompanyRemoval removal = new CompanyRemoval(jobClone.getCompanyId());
                removal.removeJob(jobClone);
            }

            // remove all export batch events for this job
            // BB 7/9/03 Quick fix: This is disabled because, for an EXPORT
            // SOURCE, it
            // prevents the batch from from being updated (during export)
            // and the export email from being sent. Right now all events
            // are automatically removed after completion. In the future
            // if we enable the history preservation, we need
            // to revisit this issue. Source export history should be
            // removed after the e-mail.
            // ServerProxy.getExportEventObserver()
            // .removeExportBatchEvents(p_job.getId());

            s_logger.info("Job " + p_job.getId() + " was cancelled by user " + nameOfUserRequestingCancel);
        } catch (Exception e) {
            tx.rollback();
            s_logger.error("WorkflowManagerLocal::cancel(Job)", e);
            String[] args = new String[1];
            args[0] = Long.toString(p_job.getId());
            throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_CANCEL_WORKFLOW, args, e,
                    WorkflowManagerException.PROPERTY_FILE_NAME);

        }
    } else {
        s_logger.error("User " + nameOfUserRequestingCancel + " doesn't have permissions to cancel job "
                + p_job.getId() + " so the cancellation failed.");
        String[] args = { Long.toString(p_job.getId()), nameOfUserRequestingCancel };
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_CANCEL_USER_NOT_ALLOWED, args,
                null);
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * This method allows a client to archive a single workflow
 * /* w w  w .  j a v a 2s.  c om*/
 * @param String
 *            Workflow p_workflow
 * @throws RemoteException
 *             , WorkflowManagerException
 */
public void archiveWorkflow(Workflow p_workflow) throws RemoteException, WorkflowManagerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    boolean canMigrateJobData = false;
    Job job = null;
    try {
        job = (JobImpl) p_workflow.getJob();
        p_workflow.setState(WF_ARCHIVED);
        // If all workflows are in "archived" state...
        if (workflowsHaveState(job.getWorkflows(), WF_ARCHIVED)) {
            job.setState(WF_ARCHIVED);
            canMigrateJobData = true;
        }
        session.saveOrUpdate(p_workflow);
        session.saveOrUpdate(job);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_ARCHIVE_WORKFLOW, null, e);
    }

    if (canMigrateJobData) {
        // Migrate data for this job here.
        try {
            JobDataMigration.migrateJobData(job);
        } catch (Exception e) {

        }

        deleteFolderForDI(job.getCompanyId(), job.getJobId());
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

public boolean archive(Job p_job) throws RemoteException, WorkflowManagerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    boolean canMigrateJobData = false;
    try {/*from  w  ww. j  av  a2s.  co  m*/
        for (Workflow wf : p_job.getWorkflows()) {
            String wfState = wf.getState();
            if (wfState.equals(WF_EXPORTED)) {
                wf.setState(WF_ARCHIVED);
                session.saveOrUpdate(wf);
            }
        }
        if (workflowsHaveState(p_job.getWorkflows(), WF_ARCHIVED)) {
            p_job.setState(WF_ARCHIVED);
            canMigrateJobData = true;
            session.saveOrUpdate(p_job);
        }

        tx.commit();
    } catch (Exception e2) {
        tx.rollback();
        s_logger.error("WorkflowManagerLocal::archive(Job)", e2);
        String[] args = new String[1];
        args[0] = new Long(p_job.getId()).toString();
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_ARCHIVE_WORKFLOW, args, e2,
                WorkflowManagerException.PROPERTY_FILE_NAME);
    }

    if (canMigrateJobData) {
        // Migrate data for this job here.
        // The migration "CAN" fail, it does not impact normal features.
        try {
            JobDataMigration.migrateJobData(p_job);
        } catch (SQLException e) {

        }

        deleteFolderForDI(p_job.getCompanyId(), p_job.getJobId());
    }
    return canMigrateJobData;
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * This method allows a client to dispatch a workflow
 * /*from ww  w . ja v a  2  s.  co m*/
 * @param String
 *            Workflow p_workflow
 * @throws RemoteException
 *             , WorkflowManagerException
 */
public void dispatch(Workflow p_workflow) throws RemoteException, WorkflowManagerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    JbpmContext ctx = null;

    try {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("dispatch " + p_workflow.getId());
        }

        Workflow wfClone = (Workflow) session.get(WorkflowImpl.class, p_workflow.getIdAsLong());

        long taskId = -1;
        String actionType = null;

        if (WF_READY.equals(wfClone.getState()) || Workflow.PENDING.equals(wfClone.getState())) {
            Job j = wfClone.getJob();
            TaskEmailInfo emailInfo = createTaskEmailInfo(j, wfClone);
            String pm = emailInfo.getProjectManagerId();

            ArrayList returnValue = dispatchWorkflow(wfClone, session, new Date(), emailInfo);

            taskId = ((Long) (returnValue).get(0)).longValue();
            actionType = returnValue.get(3) != null ? (String) returnValue.get(3) : null;

            // For sla issue
            if (wfClone.isEstimatedTranslateCompletionDateOverrided()) {
                updateEstimatedTranslateCompletionDate(wfClone.getId(),
                        wfClone.getEstimatedTranslateCompletionDate());
            }

            possiblyUpdateJob(session, wfClone, WF_DISPATCHED);
            session.saveOrUpdate(wfClone);
            tx.commit();

            if (((Boolean) returnValue.get(1)).booleanValue()) {
                exportForStfCreation(new Long(taskId), wfClone, pm);
            }
            // GBS-3002
            if (actionType != null) {
                SystemActionPerformer.perform(actionType, taskId, pm);
            }

            Task task = (Task) wfClone.getTasks().get(taskId);
            long jobId = task.getJobId();
            L10nProfile l10nProfile = ServerProxy.getJobHandler().getL10nProfileByJobId(jobId);
            long wfStatePostId = l10nProfile.getWfStatePostId();
            if (wfStatePostId != -1) {
                WfStatePostThread myTask = new WfStatePostThread(task, null, true);
                Thread t = new MultiCompanySupportedThread(myTask);
                t.start();
            }

            if (task != null) {
                task.setProjectManagerName(pm);
                TaskHelper.autoAcceptTask(task);
            }
        }
    } catch (Exception e2) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        s_logger.error("Failed to dispatch workflow: " + p_workflow.getId() + " p_workflow="
                + WorkflowHelper.toDebugString(p_workflow), e2);
        String[] args = new String[1];
        args[0] = new Long(p_workflow.getId()).toString();
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_DISPATCH_WORKFLOW, args, e2,
                WorkflowManagerException.PROPERTY_FILE_NAME);
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

public void dispatch(Job p_job) throws RemoteException, WorkflowManagerException {
    JobImpl jobClone = null;/*from w ww .  j ava2s. c  om*/
    Session session = HibernateUtil.getSession();
    Transaction transaction = null;
    JbpmContext ctx = null;

    try {
        transaction = HibernateUtil.getTransaction();
        jobClone = (JobImpl) session.get(JobImpl.class, new Long(p_job.getId()));
        if (jobClone != null) {
            // refresh job object in the session
            session.evict(jobClone);
            jobClone = (JobImpl) session.get(JobImpl.class, new Long(p_job.getId()));
        }
        Iterator it = jobClone.getWorkflows().iterator();
        // a Map containing task id as key and workflow as value.
        // This is used for possible creation of STF.
        HashMap<Long, Workflow> map = new HashMap<Long, Workflow>(1);
        HashMap<Long, String> etfMap = new HashMap<Long, String>(1);
        Date startDate = new Date();
        ExecutorService pool = Executors.newFixedThreadPool(MAX_THREAD);
        while (it.hasNext()) {
            Workflow wf = (Workflow) it.next();
            if (WF_READY.equals(wf.getState()) || Workflow.PENDING.equals(wf.getState())) {
                Workflow wfClone = (Workflow) session.get(WorkflowImpl.class, wf.getIdAsLong());
                TaskEmailInfo emailInfo = createTaskEmailInfo(jobClone, wfClone);

                ArrayList returnValue = dispatchWorkflow(wfClone, session, startDate, emailInfo);

                long taskId = ((Long) returnValue.get(0)).longValue();
                if (taskId != -1) {
                    Object actionType = returnValue.get(3);
                    if (actionType != null) {
                        etfMap.put(taskId, (String) actionType);
                    }

                    Task task = (Task) wfClone.getTasks().get(taskId);
                    long jobId = task.getJobId();
                    L10nProfile l10nProfile = ServerProxy.getJobHandler().getL10nProfileByJobId(jobId);
                    long wfStatePostId = l10nProfile.getWfStatePostId();
                    if (wfStatePostId != -1) {
                        WfStatePostThread myTask = new WfStatePostThread(task, null, true);
                        pool.execute(myTask);
                    }

                    // For sla issue
                    if (wfClone.isEstimatedTranslateCompletionDateOverrided()) {
                        updateEstimatedTranslateCompletionDate(wfClone.getId(),
                                wfClone.getEstimatedTranslateCompletionDate());
                    }

                    // prepare the map for possible creation of secondary
                    // target
                    // files
                    if (((Boolean) returnValue.get(1)).booleanValue()) {
                        map.put(new Long(taskId), wfClone);
                    }
                }
                session.saveOrUpdate(wfClone);
            }
        }
        pool.shutdown();

        jobClone.setState(WF_DISPATCHED);
        updatePageState(session, jobClone.getSourcePages(), PG_ACTIVE_JOB);
        session.saveOrUpdate(jobClone);

        HibernateUtil.commit(transaction);

        String pmId = p_job.getL10nProfile().getProject().getProjectManagerId();
        if (map.size() > 0) {
            Object[] keys = map.keySet().toArray();
            for (int i = 0; i < keys.length; i++) {
                Long stfTaskId = (Long) keys[i];
                Workflow wf = map.get(stfTaskId);
                exportForStfCreation(stfTaskId, wf, pmId);
            }
        }
        // GBS-3002
        if (etfMap.size() > 0) {
            Object[] keys = etfMap.keySet().toArray();
            for (int i = 0; i < keys.length; i++) {
                Long taskId = (Long) keys[i];
                String actionType = etfMap.get(taskId);
                SystemActionPerformer.perform(actionType, taskId, pmId);
            }
        }
    } catch (Exception e2) {
        HibernateUtil.rollback(transaction);
        s_logger.error("Failed to dispatch: " + p_job.getJobName(), e2);
        String[] args = new String[1];
        args[0] = new Long(p_job.getId()).toString();
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_DISPATCH_WORKFLOW, args, e2,
                WorkflowManagerException.PROPERTY_FILE_NAME);
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }

    runJobCreationScript(p_job);
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * @deprecated For sla report issue.//from  w w w  .  j  a v  a  2s.c  o m
 * @see WorkflowManager.updatePlannedCompletionDate(String, long, Date)
 */
public void updatePlannedCompletionDate(long p_workflowId, Date p_plannedCompletionDate)
        throws WorkflowManagerException, RemoteException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
        Workflow wf = (Workflow) session.get(WorkflowImpl.class, new Long(p_workflowId));
        wf.setPlannedCompletionDate(p_plannedCompletionDate);
        session.saveOrUpdate(wf);
        tx.commit();

        // send notification if the estimate completion date exceeds planned
        // date
        sendNotification(wf);
    } catch (Exception e) {
        tx.rollback();
        String[] args = { String.valueOf(p_workflowId) };
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_UPDATE_PCD, args, e);
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * For sla report issue User can override the estimatedCompletionDate.
 * // w w w .  j  a  v  a  2 s.  c o  m
 * @see WorkflowManager.updateEstimatedCompletionDate(String, long, Date)
 */
public void updateEstimatedCompletionDate(long p_workflowId, Date p_estimatedCompletionDate)
        throws WorkflowManagerException, RemoteException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
        Workflow wf = (Workflow) session.get(WorkflowImpl.class, new Long(p_workflowId));
        wf.setEstimatedCompletionDate(p_estimatedCompletionDate);
        wf.setEstimatedCompletionDateOverrided(true);
        session.saveOrUpdate(wf);
        tx.commit();

        // send notification if the estimate completion date exceeds planned
        // date
        // sendNotification(clone);
        sendNotification(wf);
    } catch (Exception e) {
        String[] args = { String.valueOf(p_workflowId) };
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_UPDATE_PCD, args, e);
    }
}