package com.mobius.controllers;
import com.adobe.idp.Context;
import com.adobe.idp.dsc.DSCException;
import com.adobe.idp.dsc.clientsdk.ServiceClientFactory;
import com.adobe.idp.dsc.clientsdk.ServiceClientFactoryProperties;
import com.adobe.idp.dsc.filter.Connective;
import com.adobe.idp.dsc.filter.Operator;
import com.adobe.idp.taskmanager.dsc.client.TaskManagerClientFactory;
import com.adobe.idp.taskmanager.dsc.client.TaskManagerQueryService;
import com.adobe.idp.taskmanager.dsc.client.query.*;
import com.adobe.idp.taskmanager.dsc.client.task.*;
import com.adobe.idp.um.api.UMException;
import com.adobe.idp.um.api.infomodel.AuthResult;
import com.adobe.idp.um.api.infomodel.Group;
import com.adobe.idp.um.api.infomodel.PrincipalSearchFilter;
import com.adobe.idp.um.api.infomodel.User;
import com.adobe.livecycle.usermanager.client.AuthenticationManagerServiceClient;
import com.adobe.livecycle.usermanager.client.DirectoryManagerServiceClient;
import com.mobius.livecycle.LiveCycleService;
import com.mobius.model.*;
import com.mobius.model.entity.TblEFromTemplateE;
import com.mobius.model.entity.TblPatientE;
import com.mobius.utils.ResourceManager;
import com.mobius.utils.XMLXFAHelper;
import flex.acrobat.pdf.XFAHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: Pawel
* Date: 02.01.14
* Time: 10:36
* To change this template use File | Settings | File Templates.
*/
@Controller
@RequestMapping("/task")
public class LiveCycleTask {
@RequestMapping(method = RequestMethod.GET, produces = "application/json", value = "/form")
public
@ResponseBody
ResponseData form(@RequestParam("taskId") Long taskId, HttpServletRequest request) throws UMException, TaskManagerException {
try {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication instanceof MyAuthenticationToken) {
LoggedUser user = ((MyAuthenticationToken) authentication).getMyUser();
LiveCycleService lvService = user.getLiveCycleService();
impersonateUserAndSetClientFactory(user.getCanonicalName(), user.getDomainName(), user.getLiveCycleService().getServiceClientFactory(),user.getResourceManager());
TaskManager taskManager = TaskManagerClientFactory.getTaskManager(lvService.getServiceClientFactory());
taskManager.claimTask(taskId);
TaskInfo tInfo = taskManager.getTaskInfo(taskId);
FormInstance formInstances[] = tInfo.getTaskItems();
ResponseData responseData = new ResponseData();
ArrayList<FormInstance> resList = new ArrayList<FormInstance>();
for (FormInstance formInstance : formInstances) {
resList.add(formInstance);
}
responseData.setSuccess(Boolean.TRUE);
responseData.setMax(resList.size());
responseData.setData(resList);
return responseData;
}
} catch (Exception exc) {
exc.printStackTrace();
return ResponseData.error(exc);
}
return ResponseData.succes();
}
@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/complete")
public
@ResponseBody
ResponseData complete(@RequestParam("taskId") Long taskId, HttpServletRequest request) throws UMException, TaskManagerException {
try {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication instanceof MyAuthenticationToken) {
LoggedUser user = ((MyAuthenticationToken) authentication).getMyUser();
LiveCycleService lvService = user.getLiveCycleService();
impersonateUserAndSetClientFactory(user.getCanonicalName(), user.getDomainName(), user.getLiveCycleService().getServiceClientFactory(),user.getResourceManager());
TaskManager taskManager = TaskManagerClientFactory.getTaskManager(lvService.getServiceClientFactory());
CompleteTaskResult taskResult = taskManager.completeTask(taskId,"Accept");
boolean result = taskResult.isProcessInitiated();
}
} catch (Exception exc) {
exc.printStackTrace();
return ResponseData.error(exc);
}
return ResponseData.succes();
}
@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/reject")
public
@ResponseBody
ResponseData reject(@RequestParam("taskId") Long taskId, HttpServletRequest request) throws UMException, TaskManagerException {
try {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication instanceof MyAuthenticationToken) {
LoggedUser user = ((MyAuthenticationToken) authentication).getMyUser();
LiveCycleService lvService = user.getLiveCycleService();
impersonateUserAndSetClientFactory(user.getCanonicalName(), user.getDomainName(), user.getLiveCycleService().getServiceClientFactory(),user.getResourceManager());
TaskManager taskManager = TaskManagerClientFactory.getTaskManager(lvService.getServiceClientFactory());
taskManager.rejectTask(taskId);
}
} catch (Exception exc) {
exc.printStackTrace();
return ResponseData.error(exc);
}
return ResponseData.succes();
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json", value = "/get")
public
@ResponseBody
ResponseData get(HttpServletRequest request) throws IOException, ParserConfigurationException, SAXException, DSCException, UMException, TaskQueryServiceException {
ResponseData responseData = new ResponseData();
try {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication instanceof MyAuthenticationToken) {
EntityManager em = MyEntityManagerFactory.getEm(request.getSession());
LoggedUser user = ((MyAuthenticationToken) authentication).getMyUser();
LiveCycleService lvService = user.getLiveCycleService();
ServiceClientFactory clientFactory = lvService.getServiceClientFactory();
impersonateUserAndSetClientFactory(user.getCanonicalName(), user.getDomainName(), clientFactory,user.getResourceManager());
TaskManagerQueryService queryManager = TaskManagerClientFactory.getQueryManager(clientFactory);
TaskManager taskManager = TaskManagerClientFactory.getTaskManager(clientFactory);
DirectoryManagerServiceClient dirClient = new DirectoryManagerServiceClient(clientFactory);
PrincipalSearchFilter psf = new PrincipalSearchFilter();
psf.setUserIdAbsolute(user.getUserName());
List<?> principalList = dirClient.findPrincipals(psf);
Iterator<?> pit = principalList.iterator();
User lcUser = null;
if (pit.hasNext())
lcUser = (User) (pit.next());
Set<Group> groupMemberships = lcUser.getGroupMemberships();
TaskSearchFilter taskSearchFilter = new TaskSearchFilter();
taskSearchFilter.addCondition(TaskSearchingConstants.pSTATUS,
new Operator("="), StatusFilter.assigned);
for (Group group : groupMemberships) {
if (!group.getCommonName().equals("Scanning Bureau")) {
taskSearchFilter.addCondition(
TaskSearchingConstants.pCURRENT_ASSIGNMENT_QUEUE_OWNER,
Operator.EQUALS, group.getCommonName(), Connective.OR);
}
}
taskSearchFilter.addSortDesc(TaskSearchingConstants.pPROCESS_START_TIME);
List<TaskRow> result = queryManager.taskSearch(taskSearchFilter);
ArrayList<WorkBasketItem> items = new ArrayList<WorkBasketItem>();
for (TaskRow taskRow : result) {
if (taskRow.getTaskStatus() >= 100)
continue;
if (!lcUser.getCommonName().equals(
taskRow.getCurrentAssignment().getQueueOwner())
// && !taskRow
// .getCurrentAssignment()
// .getQueueOwner()
// .startsWith("WFAG_")
)
continue;
WorkBasketItem wsItem = new WorkBasketItem();
long taskID = taskRow.getTaskId();
wsItem.setTaskId(taskID);
wsItem.setTaskStatus(taskRow.getTaskStatus());
wsItem.setProcessName(taskRow.getProcessName());
wsItem.setStepName(taskRow.getStepName());
wsItem.setQueueOwner(taskRow.getCurrentAssignment().getQueueOwner());
wsItem.setProcessTitle(taskRow.getProcessTitle());
if (!taskRow.getStepName().startsWith("Clinical Referral"))
wsItem.setDeadLine(new ResponseDate(taskRow.getDeadline()));
wsItem.setTaskCreationDate(new ResponseDate(taskRow.getTaskCreateTime()));
wsItem.setPriority(taskRow.getPriority());
wsItem.setInstructions(taskRow.getInstructions());
wsItem.setRouteList(taskRow.getRouteList());
wsItem.setIsActionRequired(taskRow.isRouteSelectionRequired());
String[] metadata = taskRow.getInstructions().split("\\|");
if (metadata.length >= 8) {
wsItem.setPatientTitle(metadata[0]);
wsItem.setPatientFirstName(metadata[1]);
wsItem.setPatientMiddleName(metadata[2]);
wsItem.setPatientLastName(metadata[3]);
if (!metadata[4].contains("nul"))
wsItem.setNhsNumber(metadata[4]);
wsItem.setHospitalNumber(metadata[5]);
wsItem.setPatientDOB(metadata[6]);
wsItem.setPatientVerificationStatus(metadata[7]);
if (metadata.length == 9) {
wsItem.setTaskSenderName(metadata[8]);
}
}
String formData = null;
try {
TaskInfo tInfo = taskManager.getTaskInfo(wsItem.getTaskId());
FormInstance formInstances[] = tInfo.getTaskItems();
ArrayList<FormInstance> resList = new ArrayList<FormInstance>();
for (FormInstance formInstance : formInstances) {
try {
String tp = formInstance.getTemplatePath();
FormInstance dataForm = taskManager.getFormInstanceForTask(wsItem.getTaskId(),formInstance.getFormInstanceId(),true);
String xfaXml = new String(dataForm.getXFAData(), Charset.forName("UTF-8"));
formData = XMLXFAHelper.getJsonDataFromXfa(xfaXml);
String path = tp.substring(tp.lastIndexOf("/") + 1, tp.lastIndexOf("."));
wsItem.setTaskForm(path);
} catch (Exception exc) {
exc.printStackTrace();
}
}
} catch (TaskPermissionException exc) {
exc.printStackTrace();
}
if(wsItem.getTaskForm()!=null) {
Query
query = em.createQuery("SELECT t FROM TblEFromTemplateE t WHERE t.name=:name", TblEFromTemplateE.class);
query.setParameter("name",wsItem.getTaskForm().toLowerCase());
List<TblEFromTemplateE> templates = query.getResultList();
if(templates.size()>0) {
wsItem.setTemplate(new ResponseEFormTemplate(templates.get(0)));
wsItem.getTemplate().setFormData(formData);
}
}
Query query = em.createQuery("SELECT p FROM TblPatientE p WHERE p.hospitalNumber=:hospitalNumber OR p.nhsNumber=:nhsNumber", TblPatientE.class);
query.setParameter("hospitalNumber",wsItem.getHospitalNumber());
query.setParameter("nhsNumber",wsItem.getNhsNumber());
List<TblPatientE> patients = query.getResultList();
if(patients.size()>0) {
wsItem.setPatient(new ResponsePatient(patients.get(0)));
}
if(wsItem.getTemplate()!=null) {
items.add(wsItem);
}
}
responseData.setSuccess(Boolean.TRUE);
responseData.setMax(items.size());
responseData.setData(items);
return responseData;
}
} catch (Exception exc) {
exc.printStackTrace();
responseData.setSuccess(Boolean.FALSE);
responseData.setMessage(exc.getMessage());
}
return responseData;
}
public static void impersonateUserAndSetClientFactory(String canonicalName, String domainName, ServiceClientFactory serviceClientFactory,ResourceManager resourceManager)
throws UMException {
AuthenticationManagerServiceClient authClient = new AuthenticationManagerServiceClient(serviceClientFactory);
AuthResult authResultAdmin = authClient
.authenticate(resourceManager.getPropValue(ServiceClientFactoryProperties.DSC_CREDENTIAL_USERNAME), resourceManager.getPropValue(ServiceClientFactoryProperties.DSC_CREDENTIAL_PASSWORD).getBytes());
Context context = new Context();
context.initPrincipal(authResultAdmin);
AuthResult authResult = authClient.getAuthResultOnBehalfOfUser(
canonicalName, domainName, context);
Context impersonateContext = new Context();
impersonateContext.initPrincipal(authResult);
serviceClientFactory.setContext(impersonateContext);
}
}