/* * */ package com.fp.bpmlib.task.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.InitialContext; import javax.persistence.EntityManager; import javax.persistence.Query; import org.jbpm.process.instance.event.listeners.TriggerRulesEventListener; import org.jbpm.services.task.impl.model.CommentImpl; import org.jbpm.services.task.impl.model.UserImpl; import org.jbpm.services.task.lifecycle.listeners.BAMTaskEventListener; import org.jbpm.services.task.lifecycle.listeners.TaskLifeCycleEventListener; import org.jbpm.services.task.utils.ContentMarshallerHelper; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.task.TaskService; import org.kie.api.task.model.Content; import org.kie.api.task.model.Status; import org.kie.api.task.model.Task; import org.kie.api.task.model.TaskData; import org.kie.api.task.model.TaskSummary; import org.kie.internal.task.api.EventService; import org.kie.internal.task.api.InternalTaskService; import com.fp.bpmlib.Common; import com.fp.bpmlib.ProcessUtil; import com.fp.bpmlib.ejb.local.JbpmBeanLocal; import com.fp.bpmlib.query.monitor.FlowActivitySave; import com.fp.bpmlib.task.MaiaWorkItemHandler; import com.fp.common.helper.Constant; import com.fp.common.logger.APPLogger; import com.fp.persistence.commondb.PersistenceHelper; import com.fp.persistence.commondb.PersistenceManager; import com.fp.persistence.pbpm.gene.TbpmGroupsUsers; import com.fp.simple.dto.TaskInfo; // /** * Class HumanTaskClient encargada de acceder al Servidor de Tareas. * * @author Jvaca * @version 2.1 */ public class HumanTaskClient { /** El valor de language. */ private String language = "en-UK"; private final TaskService taskService; private final KieSession kiesession; /** * Crea una nueva instancia de human task client. * * @throws Exception la exception */ public HumanTaskClient() throws Exception { JbpmBeanLocal local = (JbpmBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/jbpmbean"); RuntimeManager manager = local.getRuntimeManager(); RuntimeEngine runtime = manager.getRuntimeEngine(null); kiesession = runtime.getKieSession(); taskService = runtime.getTaskService(); kiesession.addEventListener(new TriggerRulesEventListener(kiesession)); kiesession.getWorkItemManager().registerWorkItemHandler("Human Task", new MaiaWorkItemHandler()); this.addListeners(runtime); } /** * Adiciona listener, para el manejo del bam de tareas. * * @param engine */ @SuppressWarnings("unchecked") private void addListeners(RuntimeEngine engine) { EventService eventService = (EventService) engine.getTaskService(); boolean hasBamEventListener = false; for (TaskLifeCycleEventListener listener : eventService.getTaskEventListeners()) { if (listener instanceof BAMTaskEventListener) { hasBamEventListener = true; break; } } if (!hasBamEventListener) { BAMTaskEventListener bamTaskEventListener = new BAMTaskEventListener(); eventService.registerTaskEventListener(bamTaskEventListener); } } /** * Activate task. * * @param pTask the task * @param pUserId the user id * @throws Exception la exception */ public void activateTask(long pTask, String pUserId) throws Exception { taskService.activate(pTask, pUserId); } /** * Claim task. * * @param pTask the task * @param pUserId the user id * @throws Exception la exception */ public void claimTask(long pTask, String pUserId) throws Exception { taskService.claim(pTask, pUserId); FlowActivitySave.actualizarActividadClaim(pTask, pUserId); } /** * Entrega lsita de grupos bpm al que pertenece el usuario. * * @param pUser Codigo de usuario a buscar los grupos a los que pertenece. * @return List * @throws Exception la exception */ public static List groupsByUser(String pUser) throws Exception { List groups = TbpmGroupsUsers.findGroupsByUser(PersistenceHelper.getEntityManager(), pUser); List data = new ArrayList(); for (TbpmGroupsUsers tbpmGroupsUsers : groups) { data.add(tbpmGroupsUsers.getPk().getGroupcode()); } return data; } /** * Close. * * @throws Exception la exception */ public void close() throws Exception { // No hacer nada con JTA la session se cierra automaticamente. } /** * Complete task. * * @param pTask the task * @param pJournalId the journal id * @param data the data * @param pResultado the resultado * @param pObs the obs * @throws Exception la exception */ public String completeTask(long pTask, String pJournalId, Map data, String pResultado, String pObs) throws Exception { Task t = this.getTaskById(pTask); TaskData td = t.getTaskData(); this.addComment(pTask, td.getActualOwner().getId(), pObs); Map input = this.getInputData(t); TaskInfo ti = (TaskInfo) input.get(ProcessUtil.TASK_METADATA); ti.setResponse(pResultado); ti.setTaskId(pTask); ti.setJournalId(pJournalId); System.out.println(pObs); if (ti.getUserId() == null && t.getTaskData().getActualOwner() != null) { ti.setUserId(t.getTaskData().getActualOwner().getId()); } // Las fechas para el monitor se toman de BamTaskSummary // ti.setCreated(new Timestamp( td.getCreatedOn().getTime())); // ti.setCompleted(FormatDates.getInstance().getDataBaseTimestamp()); ti.getAditionalData().putAll(data); taskService.complete(pTask, td.getActualOwner().getId(), input); FlowActivitySave.actualizarActividadComplete(pTask, ti); return ti.getTname(); } /** * Adiciona un comment. * * @param pTask the task * @param pUserId the user id * @param pComment the comment * @throws Exception la exception */ public void addComment(long pTask, String pUserId, String pComment) throws Exception { InternalTaskService its = (InternalTaskService) taskService; CommentImpl comentario = new CommentImpl(); comentario.setText(pComment); comentario.setAddedAt(Common.getInstance().getCurrentDate()); comentario.setAddedBy(new UserImpl(pUserId)); its.addComment(pTask, comentario); } /** * Delegate task. * * @param pTask the task * @param pUserId the user id * @param pTargetUserId the target user id * @throws Exception la exception */ public void delegateTask(long pTask, String pUserId, String pTargetUserId) throws Exception { taskService.delegate(pTask, pUserId, pTargetUserId); FlowActivitySave.actualizarActividadDelegate(pTask, pTargetUserId); } /** * Obtiene el valor de assigned tasks. * * @return Valor de assigned tasks * @throws Exception la exception */ public List getAssignedTasks() throws Exception { return taskService.getTasksAssignedAsPotentialOwner(null, language); } /** * Obtiene el valor de assigned tasks. * * @param pUserId the user id * @return Valor de assigned tasks * @throws Exception la exception */ public List getAssignedTasks(String pUserId) throws Exception { // this.client.getTasksAssignedAsPotentialOwner(pUserId, this.language, taskSummaryHandler); return taskService.getTasksOwned(pUserId, language); } /** * Obtiene el valor de content by id. * * @param pId the id * @return Valor de content by id * @throws Exception la exception */ public Content getContentById(long pId) throws Exception { return taskService.getContentById(pId); } /** * Obtiene el valor de input data. * * @param pTask the task * @return Valor de input data * @throws Exception la exception */ public Map getInputData(Task pTask) throws Exception { Content c = this.getContentById(pTask.getTaskData().getDocumentContentId()); return HumanTaskClient.getContenido(c); } /** * Obtiene el valor de output data. * * @param pTask the task * @return Valor de output data * @throws Exception la exception */ public Map getOutputData(Task pTask) throws Exception { Content c = this.getContentById(pTask.getTaskData().getOutputContentId()); return HumanTaskClient.getContenido(c); } /** * Entrega el contenido asociado al workitem. * * @param task Datos de la tarea * @return Map * @throws Exception */ @SuppressWarnings("unchecked") public static Map getContenido(Content content) throws Exception { Map maia = new HashMap(); Object obj = ContentMarshallerHelper.unmarshall(content.getContent(), null); if (obj instanceof Map) { maia = (Map) obj; } return maia; } /** * Obtiene el valor de input data. * * @param pTask the task * @return Valor de input data * @throws Exception la exception */ @SuppressWarnings(Constant.WARN_UNCHECKED) @Deprecated public Map getDatos(Content c) throws Exception { if (c != null) { // Esto funciona con jbm 5.4 Object obj = ContentMarshallerHelper.unmarshall(c.getContent(), null); if (obj != null) { ByteArrayOutputStream bos = null; ObjectOutputStream out = null; try { // return (Map) obj; bos = new ByteArrayOutputStream(); out = new ObjectOutputStream(bos); out.writeObject(obj); ObjectInputStream bin = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); return (Map) bin.readObject(); } finally { bos.close(); out.close(); } } } ObjectInputStream bin = new ObjectInputStream(new ByteArrayInputStream(c.getContent())); try { return (Map) bin.readObject(); } finally { bin.close(); } } /** * Obtiene el valor de task by id. * * @param pId the id * @return Valor de task by id * @throws Exception la exception */ public Task getTaskById(long pId) throws Exception { return taskService.getTaskById(pId); } /** * Obtiene el valor de task by work item id. * * @param pWorkId the work id * @return Valor de task by work item id * @throws Exception la exception */ public Task getTaskByWorkItemId(long pWorkId) throws Exception { return taskService.getTaskByWorkItemId(pWorkId); } /** * Obtiene el valor de task content input. * * @param taskSum the task sum * @return Valor de task content input */ public Object getTaskContentInput(TaskSummary taskSum) { ByteArrayInputStream bais = null; ObjectInputStream is = null; Task task2 = taskService.getTaskById(taskSum.getId()); TaskData taskData = task2.getTaskData(); Content content = taskService.getContentById(taskData.getDocumentContentId()); try { bais = new ByteArrayInputStream(content.getContent()); is = new ObjectInputStream(bais); Object obj = null; do { obj = is.readObject(); if (obj == null) { break; } APPLogger.getLogger().debug("OBJECT: " + obj); return obj; } while (obj != null); } catch (Exception e) { APPLogger.getLogger().warn(e, e); return null; } finally { try { if (bais != null) { bais.close(); } } catch (Exception e2) { } try { if (is != null) { is.close(); } } catch (Exception e2) { } } return null; } /** * Obtiene el valor de task data. * * @param pTask the task * @return Valor de task data * @throws Exception la exception */ public TaskData getTaskData(long pTask) throws Exception { Task task = this.getTaskById(pTask); return task.getTaskData(); } /** * Obtiene el listado de tareas Asignadas. * * @param pUserCri the user cri * @param pCriteria the criteria * @param pPage the page * @param pRecords the records * @return Listado de tareas asignadas * @throws Exception la exception */ public List getAsignedTasks(String pUserCri) throws Exception { List lestatus = new ArrayList<>(); List lresp = new ArrayList<>(); lestatus.add(Status.Reserved); lestatus.add(Status.InProgress); List list; try { list = taskService.getTasksOwnedByStatus(pUserCri, lestatus, "en-UK"); for (TaskSummary obj : list) { Object o[] = new Object[2]; Task task = this.getTaskById(obj.getId()); Content c = this.getContentById(task.getTaskData().getDocumentContentId()); o[0] = task; o[1] = c; lresp.add(o); } } catch (Exception e) { throw new RuntimeException(e); } return lresp; } /** * Obtiene el valor de unfinished tasks. * * @param pUserId the user id * @param pCri the cri * @return Valor de unfinished tasks * @throws Exception la exception */ public List getUnfinishedTasksByUser(String pUserId) throws Exception { List lestatus = new ArrayList<>(); List lresp = new ArrayList<>(); lestatus.add(Status.Reserved); lestatus.add(Status.InProgress); List list = taskService.getTasksOwnedByStatus(pUserId, lestatus, "en-UK"); try { list = taskService.getTasksOwnedByStatus(pUserId, lestatus, "en-UK"); for (TaskSummary obj : list) { Object o[] = new Object[2]; Task task = this.getTaskById(obj.getId()); Content c = this.getContentById(task.getTaskData().getDocumentContentId()); o[0] = task; o[1] = c; lresp.add(o); } } catch (Exception e) { throw new RuntimeException(e); } return lresp; } /** * JPQL JPQL_TASK_NOT_COMPLETEBYGROUP */ private static final String TAREAS_GRUPO = "select t, potentialOwners.id from TaskImpl t, OrganizationalEntityImpl potentialOwners " + "where potentialOwners.id in (:groupIds) and potentialOwners in elements ( t.peopleAssignments.potentialOwners ) and t.archived = 0 " + "and t.taskData.actualOwner = null and t.taskData.status in ('Created', 'Ready', 'Reserved', 'InProgress', 'Suspended')"; /** * Obtiene el valor de unfinished tasks por Grupo. * * @param pGroupId the user id * @param pCri the cri * @return Valor de unfinished tasks * @throws Exception la exception */ @SuppressWarnings(Constant.WARN_UNCHECKED) public List getTasksByGroup(String pGroupId, String pCri) throws Exception { List ldatos = new ArrayList(); EntityManager em = null; try { em = PersistenceManager.getInstance().getEntityManagerFactoryAuxiliar("org.jbpm.domain").createEntityManager(); Query qry = em.createQuery(HumanTaskClient.TAREAS_GRUPO); qry.setParameter("groupIds", pGroupId); ldatos = qry.getResultList(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (em.isOpen()) { em.close(); } } return ldatos; } /** * Release task. * * @param pTask the task * @param pUserId the user id * @throws Exception la exception */ public void releaseTask(long pTask, String pUserId) throws Exception { taskService.release(pTask, pUserId); } /** * Resume task. * * @param pTask the task * @param pUserId the user id * @throws Exception la exception */ public void resumeTask(long pTask, String pUserId) throws Exception { taskService.resume(pTask, pUserId); } /** * Start task. * * @param pTask the task * @throws Exception la exception */ public void startTask(long pTask) throws Exception { Task task = this.getTaskById(pTask); APPLogger.getLogger().debug("Starting task " + pTask); Map input = this.getInputData(task); // com.fp.bpmlib.Process p = this.findProcess(task.getTaskData(), snapshot); // TaskInfo ti = (TaskInfo) input.get(ProcessUtil.TASK_METADATA); // ti.setTaskId(pTask); // ti.setStarted(FormatDates.getInstance().getDataBaseTimestamp()); // ti.setCreated(new Timestamp(task.getTaskData().getCreatedOn().getTime())); // ProcessInstance processInstance = kiesession.getProcessInstance(task.getTaskData().getProcessInstanceId()); // RuleFlowProcessInstance rfpi = (RuleFlowProcessInstance) processInstance; // rfpi.setVariable(ProcessUtil.TASK_METADATA, ti); //actualiza datos en el contexto. // InternalTaskService its = ((InternalTaskService) taskService); // Elimina el content anterior y remplaza por un nuevo content. // its.deleteContent(pTask, task.getTaskData().getDocumentContentId()); // its.addContent(pTask, input); // ***** LA FECHA DE CREACION E INICIO SE TOMA DE LA BAMTASKSUMMARY PARA PRESENTAR EN EL MONITOR. taskService.start(pTask, task.getTaskData().getActualOwner().getId()); FlowActivitySave.actualizarActividadStart(pTask); APPLogger.getLogger().debug("Started task " + pTask); } /** * Stop task. * * @param pTask the task * @param pUserId the user id * @throws Exception la exception */ public void stopTask(long pTask, String pUserId) throws Exception { taskService.stop(pTask, pUserId); } /** * Suspend task. * * @param pTask the task * @param pUserId the user id * @throws Exception la exception */ public void suspendTask(long pTask, String pUserId) throws Exception { taskService.suspend(pTask, pUserId); } }