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.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * @see WorkflowManager.updateEstimatedTranslateCompletionDate(long, Date)
 *///from   w w w. j  a va  2 s. c  om
public void updateEstimatedTranslateCompletionDate(long p_workflowId, Date p_estimatedTranslateCompletionDate)
        throws WorkflowManagerException, RemoteException {
    Session session = HibernateUtil.getSession();
    Transaction tx = HibernateUtil.getTransaction();
    try {
        Workflow wf = (Workflow) session.get(WorkflowImpl.class, new Long(p_workflowId));
        refreshWorkflowInstance(wf);

        Date oriEstimatedTranslateCompletionDate = wf.getEstimatedTranslateCompletionDate();
        wf.setEstimatedTranslateCompletionDate(p_estimatedTranslateCompletionDate);
        wf.setEstimatedTranslateCompletionDateOverrided(true);

        if (Workflow.READY_TO_BE_DISPATCHED.equals(wf.getState()) && !wf.isEstimatedCompletionDateOverrided()) {
            List wfTaskInfos = ServerProxy.getWorkflowServer().timeDurationsInDefaultPath(null, wf.getId(), -1);
            FluxCalendar defaultCalendar = ServerProxy.getCalendarManager()
                    .findDefaultCalendar(String.valueOf(wf.getCompanyId()));

            Hashtable tasks = wf.getTasks();

            long workflowDuration = 0l;

            for (int i = wfTaskInfos.size() - 1; i >= 0; i--) {
                WfTaskInfo wfTaskInfo = (WfTaskInfo) wfTaskInfos.get(i);
                TaskImpl task = (TaskImpl) tasks.get(new Long(wfTaskInfo.getId()));
                if (task == null)
                    continue;

                Activity act = ServerProxy.getJobHandler().getActivity(task.getTaskName());

                if (Activity.isTranslateActivity(act.getType())) {
                    updateTaskTimeToComplete(task, oriEstimatedTranslateCompletionDate,
                            p_estimatedTranslateCompletionDate, session);
                    break;
                }

                workflowDuration += wfTaskInfo.getTotalDuration();
            }

            wf.setEstimatedCompletionDate(ServerProxy.getEventScheduler()
                    .determineDate(p_estimatedTranslateCompletionDate, defaultCalendar, workflowDuration));
        } else if (Workflow.DISPATCHED.equals(wf.getState())) {
            Task translateTask = null;
            List taskInfos = getTaskInfosInDefaultPath(wf);
            if (taskInfos != null) {
                for (int i = taskInfos.size() - 1; i >= 0; i--) {
                    TaskInfo taskInfo = (TaskInfo) taskInfos.get(i);
                    Task task = (Task) wf.getTasks().get(new Long(taskInfo.getId()));
                    Activity act = ServerProxy.getJobHandler().getActivity(task.getTaskName());

                    if (act.isType(Task.TYPE_TRANSLATE)) {
                        translateTask = task;
                        break;
                    }
                }
            }

            // Update translate task & workflow
            if ((translateTask != null) && (translateTask.getState() != Task.STATE_COMPLETED)) {
                translateTask.setEstimatedCompletionDate(p_estimatedTranslateCompletionDate);

                List wfTaskInfos = getWFServer().timeDurationsInDefaultPath(null, p_workflowId, -1);

                updateDefaultPathTasks(MODIFY_ACTION, new Date(), wfTaskInfos, wf, translateTask.getId(), false,
                        p_estimatedTranslateCompletionDate, session);
                session.saveOrUpdate(translateTask);

                updateTaskTimeToComplete(translateTask, oriEstimatedTranslateCompletionDate,
                        p_estimatedTranslateCompletionDate, session);
            }
        }
        session.saveOrUpdate(wf);
        HibernateUtil.commit(tx);
    } catch (Exception e) {
        HibernateUtil.rollback(tx);
        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

/**
 * Creates a reserved time along with a possible buffer and add it to the
 * acceptor's calendar./* ww  w.ja v  a  2s.co m*/
 */
private void createReservedTime(Task task, String reservedTimeType, Session session) throws Exception {
    UserFluxCalendar userCalendar = ServerProxy.getCalendarManager()
            .findUserCalendarByOwner(task.getAcceptor());
    UserFluxCalendar calClone = (UserFluxCalendar) session.get(UserFluxCalendar.class,
            userCalendar.getIdAsLong());
    addReservedTimeToUserCal(task, reservedTimeType, session, calClone, task.getAcceptedDate(),
            task.getEstimatedCompletionDate());

    session.saveOrUpdate(calClone);
}

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

License:Apache License

/**
 * @see WorkflowManager.reassignWorkflowOwners(long, List)
 *///from  www  . j a v  a 2  s.  co  m
public void reassignWorkflowOwners(long p_workflowId, List p_workflowOwners)
        throws RemoteException, WorkflowManagerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
        Workflow wf = (Workflow) session.get(WorkflowImpl.class, new Long(p_workflowId));
        // first delete all the previous owners (EXCEPT FOR 'PM')
        for (Iterator it = wf.getWorkflowOwners().iterator(); it.hasNext();) {
            WorkflowOwner owner = (WorkflowOwner) it.next();
            if (!Permission.GROUP_PROJECT_MANAGER.equals(owner.getOwnerType())) {
                wf.removeWorkflowOwner(owner);
                session.delete(owner);
                it.remove();
            }
        }

        // now add the newly assigned owners
        int size = p_workflowOwners.size();
        for (int i = 0; i < size; i++) {
            WorkflowOwner wfo = (WorkflowOwner) p_workflowOwners.get(i);
            wf.addWorkflowOwner(wfo);
        }

        // set the new owners in the iFlow's process instance
        assignWorkflowInstanceOwners(p_workflowId, wf.getWorkflowOwners());

        session.saveOrUpdate(wf);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw new WorkflowManagerException(e);
    }
}

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

