001package org.kuali.ole.service.impl;
002
003import org.apache.commons.io.FileUtils;
004import org.apache.commons.io.IOUtils;
005import org.apache.commons.lang.StringEscapeUtils;
006import org.apache.commons.lang.StringUtils;
007import org.apache.http.HttpEntity;
008import org.apache.http.HttpResponse;
009import org.apache.http.client.HttpClient;
010import org.apache.http.client.methods.HttpPost;
011import org.apache.http.entity.mime.MultipartEntity;
012import org.apache.http.entity.mime.content.FileBody;
013import org.apache.http.impl.client.DefaultHttpClient;
014import org.apache.log4j.Logger;
015import org.kuali.ole.OLEConstants;
016import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
017import org.kuali.ole.docstore.model.xmlpojo.ingest.*;
018import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler;
019import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
020import org.kuali.ole.select.bo.*;
021import org.kuali.ole.select.controller.LicenceRoutingRuleDelegationMaintainable;
022import org.kuali.ole.service.OleLicenseRequestService;
023import org.kuali.ole.utility.CompressUtils;
024import org.kuali.rice.core.api.config.property.ConfigContext;
025import org.kuali.rice.core.api.config.property.ConfigurationService;
026import org.kuali.rice.kew.doctype.bo.DocumentType;
027import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
028import org.kuali.rice.kim.api.identity.Person;
029import org.kuali.rice.krad.service.BusinessObjectService;
030import org.kuali.rice.krad.service.KRADServiceLocator;
031import org.kuali.rice.krad.util.GlobalVariables;
032import org.kuali.rice.krad.util.KRADConstants;
033import org.kuali.rice.krad.util.ObjectUtils;
034
035import java.io.*;
036import java.sql.Timestamp;
037import java.text.ParseException;
038import java.text.SimpleDateFormat;
039import java.util.*;
040
041/**
042 * OleLicenseRequestServiceImpl builds the Xml for the Agreement Document ingest operation.
043 */
044public class OleLicenseRequestServiceImpl implements OleLicenseRequestService {
045
046    private static final Logger LOG = Logger.getLogger(OleLicenseRequestServiceImpl.class);
047    private static final String DOCSTORE_URL = "docstore.url";
048    private static final String queryString = "DocType:bibliographic AND Title_search:";
049    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
050    /**
051     *  This method creates the multipart entity  based on zipfile and sent to the target location,
052     *
053     * @param target
054     * @param zipFile
055     * @return List<File>
056     * @throws Exception
057     */
058    public static List<File> postDataForLicense(String target, File zipFile) throws Exception {
059        CompressUtils compressUtils = new CompressUtils();
060        HttpPost httpPost = new HttpPost(target);
061        HttpClient httpclient = new DefaultHttpClient();
062        FileBody uploadFilePart = new FileBody(zipFile);
063        MultipartEntity reqEntity = new MultipartEntity();
064        reqEntity.addPart("upload-file", uploadFilePart);
065        httpPost.setEntity(reqEntity);
066
067        HttpResponse httpResponse = httpclient.execute(httpPost);
068
069        HttpEntity respEntity = httpResponse.getEntity();
070        InputStream outcome = respEntity.getContent();
071        File respFile = File.createTempFile("DocStore Ingest-", "-Response File.zip");
072        IOUtils.copy(outcome, new FileOutputStream(respFile));
073        List<File> resp = compressUtils.getAllFilesList(compressUtils.extractZippedBagFile(respFile.getAbsolutePath(), null));
074        return resp;
075    }
076    /**
077     *  This method creates the zipped Bag file which contains the requestXml and the File to be uploaded to the docStore and
078     *                  process the response file to get the uuid.
079     * @param oleAgreementDocs
080     * @return List<OleAgreementDocumentMetadata>
081     */
082    public List<OleAgreementDocumentMetadata> processIngestAgreementDocuments(List<OleAgreementDocumentMetadata> oleAgreementDocs) {
083        try {
084            String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
085            CompressUtils compressUtils = new CompressUtils();
086            File file = new File(getKualiConfigurationService().getPropertyValueAsString(
087                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_LOCATION);
088            file.mkdirs();
089            for(OleAgreementDocumentMetadata oleAgreementDoc : oleAgreementDocs) {
090                File agreementDoc = new File(getKualiConfigurationService().getPropertyValueAsString(
091                        KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_TMP_LOCATION+
092                        File.separator+oleAgreementDoc.getAgreementFileName());
093                FileUtils.copyFileToDirectory(agreementDoc, file);
094                agreementDoc.delete();
095            }
096            String requestXml = buildIngestAgreementRequestXml(oleAgreementDocs);
097            File requestxml = new File(getKualiConfigurationService().getPropertyValueAsString(
098                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_LOCATION +File.separator+
099                    "request.xml");
100            requestxml.createNewFile();
101            FileUtils.writeStringToFile(requestxml, requestXml);
102
103            File zipFile = compressUtils.createZippedBagFile(file);
104            file.delete();
105            Response response = new Response();
106            List<File> resp = postDataForLicense(docstoreURL, zipFile);
107            requestxml.delete();
108            zipFile.delete();
109            for (File respFile : resp) {
110                if (respFile.getName().equalsIgnoreCase("response.xml")) {
111                    BufferedReader br = new BufferedReader(new FileReader(respFile));
112                    String line = null;
113                    while ((line = br.readLine()) != null)
114                        response = new ResponseHandler().toObject(FileUtils.readFileToString(respFile));
115                }
116            }
117
118            if(response.getStatus().equals("Success")) {
119                Iterator agreementDocIterator = oleAgreementDocs.iterator();
120                for (ResponseDocument responseDocument : response.getDocuments()) {
121                    OleAgreementDocumentMetadata agreementDocumentMetadata = (OleAgreementDocumentMetadata) agreementDocIterator.next();
122                    agreementDocumentMetadata.setAgreementUUID(responseDocument.getUuid());
123                }
124            }
125            else {
126                LOG.error(response.getStatus()+"-" +response.getMessage());
127                return new ArrayList();
128            }
129        }
130
131        catch(Exception e) {
132            e.printStackTrace();
133        }
134        return oleAgreementDocs;
135    }
136    /**
137     *  This method creates the zipped Bag file which contains the requestXml and the File to be updated to the docStore and
138     *                  process the response file to get the uuid (after the checkin).
139     * @param oleAgreementDocs
140     * @return List<oleAgreementDocumentMetadata>
141     */
142    public List<OleAgreementDocumentMetadata> processCheckInAgreementDocuments(List<OleAgreementDocumentMetadata> oleAgreementDocs) {
143        try {
144            String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
145            CompressUtils compressUtils = new CompressUtils();
146            File file = new File(getKualiConfigurationService().getPropertyValueAsString(
147                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_LOCATION);
148            file.mkdirs();
149            String requestXml = buildCheckInAgreementRequestXml(oleAgreementDocs);
150            File requestxml = new File(getKualiConfigurationService().getPropertyValueAsString(
151                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_LOCATION+
152                    File.separator+"request.xml");
153            requestxml.createNewFile();
154            FileUtils.writeStringToFile(requestxml, requestXml);
155            File zipFile = compressUtils.createZippedBagFile(file);
156            file.delete();
157            Response response = new Response();
158            List<File> resp = postDataForLicense(docstoreURL, zipFile);
159            requestxml.delete();
160            zipFile.delete();
161            for (File respFile : resp) {
162                if (respFile.getName().equalsIgnoreCase("response.xml")) {
163                    BufferedReader br = new BufferedReader(new FileReader(respFile));
164                    String line = null;
165                    while ((line = br.readLine()) != null)
166                        response = new ResponseHandler().toObject(FileUtils.readFileToString(respFile));
167                }
168            }
169        }
170
171        catch(Exception e) {
172            e.printStackTrace();
173        }
174        return oleAgreementDocs;
175
176    }
177    /**
178     *  This method builds the requestXml for the Agreement Document ingest operation.
179     * @param agreementDocs
180     * @return requestXml
181     */
182
183    private String buildIngestAgreementRequestXml(List<OleAgreementDocumentMetadata> agreementDocs) {
184        Request requestObject = new Request();
185        RequestDocument requestDocument;
186        ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
187        requestObject.setOperation("ingest");
188        Person user = GlobalVariables.getUserSession().getPerson();
189        requestObject.setUser(user.getPrincipalName());
190        for(OleAgreementDocumentMetadata agreementDoc : agreementDocs) {
191            requestDocument = new RequestDocument();
192            requestDocument.setId("1");
193            requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
194            requestDocument.setType("license");
195            requestDocument.setUser(agreementDoc.getUploadedBy());
196            String agreementFormat = agreementDoc.getAgreementFileName().substring(agreementDoc.getAgreementFileName().indexOf(".")+1,agreementDoc.getAgreementFileName().length());
197            if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
198                requestDocument.setFormat(agreementFormat);
199            }
200            else {
201                requestDocument.setFormat("doc");
202            }
203
204            requestDocument.setDocumentName(agreementDoc.getAgreementFileName());
205            requestDocument.setDocumentTitle(agreementDoc.getAgreementName());
206            requestDocument.setDocumentMimeType(agreementDoc.getAgreementMimeType());
207            AdditionalAttributes additionalAttributes = new AdditionalAttributes();
208            additionalAttributes.setDateEntered(agreementDoc.getUploadedDate().toString());
209            additionalAttributes.setAttribute("label", agreementDoc.getAgreementName());
210            additionalAttributes.setAttribute("notes", agreementDoc.getAgreementNotes());
211            additionalAttributes.setAttribute("type",agreementDoc.getAgreementType());
212            requestDocument.setAdditionalAttributes(additionalAttributes);
213            requestDocuments.add(requestDocument);
214        }
215        requestObject.setRequestDocuments(requestDocuments);
216
217        RequestHandler requestHandler = new RequestHandler();
218        String requestXml = requestHandler.toXML(requestObject);
219        return requestXml;
220    }
221
222    /**
223     * This method builds the requestXml for the checkin operation of the agreement document.
224     * @param agreementDocs
225     * @return  requestXml
226     */
227    private String buildCheckInAgreementRequestXml(List<OleAgreementDocumentMetadata> agreementDocs) {
228        Request requestObject = new Request();
229        RequestDocument requestDocument;
230        ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
231        requestObject.setOperation("checkIn");
232        Person user = GlobalVariables.getUserSession().getPerson();
233        requestObject.setUser(user.getPrincipalName());
234        for(OleAgreementDocumentMetadata agreementDoc : agreementDocs) {
235            requestDocument = new RequestDocument();
236            requestDocument.setId("1");
237            requestDocument.setUuid(agreementDoc.getAgreementUUID());
238            requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
239            requestDocument.setType("license");
240            requestDocument.setUser(agreementDoc.getUploadedBy());
241            String agreementFormat = agreementDoc.getAgreementFileName().substring(agreementDoc.getAgreementFileName().indexOf(".")+1,agreementDoc.getAgreementFileName().length());
242            if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
243                requestDocument.setFormat(agreementFormat);
244            }
245            else {
246                requestDocument.setFormat("doc");
247            }
248            requestDocument.setFormat(agreementFormat);
249            requestDocument.setDocumentName(agreementDoc.getAgreementFileName());
250            requestDocument.setDocumentTitle(agreementDoc.getAgreementName());
251            requestDocument.setDocumentMimeType(agreementDoc.getAgreementMimeType());
252            AdditionalAttributes additionalAttributes = new AdditionalAttributes();
253            additionalAttributes.setDateEntered(agreementDoc.getUploadedDate().toString());
254            additionalAttributes.setAttribute("label", agreementDoc.getAgreementName());
255            additionalAttributes.setAttribute("notes", agreementDoc.getAgreementNotes());
256            additionalAttributes.setAttribute("type", agreementDoc.getAgreementType());
257            requestDocument.setAdditionalAttributes(additionalAttributes);
258            requestDocuments.add(requestDocument);
259        }
260        requestObject.setRequestDocuments(requestDocuments);
261
262        RequestHandler requestHandler = new RequestHandler();
263        String requestXml = requestHandler.toXML(requestObject);
264        return requestXml;
265    }
266    /**
267     *  This method downloads the agreement document from the docStore based on uuid.
268     * @param oleAgreementDocumentMetadata
269     * @return File
270     */
271    public File downloadAgreementDocumentFromDocstore(OleAgreementDocumentMetadata oleAgreementDocumentMetadata) {
272        File resultFile = null;
273        String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
274        CompressUtils compressUtils = new CompressUtils();
275        File file = new File(getKualiConfigurationService().getPropertyValueAsString(
276                KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleAgreementDownloadConstants.AGREEMENT_CHECKOUT_LOCATION_ROOT);
277        file.mkdirs();
278        String requestXml = checkoutAgreementDocument(oleAgreementDocumentMetadata);
279        try {
280            File requestxml = new File(getKualiConfigurationService().getPropertyValueAsString(
281                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleAgreementDownloadConstants.AGREEMENT_CHECKOUT_LOCATION);
282            requestxml.createNewFile();
283            FileUtils.writeStringToFile(requestxml, requestXml);
284            File zipFile = compressUtils.createZippedBagFile(file);
285            requestxml.delete();
286            file.delete();
287            List<File> resp = postDataForLicense(docstoreURL, zipFile);
288            zipFile.delete();
289            for (File respFile : resp) {
290                if (respFile.getName().equalsIgnoreCase(oleAgreementDocumentMetadata.getAgreementFileName())) {
291                    return respFile;
292                }
293            }
294        }
295        catch(Exception e) {
296            LOG.error("Error while retriving form docstore");
297        }
298
299        return resultFile;
300    }
301
302    /**
303     * This method builds the requestXml for the checkOut of agreementdocument from the docstore.
304     * @param oleAgreementDocumentMetadata
305     * @return  String
306     */
307    private String checkoutAgreementDocument(OleAgreementDocumentMetadata oleAgreementDocumentMetadata) {
308        if (oleAgreementDocumentMetadata.getAgreementUUID() != null) {
309            Request request = new Request();
310
311            request.setUser(GlobalVariables.getUserSession().getPrincipalName());
312            request.setOperation("checkOut");
313            RequestDocument requestDocument = new RequestDocument();
314            requestDocument.setId("1");
315            requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
316            requestDocument.setType("license");
317            String agreementFormat = oleAgreementDocumentMetadata.getAgreementFileName().substring(oleAgreementDocumentMetadata.getAgreementFileName().indexOf(".")+1,
318                    oleAgreementDocumentMetadata.getAgreementFileName().length());
319            requestDocument.setFormat(agreementFormat);
320            requestDocument.setUuid(oleAgreementDocumentMetadata.getAgreementUUID());
321            request.getRequestDocuments().add(requestDocument);
322            RequestHandler requestHandler = new RequestHandler();
323            String requestXml = requestHandler.toXML(request);
324
325            return requestXml;
326        }
327        else {
328            LOG.error("UUId doesnt exit");
329        }
330        return null;
331    }
332
333    /**
334     * This method returns the uuid by  ingesting the agreement content to the docstore
335     * @param content
336     * @return   uuid
337     */
338    public String ingestAgreementContent(String content){
339        String uuid = "";
340        Response response = new Response();
341        CompressUtils compressUtils = new CompressUtils();
342        Request request = new Request();
343        request.setUser(GlobalVariables.getUserSession().getPrincipalName());
344        request.setOperation("ingest");
345        RequestDocument requestDocument = new RequestDocument();
346        requestDocument.setId("1");
347        requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
348        requestDocument.setType("license");
349        requestDocument.setFormat("onixpl");
350        requestDocument.getContent().setContent(content);
351        request.getRequestDocuments().add(requestDocument);
352        RequestHandler requestHandler = new RequestHandler();
353        String requestXml = requestHandler.toXML(request);
354        try{
355            File folder = new File(getKualiConfigurationService().getPropertyValueAsString(
356                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+File.separator+ File.separator+
357                    "tmp/");
358            folder.mkdir();
359            FileOutputStream fos = new FileOutputStream(new File(folder.getAbsolutePath() + File.separator +"request.xml"));
360            IOUtils.copy(IOUtils.toInputStream(requestXml), fos);
361            fos.close();
362            File zipFile = compressUtils.createZippedBagFile(folder);
363            folder.delete();
364            String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
365            List<File> resp = postDataForLicense(docstoreURL, zipFile);
366            for (File respFile : resp) {
367                if (respFile.getName().equalsIgnoreCase("response.xml")) {
368                    BufferedReader br = new BufferedReader(new FileReader(respFile));
369                    String line = null;
370                    while ((line = br.readLine()) != null)
371                        response = new ResponseHandler().toObject(FileUtils.readFileToString(respFile));
372                }
373            }
374        }
375        catch(Exception e) {
376            LOG.error("Error while Creating the request xml");
377        }
378        if(response.getStatus().equals("Success")) {
379            for (ResponseDocument responseDocument : response.getDocuments()) {
380                if(responseDocument.getFormat().equalsIgnoreCase("onixpl") &&
381                        responseDocument.getType().equalsIgnoreCase("license")) {
382                    uuid = responseDocument.getUuid();
383                }
384            }
385        }
386        return uuid;
387    }
388
389    /**
390     * This method returns the agreement content for the given uniqueId
391     * @param uuid
392     * @return agreementContent
393     */
394    public String getAgreementContent(String uuid){
395        String agreementContent = "";
396        Response response = new Response();
397        CompressUtils compressUtils = new CompressUtils();
398        if(uuid != null) {
399            Request request = new Request();
400            request.setUser(GlobalVariables.getUserSession().getPrincipalName());
401            request.setOperation("checkOut");
402            RequestDocument requestDocument = new RequestDocument();
403            requestDocument.setId("1");
404            requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
405            requestDocument.setType("license");
406            requestDocument.setFormat("onixpl");
407            requestDocument.setUuid(uuid);
408            request.getRequestDocuments().add(requestDocument);
409            RequestHandler requestHandler = new RequestHandler();
410            String requestXml = requestHandler.toXML(request);
411            try{
412                File folder =new File(getKualiConfigurationService().getPropertyValueAsString(
413                        KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+File.separator+ File.separator+
414                        "tmp/");
415                folder.mkdirs();
416                FileOutputStream fos = new FileOutputStream(new File(folder.getAbsolutePath() + File.separator +"request.xml"));
417                IOUtils.copy(IOUtils.toInputStream(requestXml), fos);
418                fos.close();
419                File zipFile = compressUtils.createZippedBagFile(folder);
420                folder.delete();
421                String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
422                List<File> resp = postDataForLicense(docstoreURL, zipFile);
423                for (File respFile : resp) {
424                    if (respFile.getName().equalsIgnoreCase("response.xml")) {
425                        BufferedReader br = new BufferedReader(new FileReader(respFile));
426                        String line = null;
427                        while ((line = br.readLine()) != null)
428                            response = new ResponseHandler().toObject(FileUtils.readFileToString(respFile));
429                    }
430                    respFile.delete();
431                }
432
433            }
434            catch(Exception e) {
435                LOG.error("Error while Creating the request xml");
436            }
437            if(response.getStatus().equals("Success")) {
438                for (ResponseDocument responseDocument : response.getDocuments()) {
439                    if(responseDocument.getFormat().equalsIgnoreCase("onixpl") &&
440                            responseDocument.getType().equalsIgnoreCase("license")) {
441                        agreementContent = responseDocument.getContent().getContent();
442                    }
443
444                }
445            }
446        }
447        else {
448            LOG.error("UUID of the Agreement Document is null");
449        }
450        return agreementContent;
451    }
452
453    /**
454     * This method returns the License request documents based on the criterias map
455     * @param licenseId
456     * @return  licenseRequestList
457     */
458    public int getLicenseAttachments(String licenseId){
459
460
461        BusinessObjectService service = KRADServiceLocator.getBusinessObjectService();
462        Map<String,String> documentCriteria = new HashMap<String,String>();
463        documentCriteria.put(OLEConstants.NAME, OLEConstants.OleLicenseRequest.LICENSE_REQUEST_DOC_TYPE);
464        List<DocumentType> documentTypeList= (List<DocumentType>) service.findMatching(DocumentType.class,documentCriteria);
465        List<OleAgreementDocumentMetadata> list = null;
466        Map<String,String> searchCriteria = new HashMap<String,String>();
467        for(int k=0;k<documentTypeList.size();k++){
468            searchCriteria.put(OLEConstants.DOC_TYP_ID,documentTypeList.get(k).getDocumentTypeId());
469            searchCriteria.put("documentId",licenseId);
470            List<DocumentRouteHeaderValue> documentList= ( List<DocumentRouteHeaderValue>)  service.findMatching(DocumentRouteHeaderValue.class,searchCriteria);
471            OleLicenseRequestBo licenseRequestBo ;
472            for(int i=0;i<documentList.size();i++){
473
474                LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentList.get(i).getDocContent());
475
476                licenseRequestBo=(OleLicenseRequestBo)bo.getDataObject();
477                list=licenseRequestBo.getAgreementDocumentMetadataList();
478
479            }
480
481        }
482        return list.size();
483
484    }
485
486    public List<OleLicenseRequestBo> findLicenseRequestByCriteria( Map<String, String> criteria)throws Exception{
487        boolean add =false ;
488        BusinessObjectService service = KRADServiceLocator.getBusinessObjectService();
489        List<OleLicenseRequestBo> licenseRequestList = new ArrayList<OleLicenseRequestBo>();
490        List<String> uuids = new ArrayList<String>();
491        boolean isTitlePresent = false;
492        boolean isValidDate = false;
493        String createdFromDate=criteria.get(OLEConstants.OleLicenseRequest.CREATED_FROM_DATE);
494        String createdToDate=criteria.get(OLEConstants.OleLicenseRequest.CREATED_TO_DATE);
495        String lastModifiedDateFrom = criteria.get(OLEConstants.OleLicenseRequest.LAST_MOD_FROM_DATE);
496        String lastModifiedDateTo = criteria.get(OLEConstants.OleLicenseRequest.LAST_MOD_TO_DATE);
497        String lastModifiedDateSearchType = criteria.get(OLEConstants.OleLicenseRequest.LAST_MOD_SEARCH_TYPE);
498        try {
499            //createdToDate=createdToDate.length()!=0?createdToDate:dateFormat.format(new Date());
500            //Timestamp createdDateTo = new Timestamp(dateFormat.parse(createdToDate).getTime());
501            //lastModifiedDateTo=lastModifiedDateTo.length()!=0?lastModifiedDateTo:dateFormat.format(new Date());
502            //Timestamp lastModifiedToDate = new Timestamp(dateFormat.parse(lastModifiedDateTo).getTime());
503            if(!("".equals(criteria.get(OLEConstants.OleLicenseRequest.BIB_TITLE)))) {
504                isTitlePresent =  true;
505                uuids = getUUIDs(criteria.get(OLEConstants.OleLicenseRequest.BIB_TITLE));
506            }
507            Map<String,String> documentCriteria = new HashMap<String,String>();
508            documentCriteria.put(OLEConstants.NAME, OLEConstants.OleLicenseRequest.LICENSE_REQUEST_DOC_TYPE);
509            List<DocumentType> documentTypeList= (List<DocumentType>) service.findMatching(DocumentType.class,documentCriteria);
510            Map<String,String> searchCriteria = new HashMap<String,String>();
511            for(int k=0;k<documentTypeList.size();k++){
512                searchCriteria.put(OLEConstants.DOC_TYP_ID,documentTypeList.get(k).getDocumentTypeId());
513                List<DocumentRouteHeaderValue> documentList= ( List<DocumentRouteHeaderValue>)  service.findMatching(DocumentRouteHeaderValue.class,searchCriteria);
514                OleLicenseRequestBo licenseRequestBo ;
515                for(int i=0;i<documentList.size();i++){
516                    add = false;
517                    LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentList.get(i).getDocContent());
518                    Date createDateInBo=documentList.get(i).getCreateDate();
519                    String strCreateDateInBo=dateFormat.format(createDateInBo);
520                    String lastModifiedDateInBo = dateFormat.format(documentList.get(i).getDateModified());
521                    boolean isValidCreateDate = false;
522                    boolean  isValidModifiedDate = false;
523                    boolean  isDateBlank = false;
524                    if (createdFromDate.isEmpty() && createdToDate.isEmpty() && lastModifiedDateFrom.isEmpty() && lastModifiedDateTo.isEmpty()){
525                        isDateBlank=true;
526                    }
527                    isValidCreateDate = validateDate(createDateInBo,createdFromDate,createdToDate);
528                    isValidModifiedDate = validateDate(documentList.get(i).getDateModified(),lastModifiedDateFrom,lastModifiedDateTo);
529                    if(lastModifiedDateSearchType.equalsIgnoreCase("true")){
530                        isValidDate =  isValidCreateDate && isValidModifiedDate;
531                    }
532                    else {
533                        isValidDate = (isValidCreateDate && !(createdFromDate .isEmpty() && createdToDate.isEmpty()))||
534                                (isValidModifiedDate && !(lastModifiedDateFrom.isEmpty() && lastModifiedDateTo.isEmpty()));
535                    }
536                    if(bo!=null && (isValidDate || isDateBlank)){
537                        licenseRequestBo =  (OleLicenseRequestBo) bo.getDataObject();
538                        if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.ASSIGNEE))) || (licenseRequestBo.getAssignee()!=null&&!licenseRequestBo.getAssignee().isEmpty()
539                                && licenseRequestBo.getAssignee().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.ASSIGNEE)))){
540                            if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.LOCATION_ID))) || (licenseRequestBo.getLocationId()!=null&&!licenseRequestBo.getLocationId().isEmpty()
541                                    &&licenseRequestBo.getLocationId().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.LOCATION_ID)))){
542                                if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.STATUS_CODE))) || (licenseRequestBo.getLicenseRequestStatusCode()!=null
543                                        && !licenseRequestBo.getLicenseRequestStatusCode().isEmpty()&&licenseRequestBo.getOleLicenseRequestStatus().getName().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.STATUS_CODE)))){
544                                    if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.LICENSE_REQUEST_TYPE_ID))) || (licenseRequestBo.getLicenseRequestTypeId()!=null
545                                            && !licenseRequestBo.getLicenseRequestTypeId().isEmpty()&&licenseRequestBo.getLicenseRequestTypeId().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.LICENSE_REQUEST_TYPE_ID)))){
546                                        add=true;
547                                    }}
548
549
550                            }}
551                        if(add){
552                            OleLicenseRequestBo oleLicenseRequestBo=getOleLicenseRequestBoWithDocNumb(licenseRequestBo);
553                            List<OleLicenseRequestItemTitle> itemTitleList = oleLicenseRequestBo.getOleLicenseRequestItemTitles();
554                            List<OleLicenseRequestItemTitle> newItemTitleList = new ArrayList<OleLicenseRequestItemTitle>();
555                            if(itemTitleList!=null && itemTitleList.size()>0 ){
556                                OleLicenseRequestBo newLicenseRequestBo;
557                                for(int j=0;j<itemTitleList.size();j++){
558                                    newLicenseRequestBo = (OleLicenseRequestBo) ObjectUtils.deepCopy(licenseRequestBo);
559                                    newLicenseRequestBo.setOleLicenseRequestItemTitles(null);
560                                    newItemTitleList.add(itemTitleList.get(j));
561                                    newLicenseRequestBo.setOleLicenseRequestItemTitles(newItemTitleList);
562                                    newLicenseRequestBo.setDocumentNumber(documentList.get(i).getDocumentContent().getDocumentId());
563                                    newLicenseRequestBo.setCreatedDate(documentList.get(i).getCreateDate());
564                                    newLicenseRequestBo.setCreatedDateFrom(documentList.get(i).getCreateDate());
565                                    if(isTitlePresent) {
566                                        if(uuids.size() > 0 && uuids.contains(itemTitleList.get(j).getItemUUID())) {
567                                            String bibliographicTitle= getDescription(itemTitleList.get(j).getItemUUID());
568                                            newLicenseRequestBo.setBibliographicTitle(bibliographicTitle);
569                                            if (newLicenseRequestBo.getLocationId() != null && !newLicenseRequestBo.getLocationId().isEmpty()) {
570                                                newLicenseRequestBo.setOleLicenseRequestLocation(getLicenseRequestLocation(newLicenseRequestBo.getLocationId()));
571                                            }
572                                            if (newLicenseRequestBo.getLicenseRequestTypeId() != null && !newLicenseRequestBo.getLicenseRequestTypeId().isEmpty()) {
573                                                newLicenseRequestBo.setOleLicenseRequestType(getLicenseRequestType(newLicenseRequestBo.getLicenseRequestTypeId()));
574                                            }
575                                            licenseRequestList.add(newLicenseRequestBo);
576                                        }
577                                    }
578                                    else {
579                                        String bibliographicTitle= getDescription(itemTitleList.get(j).getItemUUID());
580                                        newLicenseRequestBo.setBibliographicTitle(bibliographicTitle);
581                                        if (newLicenseRequestBo.getLocationId() != null && !newLicenseRequestBo.getLocationId().isEmpty()) {
582                                            newLicenseRequestBo.setOleLicenseRequestLocation(getLicenseRequestLocation(newLicenseRequestBo.getLocationId()));
583                                        }
584                                        if (newLicenseRequestBo.getLicenseRequestTypeId() != null && !newLicenseRequestBo.getLicenseRequestTypeId().isEmpty()) {
585                                            newLicenseRequestBo.setOleLicenseRequestType(getLicenseRequestType(newLicenseRequestBo.getLicenseRequestTypeId()));
586                                        }
587                                        licenseRequestList.add(newLicenseRequestBo);
588                                    }
589                                }
590                            }
591                            else if (!isTitlePresent){
592                                licenseRequestBo.setDocumentNumber(documentList.get(i).getDocumentContent().getDocumentId());
593                                licenseRequestBo.setCreatedDate(documentList.get(i).getCreateDate());
594                                licenseRequestBo.setCreatedDateFrom(documentList.get(i).getCreateDate());
595                                licenseRequestList.add(licenseRequestBo);
596                            }
597
598                        }
599                    }  }
600            }
601        }catch  (ParseException e) {
602            e.printStackTrace();
603        }
604        return licenseRequestList;
605    }
606
607    private OleLicenseRequestLocation getLicenseRequestLocation(String id) {
608        OleLicenseRequestLocation oleLicenseRequestLocation = KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleLicenseRequestLocation.class,
609                id);
610        return oleLicenseRequestLocation;
611    }
612
613    private OleLicenseRequestType getLicenseRequestType (String licenseRequestTypeId) {
614        OleLicenseRequestType oleLicenseRequestType = KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleLicenseRequestType.class, licenseRequestTypeId);
615        return oleLicenseRequestType;
616    }
617
618
619    public OleLicenseRequestBo getLicenseRequestFromDocumentContent(String documentContent) {
620        OleLicenseRequestBo oleLicenseRequestBo = null;
621        LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentContent);
622        oleLicenseRequestBo =  (OleLicenseRequestBo) bo.getDataObject();
623        return oleLicenseRequestBo;
624    }
625    /**
626     * This method returns the license request documentNum for the given requisition documet number
627     * @param reqDocNum
628     * @return  licenseRequestDocNum
629     */
630   /* public String getLicenseRequestByRequisitionDocNum(String reqDocNum) {
631        BusinessObjectService service = KRADServiceLocator.getBusinessObjectService();
632        Map<String,String> documentCriteria = new HashMap<String,String>();
633        documentCriteria.put(OLEConstants.NAME,OLEConstants.OleLicenseRequest.LICENSE_REQUEST_DOC_TYPE);
634        List<DocumentType> documentTypeList= (List<DocumentType>) service.findMatching(DocumentType.class,documentCriteria);
635        Map<String,String> searchCriteria = new HashMap<String,String>();
636        for(int i=0;i<documentTypeList.size();i++){
637            searchCriteria.put(OLEConstants.DOC_TYP_ID,documentTypeList.get(i).getDocumentTypeId());
638        }
639        List<DocumentRouteHeaderValue> documentList= ( List<DocumentRouteHeaderValue>)  service.findMatching(DocumentRouteHeaderValue.class,searchCriteria);
640        String licenseRequestDocNum = "";
641        OleLicenseRequestBo licenseRequestBo ;
642        for(int i=0;i<documentList.size();i++){
643            LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentList.get(i).getDocContent());
644
645            if(bo!=null){
646                licenseRequestBo =  (OleLicenseRequestBo) bo.getDataObject();
647                if(("".equals(reqDocNum)) || (licenseRequestBo.getRequisitionDocNumber()!=null&&!licenseRequestBo.getRequisitionDocNumber().isEmpty()
648                        && licenseRequestBo.getRequisitionDocNumber().equals(reqDocNum))){
649                    licenseRequestDocNum = licenseRequestBo.getDocumentNumber();
650                }
651            }
652        }
653        return licenseRequestDocNum;
654    }*/
655
656    /**
657     * This method converts the xml content into bussinessObjectBase class
658     * @param xmlDocumentContents
659     * @return   businessObject
660     */
661    private Object getDataObjectFromXML(String xmlDocumentContents) {
662        if(xmlDocumentContents!=null || !"".equals(xmlDocumentContents) || !xmlDocumentContents.isEmpty()) {
663            String maintXml = StringUtils.substringBetween(xmlDocumentContents, OLEConstants.OleLicenseRequest.START_TAG,
664                    OLEConstants.OleLicenseRequest.END_TAG);
665            Object businessObject =null;
666            if(maintXml!=null){
667                maintXml = maintXml.substring(2,maintXml.length());
668                businessObject = KRADServiceLocator.getXmlObjectSerializerService().fromXml(maintXml);
669            }
670            return businessObject;                                                                            }
671        else{
672            return null;
673        }
674    }
675
676    /**
677     * This method returns the bibliographic title for the given uuid
678     * @param bibUuid
679     * @return   itemDescription
680     */
681    private String getDescription(String bibUuid){
682        String itemDescription=null;
683        String title=null;
684        String author=null;
685        String publisher=null;
686        String isbn=null;
687        try{
688            List<HashMap<String, Object>> bibDocumentList= QueryServiceImpl.getInstance().retriveResults("id:"+bibUuid);
689            HashMap<String, Object> bibValues = bibDocumentList.get(0);
690
691            ArrayList<String> titleList= (ArrayList<String>) bibValues.get("Title_display");
692            ArrayList<String> authorList= (ArrayList<String>) bibValues.get("Author_display");
693            ArrayList<String> publisherList= (ArrayList<String>) bibValues.get("Publisher_display");
694            ArrayList<String> isbnList= (ArrayList<String>) bibValues.get("ISBN_display");
695            if(titleList!=null){
696                title=titleList.get(0);
697            }
698            if(authorList!=null){
699                author=authorList.get(0);
700            }
701            if(publisherList!=null){
702                publisher=publisherList.get(0);}
703            if(isbnList!=null) {
704                isbn=isbnList.get(0);
705            }
706            itemDescription  = (( title!=null && ! title.isEmpty()) ? title+"," : "");
707            /*+
708      (( author!=null&&!author.isEmpty())? author+"," : "") +
709      ((publisher!=null&&!publisher.isEmpty()) ?   publisher+"," : "") +
710      ((isbn!=null&&!isbn.isEmpty() ) ?  isbn+"," : "");*/
711            if(itemDescription != null && !(itemDescription.equals(""))){
712                itemDescription = itemDescription.substring(0, itemDescription.lastIndexOf(","));
713            }
714
715        }catch(Exception e){
716            e.printStackTrace();
717        }
718        return itemDescription;
719    }
720
721
722    /**
723     * This method returns the uuids for the given bibliographic Title
724     * @param title
725     * @return   uuids
726     */
727    private List<String> getUUIDs(String title){
728        StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
729        List<String> uuids = new ArrayList<String>();
730        try{
731            List<HashMap<String, Object>> bibDocumentList= QueryServiceImpl.getInstance().retriveResults(queryString+ stringEscapeUtils.escapeXml(title));
732            if(bibDocumentList.size() > 0) {
733                Iterator listIterator = bibDocumentList.iterator();
734                while(listIterator.hasNext()) {
735                    Map results = (Map)listIterator.next();
736                    uuids.add((String)results.get("uniqueId"));
737                }
738            }
739        }catch(Exception e){
740            e.printStackTrace();
741        }
742        return uuids;
743    }
744    private ConfigurationService getKualiConfigurationService() {
745        return KRADServiceLocator.getKualiConfigurationService();
746    }
747
748    /**
749     * This method will delete the Agreement Document Content from the docstore
750     * @param metadata
751     * * @return boolean
752     */
753    public boolean deleteAgreementDocument(OleAgreementDocumentMetadata metadata) {
754        String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
755        String deleteRequestXml = "";
756        List<File> resp = new ArrayList<File>();
757        CompressUtils compressUtils = new CompressUtils();
758        File file = new File(getKualiConfigurationService().getPropertyValueAsString(
759                KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_DELETE);
760        file.mkdirs();
761        File requestxml = new File(getKualiConfigurationService().getPropertyValueAsString(
762                KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_DELETE +File.separator+
763                "request.xml");
764
765        try {
766            deleteRequestXml = buildDeleteAgreementRequestXml(metadata);
767            requestxml.createNewFile();
768            FileUtils.writeStringToFile(requestxml, deleteRequestXml);
769            File zipFile = compressUtils.createZippedBagFile(file);
770            file.delete();
771            Response response = new Response();
772            resp = postDataForLicense(docstoreURL, zipFile);
773            requestxml.delete();
774            zipFile.delete();
775            for (File respFile : resp) {
776                if (respFile.getName().equalsIgnoreCase("response.xml")) {
777                    BufferedReader br = new BufferedReader(new FileReader(respFile));
778                    String line = null;
779                    while ((line = br.readLine()) != null)
780                        response = new ResponseHandler().toObject(FileUtils.readFileToString(respFile));
781                }
782            }
783            if(response.getStatus().equals("Success")) {
784                return true;
785            }
786        }
787        catch (Exception e) {
788            LOG.error(e.getMessage());
789        }
790
791        return false;
792
793    }
794
795    /**
796     * This method will generate the request xml for the delete operation.
797     * @param metadata
798     * @return  rollBackXml
799     */
800    private String buildDeleteAgreementRequestXml(OleAgreementDocumentMetadata metadata){
801        ResponseHandler responseHandler = new ResponseHandler();
802        RequestHandler requestHandler = new RequestHandler();
803        Request request = new Request();
804        request.setUser("khuntley");
805        request.setOperation("delete");
806        RequestDocument requestDocument = new RequestDocument();
807        requestDocument.setId("1");
808        requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
809        requestDocument.setType("license");
810        requestDocument.setUuid(metadata.getAgreementUUID());
811        String agreementFormat = metadata.getAgreementFileName().substring(metadata.getAgreementFileName().indexOf(".")+1
812                ,metadata.getAgreementFileName().length());
813        if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
814            requestDocument.setFormat(agreementFormat);
815        }
816        else {
817            requestDocument.setFormat("doc");
818        }
819        //requestDocument.setFormat(agreementFormat);
820        List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
821        requestDocuments.add(requestDocument);
822        request.setRequestDocuments(requestDocuments);
823        String rollBackXml = requestHandler.toXML(request);
824        return rollBackXml;
825    }
826    @Override
827    public boolean validateDate (Date documentDate, String fromDate, String toDate)throws Exception{
828        boolean isValidDate = false ;
829        String dateToCompare = "";
830        if(documentDate != null ) {
831            dateToCompare=dateFormat.format(documentDate);
832        }
833        try {
834            if (((toDate == null || toDate.isEmpty()) && fromDate != null && !fromDate.isEmpty())
835                    && (dateToCompare.equals(fromDate) || (documentDate != null && documentDate.after(dateFormat.parse(fromDate))))) {
836                isValidDate = true;
837            }
838            else if ( ((fromDate == null || fromDate.isEmpty()) && toDate != null && !toDate.isEmpty())
839                    && (dateToCompare.equals(toDate) || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))) {
840                isValidDate = true;
841            }
842            else if (((fromDate == null || fromDate.isEmpty() ) && ((toDate == null) || toDate.isEmpty())) ||
843                    ((fromDate != null && (dateToCompare.equals(fromDate) || (documentDate != null && documentDate.after(dateFormat.parse(fromDate))))) &&
844                            (toDate != null && (dateToCompare.equals(toDate) || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))))) {
845                isValidDate = true;
846            }
847        }
848        catch (Exception e) {
849            LOG.error("Error while comparing the date" + e.getMessage());
850            throw new RuntimeException(e);
851        }
852        return isValidDate;
853
854    }
855    public OleLicenseRequestBo getOleLicenseRequestBoWithDocNumb(OleLicenseRequestBo oleLicenseRequestBo){
856        Map<String,String> map=new HashMap<>();
857        map.put(OLEConstants.OLEEResourceRecord.ERESOURCE_DOC_NUMBER,oleLicenseRequestBo.geteResourceDocNumber());
858        return KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleLicenseRequestBo.class,map);
859    }
860}