License:Apache License

private void createTasks(Session p_session, Vector p_workflowTaskInstances, Hashtable p_modifiedTasks,
        Workflow p_workflow, List p_wfTaskInfos) throws Exception {
    TaskImpl task = null;/*  w  w  w. j a va 2 s. com*/
    try {

        int size = p_workflowTaskInstances.size();
        CostingEngine ce = ServerProxy.getCostingEngine();
        for (int i = 0; i < size; i++) {
            WorkflowTaskInstance inst = (WorkflowTaskInstance) p_workflowTaskInstances.elementAt(i);
            TaskInfoBean taskInfo = null;
            taskInfo = (TaskInfoBean) p_modifiedTasks.get(new Long(inst.getSequence()));
            task = new TaskImpl();
            task.setId(inst.getTaskId());
            task.setWorkflow(p_workflow);
            p_workflow.addTask(task);
            task.setName(inst.getActivityName());
            task.setState(TaskImpl.STATE_DEACTIVE);
            task.setType(getActivityType(task.getName()));
            task.setCompanyId(p_workflow.getCompanyId());
            Rate pageBasedRate = null;
            String hourAmount = null;
            // For Expenses
            long rateId = inst.getExpenseRateId();
            task.setRateSelectionCriteria(inst.getRateSelectionCriteria());
            if (rateId > 0) {
                // need to create a clone because the rate already exists -
                // so
                // don't want to try and insert but just set up the
                // relationship
                Rate rateClone = (Rate) ce.getRate(rateId);
                task.setExpenseRate(rateClone);
                if (rateClone.getRateType().equals(Rate.UnitOfWork.PAGE_COUNT)) {
                    pageBasedRate = rateClone;
                } else {
                    if (rateClone.getRateType().equals(Rate.UnitOfWork.HOURLY)) {
                        AmountOfWork cloneNewAow = null;
                        if (taskInfo != null) {
                            hourAmount = taskInfo.getEstimatedHours();
                        }
                        if (hourAmount != null) {
                            AmountOfWork newAow = rateClone.createAmountOfWork();
                            // set the hour amount as estimated hours
                            newAow.setEstimatedAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                            cloneNewAow = newAow;
                            // p_session.save(cloneNewAow);
                        }
                        task.setAmountOfWork(cloneNewAow);
                    }
                }
            }
            // for Revenue
            rateId = inst.getRevenueRateId();
            if (rateId > 0) {
                // need to create a clone because the rate already exists -
                // so
                // don't want to try and insert but just set up the
                // relationship
                // Rate rateClone = (Rate) p_uow.registerObject(ce
                // .getRate(rateId));
                Rate rateClone = (Rate) ce.getRate(rateId);
                task.setRevenueRate(rateClone);
                if (pageBasedRate == null && rateClone.getRateType().equals(Rate.UnitOfWork.PAGE_COUNT)) {
                    pageBasedRate = rateClone;
                } else {
                    if (rateClone.getRateType().equals(Rate.UnitOfWork.HOURLY)) {
                        AmountOfWork cloneNewAow = null;
                        if (hourAmount == null) {
                            if (taskInfo != null) {
                                hourAmount = taskInfo.getEstimatedHours();
                            }
                            if (hourAmount != null) {
                                AmountOfWork newAow = rateClone.createAmountOfWork();
                                // set the hour amount as estimated hours
                                newAow.setEstimatedAmount(
                                        Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                                cloneNewAow = newAow;
                                // p_session.save(cloneNewAow);
                            }
                            task.setAmountOfWork(cloneNewAow);
                        }
                    }
                }
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("createTasks : " + " workflow=" + p_workflow.getId() + " WorkflowTaskInstance="
                        + WorkflowHelper.toDebugString(inst) + GlobalSightCategory.getLineContinuation()
                        + " task=" + task.toString());
            }

            // if a page based rate is assigned to one of the expenses
            // then need to add that amount of work to the task class.
            if (pageBasedRate != null) {
                AmountOfWork pageAow = pageBasedRate.createAmountOfWork();
                int numOfPages = task.getWorkflow().getJob().getPageCount();
                pageAow.setEstimatedAmount(numOfPages);
                // p_session.save(pageAow);
                task.setAmountOfWork(pageAow);
            }
            p_session.saveOrUpdate(task);

            for (Object ob : task.getWorkSet()) {
                if (ob instanceof AmountOfWork) {
                    AmountOfWork aWork = (AmountOfWork) ob;
                    p_session.saveOrUpdate(aWork);
                }
            }
        }
    } catch (Exception e) {
        s_logger.error("Failed to get a rate for a task.", e);
        // if a task was set then specify the task - otherwise specify all
        // because
        // the costing engine couldn't be retrieved to get rates.
        String taskId = task != null ? Long.toString(task.getId()) : "all";
        String args[] = { taskId };
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_FIND_RATE_FOR_TASK, args, e);
    }

    if (s_logger.isDebugEnabled()) {
        s_logger.debug(
                "createTasks : " + " setCompletionFraction numerator=" + p_workflow.getCompletionNumerator()
                        + " denominator=" + p_workflow.getCompletionDenominator());
    }
}

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

License:Apache License

/**
 * Modify one task.//from  w w w  . j a va2 s .c  o  m
 */
private Task modifyTask(Task p_task, TaskInfoBean p_tib, Session p_session) throws Exception {
    // modify the rate - since it is the only thing on a task
    // that can be modified at this place
    Task taskClone = (Task) p_session.get(TaskImpl.class, new Long(p_task.getId()));
    Rate expenseRate = null;
    Rate oldExpenseRate = null;
    Rate revenueRate = null;
    Rate oldRevenueRate = null;
    boolean allowRemovalOfAmountOfWork = false;

    // Rate pageBasedRate = null;
    // Get the Expense Rate
    expenseRate = p_tib.getExpenseRate();
    oldExpenseRate = p_task.getExpenseRate();
    // Get the Revenue Rate
    revenueRate = p_tib.getRevenueRate();
    oldRevenueRate = p_task.getRevenueRate();

    taskClone.setRateSelectionCriteria(p_tib.getRateSelectionCriteria());
    taskClone.setIsReportUploadCheck(p_tib.getIsReportUploadCheck());
    // update task name and type
    String taskName = p_tib.getActivityName();
    taskClone.setTaskName(taskName);
    Activity activity = ServerProxy.getJobHandler().getActivity(taskName);
    if (activity != null) {
        taskClone.setType(activity.getActivityType());
    }

    if (expenseRate == null && revenueRate == null) {
        allowRemovalOfAmountOfWork = true;
    } else if (expenseRate == null && revenueRate != null) {
        if (oldExpenseRate != null) {
            if (oldExpenseRate.getRateType() != revenueRate.getRateType()) {
                allowRemovalOfAmountOfWork = true;
            }
        }
    } else if (expenseRate != null && revenueRate == null) {
        if (oldRevenueRate != null) {
            if (oldRevenueRate.getRateType() != expenseRate.getRateType()) {
                allowRemovalOfAmountOfWork = true;
            }
        }
    }

    // if a expenseRate is being set
    if (expenseRate != null) {
        Rate oldRate = null;
        oldRate = p_task.getExpenseRate();
        AmountOfWork oldAow = (oldRate == null) ? null : p_task.getAmountOfWork(oldRate.getRateType());

        // need to create a clone because the rate already exists - so
        // don't want to try and insert but just set up the relationship
        taskClone.setExpenseRate(expenseRate);
        if (expenseRate.getRateType().equals(Rate.UnitOfWork.PAGE_COUNT)) {
            // pageBasedRate = expenseRate;
        } else {
            if (expenseRate.getRateType().equals(Rate.UnitOfWork.HOURLY)) {
                AmountOfWork cloneNewAow = null;
                String hourAmount = null;
                boolean isEstimatedAmount = false;

                // if the task is complete then need to be updating the
                // actual hours - if not complete yet then update the
                // estimated hours.
                if ((hourAmount = p_tib.getActualHours()) == null) {
                    isEstimatedAmount = true; // specifies that the
                    // estimated amount
                    // is being updated
                    hourAmount = p_tib.getEstimatedHours();
                }

                // if one exists
                if (oldAow != null) {
                    // if the amount is cleared and it is persisted
                    // delete the amount
                    if (hourAmount == null) {
                        p_session.delete(oldAow);
                    } else
                    // there is a new amount
                    {
                        cloneNewAow = oldAow;
                        // set the unit of work just in case it changed
                        cloneNewAow.setUnitOfWork(expenseRate.getRateType());
                        if (isEstimatedAmount) {
                            cloneNewAow.setEstimatedAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        } else {
                            cloneNewAow.setActualAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        }
                        p_session.update(cloneNewAow);
                    }
                } else
                // no previous uow
                {
                    // if an estimate is to be set
                    if (hourAmount != null) {
                        AmountOfWork newAow = taskClone.getExpenseRate().createAmountOfWork();
                        if (isEstimatedAmount) {
                            newAow.setEstimatedAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        } else {
                            newAow.setActualAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        }
                        cloneNewAow = newAow;
                        // p_session.save(cloneNewAow);
                    }
                }
                taskClone.setAmountOfWork(cloneNewAow);
            }
        }

    } else
    // NO RATE
    {
        // if there was a rate AND an amount of work specified
        // remove the amount of work
        if (p_task.getExpenseRate() != null
                && p_task.getAmountOfWork(p_task.getExpenseRate().getRateType()) != null
                && allowRemovalOfAmountOfWork) {
            AmountOfWork aow = p_task.getAmountOfWork(p_task.getExpenseRate().getRateType());
            // remove relationship and delete
            taskClone.removeAmountOfWork(aow.getUnitOfWork());
            // if persistent
            if (aow != null) {
                p_session.delete(aow);
            }
        }
        taskClone.setExpenseRate(null);
    }

    // if a revenueRate is being set
    if (revenueRate != null) {
        Rate oldRate = null;
        oldRate = p_task.getRevenueRate();
        AmountOfWork oldAow = (oldRate == null) ? null : p_task.getAmountOfWork(oldRate.getRateType());

        // need to create a clone because the revenueRate already exists -
        // so
        // don't want to try and insert but just set up the relationship
        taskClone.setRevenueRate(revenueRate);
        if (revenueRate.getRateType().equals(Rate.UnitOfWork.PAGE_COUNT)) {
            // pageBasedRate = revenueRate;
        } else {
            if (revenueRate.getRateType().equals(Rate.UnitOfWork.HOURLY)) {
                AmountOfWork cloneNewAow = null;
                String hourAmount = null;
                boolean isEstimatedAmount = false;

                // if the task is complete then need to be updating the
                // actual hours - if not complete yet then update the
                // estimated hours.
                if ((hourAmount = p_tib.getActualHours()) == null) {
                    isEstimatedAmount = true; // specifies that the
                    // estimated amount
                    // is being updated
                    hourAmount = p_tib.getEstimatedHours();
                }

                // if one exists
                if (oldAow != null) {
                    // if the amount is cleared and it is persisted
                    // delete the amount
                    if (hourAmount == null) {
                        p_session.delete(oldAow);
                    } else
                    // there is a new amount
                    {
                        cloneNewAow = oldAow;
                        // set the unit of work just in case it changed
                        cloneNewAow.setUnitOfWork(revenueRate.getRateType());
                        if (isEstimatedAmount) {
                            cloneNewAow.setEstimatedAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        } else {
                            cloneNewAow.setActualAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        }
                        p_session.update(cloneNewAow);
                    }
                } else
                // no previous uow
                {
                    // if an estimate is to be set
                    if (hourAmount != null) {
                        AmountOfWork newAow = taskClone.getRevenueRate().createAmountOfWork();
                        if (isEstimatedAmount) {
                            newAow.setEstimatedAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        } else {
                            newAow.setActualAmount(
                                    Double.parseDouble((hourAmount.length() == 0) ? "0" : hourAmount));
                        }
                        // cloneNewAow = (AmountOfWork) p_uow
                        // .registerNewObject(newAow);
                        cloneNewAow = newAow;
                        // p_session.save(cloneNewAow);
                    }
                }
                taskClone.setAmountOfWork(cloneNewAow);
            }
        }

    } else
    // No Rate
    {
        // if there was a rate AND an amount of work specified
        // remove the amount of work
        if (p_task.getRevenueRate() != null
                && p_task.getAmountOfWork(p_task.getRevenueRate().getRateType()) != null
                && allowRemovalOfAmountOfWork) {
            AmountOfWork aow = p_task.getAmountOfWork(p_task.getRevenueRate().getRateType());
            // remove relationship and delete
            taskClone.removeAmountOfWork(aow.getUnitOfWork());
            // if persistent
            if (aow != null) {
                p_session.delete(aow);
            }
        }
        taskClone.setRevenueRate(null);
    }
    p_session.saveOrUpdate(taskClone);

    if (taskClone instanceof TaskImpl) {
        TaskImpl task = (TaskImpl) taskClone;
        for (Object ob : task.getWorkSet()) {
            if (ob instanceof AmountOfWork) {
                AmountOfWork aWork = (AmountOfWork) ob;
                p_session.saveOrUpdate(aWork);
            }
        }
    }

    return p_task;
}

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

License:Apache License

private void updateDuration(long p_wfiId, List p_wfTaskInfos, Session session) throws WorkflowManagerException {
    try {//from   w w  w  .ja v a  2s.c o m
        long durationInMilli = 0;
        int size = p_wfTaskInfos.size();
        for (int i = 0; i < size; i++) {
            WfTaskInfo wfTaskInfo = (WfTaskInfo) p_wfTaskInfos.get(i);
            // get all the complete durations in the default path (not the
            // accept time)
            durationInMilli += wfTaskInfo.getCompletionDuration();
        }

        // convert the millisec to minutes since it's the smallest unit
        // of time used for each activity of a workflow.
        int duration = (int) (durationInMilli / 60000);

        Workflow wf = (Workflow) session.get(WorkflowImpl.class, new Long(p_wfiId));
        wf.setDuration(duration);
        session.saveOrUpdate(wf);
    } catch (Exception e) {
        String eArgs[] = new String[1];
        eArgs[0] = Long.toString(p_wfiId);
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_UPDATE_WORKFLOW_DURATION,
                eArgs, e);
    }
}

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

License:Apache License

private List<Task> updateTaskState(Session p_session, List<WfTaskInfo> p_nextWfTaskInfos, Hashtable p_tasks,
        int p_state) throws Exception {
    int size = p_nextWfTaskInfos.size();
    List<Task> tasks = new ArrayList<Task>(size);
    for (int i = 0; i < size; i++) {
        WfTaskInfo wfti = p_nextWfTaskInfos.get(i);
        Task task = (Task) p_tasks.get(new Long(wfti.getId()));
        Task taskClone = (Task) p_session.get(TaskImpl.class, new Long(task.getId()));
        taskClone.setState(p_state);// w w  w. j  a va  2 s  .c  om
        tasks.add(taskClone);
        p_session.saveOrUpdate(taskClone);
    }

    return tasks;
}

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

License:Apache License

private void updateTaskState(Session p_session, Object[] p_activeTasks, Hashtable p_wfTasks, int p_state)
        throws Exception {
    int size = p_activeTasks == null ? -1 : p_activeTasks.length;
    for (int i = 0; i < size; i++) {
        WorkflowTaskInstance wfti = (WorkflowTaskInstance) p_activeTasks[i];
        Task task = (Task) p_wfTasks.get(new Long(wfti.getTaskId()));
        task.setState(p_state);//  w  ww . ja v  a2s .com
        p_session.saveOrUpdate(task);
    }
}

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

License:Apache License

private void possiblyUpdateJob(Session p_session, Workflow p_wf, String p_wfState) throws Exception {
    JobImpl job = (JobImpl) p_wf.getJob();
    String jobState = job.getState();
    int jobStateIndex = -1;
    for (int i = 0; i < ORDERED_STATES.length && jobStateIndex < 0; i++) {
        if (jobState.equals(ORDERED_STATES[i])) {
            jobStateIndex = i;/*from w w  w.ja  v  a2  s . c  o  m*/
        }
    }
    int lowest = findLowestStateIndex(job.getWorkflows());
    if (jobStateIndex < lowest) {
        JobImpl jobClone = (JobImpl) p_session.get(JobImpl.class, job.getIdAsLong());
        jobClone.setState(ORDERED_STATES[lowest]);
        if (!Workflow.EXPORT_FAILED.equals(p_wfState)
                && WorkflowTypeConstants.TYPE_TRANSLATION.equals(p_wf.getWorkflowType())) {
            updatePageState(p_session, jobClone.getSourcePages(),
                    ((lowest == LOCALIZED_STATE || lowest == EXPORTING_STATE) ? PG_LOCALIZED : PG_ACTIVE_JOB));
        }
        p_session.saveOrUpdate(jobClone);
    }
    if (lowest >= LOCALIZED_STATE) {
        TaskEmailInfo p_emailInfo = createTaskEmailInfo(job, p_wf);
        p_emailInfo.setAssigneesName(job.getCreateUser().getFirstName());
        getWFServer().sendJobActionEmailToUser(job.getCreateUser().getUserId(), p_emailInfo,
                WorkflowMailerConstants.COMPLETED_JOB);
    }
}

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

License:Apache License

private void completeTask(String p_userId, Task p_task, String p_destinationArrow, String skipping)
        throws WorkflowManagerException {
    boolean isCompleted = false; // true if all workflows are complete
    boolean isManualImportFileSystemJob = true;
    boolean isTranslationWorkflow = false;
    boolean isDbJob = false;
    Workflow wfClone = null;// w  w w . j  a  va  2 s . c o  m
    TaskEmailInfo emailInfo = null;
    long jobId = -2;
    long taskId = -2;
    long wfId = -2;

    if (p_task == null) {
        s_logger.error("Task is null in _setTaskCompletion() for user: " + UserUtil.getUserNameById(p_userId));
    } else {
        taskId = p_task.getId();
    }
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    JbpmContext ctx = null;

    try {
        Date currentTime = new Date();
        TaskImpl task = (TaskImpl) session.get(TaskImpl.class, new Long(p_task.getId()));
        task.setCompletedDate(currentTime);
        task.setState(TaskImpl.STATE_COMPLETED);
        wfClone = (Workflow) task.getWorkflow();
        isTranslationWorkflow = WorkflowTypeConstants.TYPE_TRANSLATION.equals(wfClone.getWorkflowType());
        wfId = wfClone.getId();
        if (isTranslationWorkflow) {
            for (TargetPage tPage : wfClone.getTargetPages()) {
                String type = tPage.getDataSourceType();
                if (!DataSourceType.FILE_SYSTEM.equals(type)) {
                    isManualImportFileSystemJob = false;
                    isDbJob = DataSourceType.DATABASE.equals(type);
                    break;
                }

            }
        } else {
            isManualImportFileSystemJob = false;
            isDbJob = false;
        }

        ArrorInfo arrorInfo = new ArrorInfo(p_task.getId(), p_destinationArrow);

        // -1 indicates that the default path would be from the
        // beginning of the workflow (form START node)
        List wfTaskInfos = getWFServer().timeDurationsInDefaultPath(wfClone.getId(), -1, arrorInfo,
                getWFServer().getWorkflowInstanceById(wfClone.getId()));

        updateDuration(wfClone.getId(), wfTaskInfos, session);

        DefaultPathTasks dpt = updateDefaultPathTasks(ADVANCE_ACTION, currentTime, wfTaskInfos, wfClone,
                task.getId(), session);

        Job job = wfClone.getJob();
        jobId = job.getId();
        emailInfo = createTaskEmailInfo(job, wfClone);
        if (job != null && p_task != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Advancing task " + p_task.getTaskName() + ", taskId " + taskId + ", wfId "
                        + wfId + ", job " + job.getJobName() + ", jobId " + jobId + ", user "
                        + UserUtil.getUserNameById(p_userId));
            }
        }

        WorkflowInstanceInfo wfInstInfo = getWFServer().advanceTask(wfClone, p_userId, task.getId(),
                p_destinationArrow, dpt, emailInfo, skipping);

        int wfState = wfInstInfo.getState();
        isCompleted = wfState == WorkflowConstants.STATE_COMPLETED;
        if (isCompleted) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("workflow state is completed for workflow instance " + wfInstInfo.getId());
            }
        }

        // update the completion fraction
        updateCompletionFraction(wfClone, p_task, wfTaskInfos, isCompleted);
        long stfTaskId = -1;
        boolean createSTF = false;
        String actionType = null;
        long nextTaskId = -1;

        if (isCompleted) {
            if (isManualImportFileSystemJob) {
                wfClone.setState(WF_LOCALIZED);
            } else {
                if (skipping == null) {
                    wfClone.setState(WF_LOCALIZED);
                } else {
                    wfClone.setState(WF_EXPORTING);
                }
            }
            if (WorkflowTypeConstants.TYPE_DTP.equals(wfClone.getWorkflowType())) {
                wfClone.setState(WF_EXPORTED);
            }
            wfClone.setCompletedDate(currentTime);
            if (isTranslationWorkflow) {
                updatePageState(session, wfClone.getTargetPages(), PG_LOCALIZED);
                updateSecondaryTargetFileState(session, wfClone.getSecondaryTargetFiles(),
                        SecondaryTargetFileState.LOCALIZED);
            }
            possiblyUpdateJob(session, wfClone, WF_LOCALIZED);

            // Set up completed date of job
            job.setCompletedDate(currentTime);
            session.saveOrUpdate(job);
        } else {
            if (isTranslationWorkflow) {
                createTaskTuvs(wfClone, task, p_task.getTaskName(), session);
            }

            List<WfTaskInfo> nextTaskInfos = wfInstInfo.getNextTaskInfos();
            // update the state of the next active tasks
            List<Task> nextTasks = updateTaskState(session, nextTaskInfos, wfClone.getTasks(),
                    Task.STATE_ACTIVE);
            // perform the creation of STF if necessary
            ArrayList returnValue = possiblyPerformSystemActions(nextTaskInfos, nextTasks, wfClone,
                    emailInfo.getProjectManagerId());

            if (isTranslationWorkflow) {
                stfTaskId = ((Long) (returnValue.get(0))).longValue();
                createSTF = ((Boolean) returnValue.get(1)).booleanValue();
                actionType = returnValue.get(3) != null ? (String) returnValue.get(3) : null;
            }

            nextTaskId = ((Long) returnValue.get(0)).longValue();
        }

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

        if (createSTF) {
            s_logger.debug("Exporting for STF creation, taskId=" + stfTaskId);
            exportForStfCreation(new Long(stfTaskId), wfClone, p_userId);
        }
        // GBS-3002
        if (actionType != null && (skipping == null || skipping.startsWith("LAST"))) {
            SystemActionPerformer.perform(actionType, stfTaskId, p_userId);
        }

        // now remove the reserved time from the user's calendar.
        // This does not need to be part of the same transaction
        removeReservedTime(task.getId(), p_userId);
    } catch (AmbassadorDwUpException e) {
        s_logger.error("Failed to create job on GS Edtion", e);
    } catch (Exception e) {
        tx.rollback();
        s_logger.error("Failed to complete task " + taskId + ", workflow " + wfId + ", job " + jobId, e);
        String taskIdString = "null task id!";
        if (p_task != null) {
            Long id = new Long(p_task.getId());
            taskIdString = id.toString();
        }
        String[] args = new String[1];
        args[0] = taskIdString;
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_SET_TASK_COMPLETION, args, e);
    } finally {
        if (ctx != null) {
            ctx.close();
        }
        // despite errors above, if the job is complete, then attempt the
        // export
        // but re-check job state from TopLink instead of relying on the
        // above boolean
        if (!isManualImportFileSystemJob) {
            if (wfClone != null) {
                String projectMgrUserId = null;
                if (emailInfo != null)
                    projectMgrUserId = emailInfo.getProjectManagerId();
                else {
                    s_logger.warn("Project Mgr Id is null for task " + taskId + ", workflow " + wfId + ", job "
                            + jobId);
                }

                try {
                    exportLocalizedWorkflow(wfClone.getId(), projectMgrUserId, isDbJob, isCompleted);
                } catch (Throwable t) {
                    // log the error but don't let it affect job completion
                    s_logger.error("Error trying to export for completed workflow.", t);
                }
            } else {
                s_logger.warn("Not exporting wf for task " + taskId + ", workflow " + wfId + ", job " + jobId);
            }
        }
    }
}