View Javadoc
1   package org.kuali.ole.service.impl;
2   
3   import org.apache.commons.io.FileUtils;
4   import org.apache.commons.io.IOUtils;
5   import org.apache.commons.lang.StringEscapeUtils;
6   import org.apache.commons.lang.StringUtils;
7   import org.apache.http.HttpEntity;
8   import org.apache.http.HttpResponse;
9   import org.apache.http.client.HttpClient;
10  import org.apache.http.client.methods.HttpPost;
11  import org.apache.http.entity.mime.MultipartEntity;
12  import org.apache.http.entity.mime.content.FileBody;
13  import org.apache.http.impl.client.DefaultHttpClient;
14  import org.apache.log4j.Logger;
15  import org.kuali.ole.OLEConstants;
16  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
17  import org.kuali.ole.docstore.common.document.License;
18  import org.kuali.ole.docstore.common.document.LicenseAttachment;
19  import org.kuali.ole.docstore.common.document.LicenseOnixpl;
20  import org.kuali.ole.docstore.common.document.Licenses;
21  import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
22  import org.kuali.ole.select.bo.*;
23  import org.kuali.ole.select.controller.LicenceRoutingRuleDelegationMaintainable;
24  import org.kuali.ole.select.document.OLEEResourceRecordDocument;
25  import org.kuali.ole.service.OLEEResourceSearchService;
26  import org.kuali.ole.service.OleLicenseRequestService;
27  import org.kuali.ole.sys.context.SpringContext;
28  import org.kuali.ole.utility.CompressUtils;
29  import org.kuali.rice.core.api.config.property.ConfigContext;
30  import org.kuali.rice.core.api.config.property.ConfigurationService;
31  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
32  import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
33  import org.kuali.rice.kew.doctype.bo.DocumentType;
34  import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
35  import org.kuali.rice.kim.api.identity.Person;
36  import org.kuali.rice.krad.service.BusinessObjectService;
37  import org.kuali.rice.krad.service.KRADServiceLocator;
38  import org.kuali.rice.krad.util.GlobalVariables;
39  import org.kuali.rice.krad.util.KRADConstants;
40  import org.kuali.rice.krad.util.ObjectUtils;
41  
42  import java.io.*;
43  import java.text.ParseException;
44  import java.text.SimpleDateFormat;
45  import java.util.*;
46  
47  /**
48   * OleLicenseRequestServiceImpl builds the Xml for the Agreement Document ingest operation.
49   */
50  public class OleLicenseRequestServiceImpl implements OleLicenseRequestService {
51  
52      private static final Logger LOG = Logger.getLogger(OleLicenseRequestServiceImpl.class);
53      private static final String DOCSTORE_URL = "docstore.url";
54      private static final String queryString = "DocType:bibliographic AND Title_search:";
55      private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
56      private OLEEResourceSearchService oleEResourceSearchService = null;
57      private DocstoreClientLocator docstoreClientLocator;
58  
59      public DocstoreClientLocator getDocstoreClientLocator() {
60          if (null == docstoreClientLocator) {
61              return  SpringContext.getBean(DocstoreClientLocator.class);
62          }
63          return docstoreClientLocator;
64      }
65  
66  
67      /**
68       *  This method creates the multipart entity  based on zipfile and sent to the target location,
69       *
70       * @param target
71       * @param zipFile
72       * @return List<File>
73       * @throws Exception
74       */
75  //    public static List<File> postDataForLicense(String target, File zipFile) throws Exception {
76  //        CompressUtils compressUtils = new CompressUtils();
77  //        HttpPost httpPost = new HttpPost(target);
78  //        HttpClient httpclient = new DefaultHttpClient();
79  //        FileBody uploadFilePart = new FileBody(zipFile);
80  //        MultipartEntity reqEntity = new MultipartEntity();
81  //        reqEntity.addPart("upload-file", uploadFilePart);
82  //        httpPost.setEntity(reqEntity);
83  //
84  //        HttpResponse httpResponse = httpclient.execute(httpPost);
85  //
86  //        HttpEntity respEntity = httpResponse.getEntity();
87  //        InputStream outcome = respEntity.getContent();
88  //        File respFile = File.createTempFile("DocStore Ingest-", "-Response File.zip");
89  //        IOUtils.copy(outcome, new FileOutputStream(respFile));
90  //        List<File> resp = compressUtils.getAllFilesList(compressUtils.extractZippedBagFile(respFile.getAbsolutePath(), null));
91  //        return resp;
92  //    }
93      /**
94       *  This method creates the zipped Bag file which contains the requestXml and the File to be uploaded to the docStore and
95       *                  process the response file to get the uuid.
96       * @param oleAgreementDocs
97       * @return List<OleAgreementDocumentMetadata>
98       */
99      public List<OleAgreementDocumentMetadata> processIngestAgreementDocuments(List<OleAgreementDocumentMetadata> oleAgreementDocs) {
100         try {
101             String filePath = getKualiConfigurationService().getPropertyValueAsString(
102                     KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + OLEConstants.OleLicenseRequest.AGREEMENT_TMP_LOCATION;
103 
104             File file = new File(filePath);
105             file.mkdirs();
106             Licenses licenses = new Licenses();
107             for (OleAgreementDocumentMetadata oleAgreementDoc : oleAgreementDocs) {
108                 LicenseAttachment licenseAttachment = new LicenseAttachment();
109                 licenseAttachment.setFilePath(filePath);
110                 licenseAttachment.setFileName(oleAgreementDoc.getAgreementFileName());
111 //                File agreementDoc = new File(filePath + File.separator + oleAgreementDoc.getAgreementFileName());
112 //                FileUtils.copyFileToDirectory(agreementDoc, file);
113                 String agreementFormat = oleAgreementDoc.getAgreementFileName().substring(oleAgreementDoc.getAgreementFileName().indexOf(".")+1,oleAgreementDoc.getAgreementFileName().length());
114                 if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
115                     licenseAttachment.setFormat(agreementFormat);
116                 }
117                 else {
118                     licenseAttachment.setFormat("doc");
119                 }
120 //                licenseAttachment.setByteContent(FileUtils.readFileToByteArray(agreementDoc));
121                 licenseAttachment.setFileName(oleAgreementDoc.getAgreementFileName());
122                 licenseAttachment.setDocumentTitle(oleAgreementDoc.getAgreementName());
123                 licenseAttachment.setDocumentMimeType(oleAgreementDoc.getAgreementMimeType());
124                 licenseAttachment.setAgreementNote(oleAgreementDoc.getAgreementNotes());
125                 licenseAttachment.setAgreementType(oleAgreementDoc.getAgreementType());
126                 licenses.getLicenses().add(licenseAttachment);
127             }
128 
129             getDocstoreClientLocator().getDocstoreClient().createLicenses(licenses);
130             Iterator agreementDocIterator = oleAgreementDocs.iterator();
131             for (License license : licenses.getLicenses()) {
132                 OleAgreementDocumentMetadata agreementDocumentMetadata = (OleAgreementDocumentMetadata) agreementDocIterator.next();
133                 agreementDocumentMetadata.setAgreementUUID(license.getId());
134                 File agreementDoc = new File(filePath + File.separator + agreementDocumentMetadata.getAgreementFileName());
135                 agreementDoc.delete();
136             }
137 
138         } catch(Exception e) {
139             e.printStackTrace();
140         }
141         return oleAgreementDocs;
142     }
143     /**
144      *  This method creates the zipped Bag file which contains the requestXml and the File to be updated to the docStore and
145      *                  process the response file to get the uuid (after the checkin).
146      * @param oleAgreementDocs
147      * @return List<oleAgreementDocumentMetadata>
148      */
149     public List<OleAgreementDocumentMetadata> processCheckInAgreementDocuments(List<OleAgreementDocumentMetadata> oleAgreementDocs) {
150         try {
151 //            String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
152             CompressUtils compressUtils = new CompressUtils();
153             File file = new File(getKualiConfigurationService().getPropertyValueAsString(
154                     KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleLicenseRequest.AGREEMENT_LOCATION);
155             file.mkdirs();
156             Licenses licenses = buildCheckInAgreementRequestXml(oleAgreementDocs);
157             getDocstoreClientLocator().getDocstoreClient().updateLicenses(licenses);
158         }
159 
160         catch(Exception e) {
161             e.printStackTrace();
162         }
163         return oleAgreementDocs;
164 
165     }
166     /**
167      *  This method builds the requestXml for the Agreement Document ingest operation.
168      * @param agreementDocs
169      * @return requestXml
170      */
171 
172 //    private String buildIngestAgreementRequestXml(List<OleAgreementDocumentMetadata> agreementDocs) {
173 //        Request requestObject = new Request();
174 //        RequestDocument requestDocument;
175 //        ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
176 //        requestObject.setOperation("ingest");
177 //        Person user = GlobalVariables.getUserSession().getPerson();
178 //        requestObject.setUser(user.getPrincipalName());
179 //        for(OleAgreementDocumentMetadata agreementDoc : agreementDocs) {
180 //            requestDocument = new RequestDocument();
181 //            requestDocument.setId("1");
182 //            requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
183 //            requestDocument.setType("license");
184 //            requestDocument.setUser(agreementDoc.getUploadedBy());
185 //            String agreementFormat = agreementDoc.getAgreementFileName().substring(agreementDoc.getAgreementFileName().indexOf(".")+1,agreementDoc.getAgreementFileName().length());
186 //            if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
187 //                requestDocument.setFormat(agreementFormat);
188 //            }
189 //            else {
190 //                requestDocument.setFormat("doc");
191 //            }
192 //
193 //            requestDocument.setDocumentName(agreementDoc.getAgreementFileName());
194 //            requestDocument.setDocumentTitle(agreementDoc.getAgreementName());
195 //            requestDocument.setDocumentMimeType(agreementDoc.getAgreementMimeType());
196 //            AdditionalAttributes additionalAttributes = new AdditionalAttributes();
197 //            additionalAttributes.setDateEntered(agreementDoc.getUploadedDate().toString());
198 //            additionalAttributes.setAttribute("label", agreementDoc.getAgreementName());
199 //            additionalAttributes.setAttribute("notes", agreementDoc.getAgreementNotes());
200 //            additionalAttributes.setAttribute("type",agreementDoc.getAgreementType());
201 //            requestDocument.setAdditionalAttributes(additionalAttributes);
202 //            requestDocuments.add(requestDocument);
203 //        }
204 //        requestObject.setRequestDocuments(requestDocuments);
205 //
206 //        RequestHandler requestHandler = new RequestHandler();
207 //        String requestXml = requestHandler.toXML(requestObject);
208 //        return requestXml;
209 //    }
210 
211     /**
212      * This method builds the requestXml for the checkin operation of the agreement document.
213      * @param agreementDocs
214      * @return  requestXml
215      */
216     private Licenses buildCheckInAgreementRequestXml(List<OleAgreementDocumentMetadata> agreementDocs) {
217         Licenses licenses = new Licenses();
218 
219         for(OleAgreementDocumentMetadata agreementDoc : agreementDocs) {
220             License license = null;
221             String agreementFormat = agreementDoc.getAgreementFileName().substring(agreementDoc.getAgreementFileName().indexOf(".")+1,agreementDoc.getAgreementFileName().length());
222             if((agreementFormat.equals("pdf")) || (agreementFormat.equals("xslt")) || (agreementFormat.equals("doc"))) {
223                 LicenseAttachment licenseAttachment = new LicenseAttachment();
224                 licenseAttachment.setFormat(agreementFormat);
225                 licenseAttachment.setFileName(agreementDoc.getAgreementFileName());
226                 licenseAttachment.setDocumentTitle(agreementDoc.getAgreementName());
227                 licenseAttachment.setDocumentMimeType(agreementDoc.getAgreementMimeType());
228                 licenseAttachment.setAgreementType(agreementDoc.getAgreementType());
229                 license = licenseAttachment;
230 
231             }
232             else {
233                 license = new LicenseOnixpl();
234                 license.setFormat("onixpl");
235             }
236 
237             license.setId(agreementDoc.getAgreementUUID());
238             license.setCategory(OLEConstants.WORK_CATEGORY);
239             license.setType("license");
240             license.setUpdatedBy(agreementDoc.getUploadedBy());
241             licenses.getLicenses().add(license);
242         }
243         return licenses;
244     }
245     /**
246      *  This method downloads the agreement document from the docStore based on uuid.
247      * @param oleAgreementDocumentMetadata
248      * @return File
249      */
250     public File downloadAgreementDocumentFromDocstore(OleAgreementDocumentMetadata oleAgreementDocumentMetadata) {
251 //        File resultFile = null;
252 //        String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
253 //        CompressUtils compressUtils = new CompressUtils();
254 //        File file = new File(getKualiConfigurationService().getPropertyValueAsString(
255 //                KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleAgreementDownloadConstants.AGREEMENT_CHECKOUT_LOCATION_ROOT);
256 //        file.mkdirs();
257 //        String requestXml = checkoutAgreementDocument(oleAgreementDocumentMetadata);
258 //        try {
259 //            File requestxml = new File(getKualiConfigurationService().getPropertyValueAsString(
260 //                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ OLEConstants.OleAgreementDownloadConstants.AGREEMENT_CHECKOUT_LOCATION);
261 //            requestxml.createNewFile();
262 //            FileUtils.writeStringToFile(requestxml, requestXml);
263 //            File zipFile = compressUtils.createZippedBagFile(file);
264 //            requestxml.delete();
265 //            file.delete();
266 //            List<File> resp = postDataForLicense(docstoreURL, zipFile);
267 //            zipFile.delete();
268 //            for (File respFile : resp) {
269 //                if (respFile.getName().equalsIgnoreCase(oleAgreementDocumentMetadata.getAgreementFileName())) {
270 //                    return respFile;
271 //                }
272 //            }
273 //        }
274 //        catch(Exception e) {
275 //            LOG.error("Error while retriving form docstore");
276 //        }
277 
278         try {
279             LOG.info("License id to retrieve : " + oleAgreementDocumentMetadata.getAgreementUUID());
280             LicenseAttachment licenseAttachment = (LicenseAttachment) getDocstoreClientLocator().getDocstoreClient().retrieveLicense(oleAgreementDocumentMetadata.getAgreementUUID());
281 
282             File resultFile = new File(licenseAttachment.getFilePath() + File.separator + licenseAttachment.getFileName());
283             return resultFile;
284         } catch (Exception e) {
285             e.printStackTrace();
286         }
287 
288         return null;
289     }
290 
291     /**
292      * This method builds the requestXml for the checkOut of agreementdocument from the docstore.
293      * @param oleAgreementDocumentMetadata
294      * @return  String
295      */
296 //    private String checkoutAgreementDocument(OleAgreementDocumentMetadata oleAgreementDocumentMetadata) {
297 //        if (oleAgreementDocumentMetadata.getAgreementUUID() != null) {
298 //            Request request = new Request();
299 //
300 //            request.setUser(GlobalVariables.getUserSession().getPrincipalName());
301 //            request.setOperation("checkOut");
302 //            RequestDocument requestDocument = new RequestDocument();
303 //            requestDocument.setId("1");
304 //            requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
305 //            requestDocument.setType("license");
306 //            String agreementFormat = oleAgreementDocumentMetadata.getAgreementFileName().substring(oleAgreementDocumentMetadata.getAgreementFileName().indexOf(".")+1,
307 //                    oleAgreementDocumentMetadata.getAgreementFileName().length());
308 //            requestDocument.setFormat(agreementFormat);
309 //            requestDocument.setUuid(oleAgreementDocumentMetadata.getAgreementUUID());
310 //            request.getRequestDocuments().add(requestDocument);
311 //            RequestHandler requestHandler = new RequestHandler();
312 //            String requestXml = requestHandler.toXML(request);
313 //
314 //            return requestXml;
315 //        }
316 //        else {
317 //            LOG.error("UUId doesnt exit");
318 //        }
319 //        return null;
320 //    }
321 
322     /**
323      * This method returns the uuid by  ingesting the agreement content to the docstore
324      * @param content
325      * @return   uuid
326      */
327     public String ingestAgreementContent(String content) {
328         License licenseOnixpl = new LicenseOnixpl();
329         String uuid = "";
330         licenseOnixpl.setCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
331         licenseOnixpl.setCategory(OLEConstants.WORK_CATEGORY);
332         licenseOnixpl.setType("license");
333         licenseOnixpl.setFormat("onixpl");
334         licenseOnixpl.setContent(content);
335         Licenses licenses = new Licenses();
336         licenses.getLicenses().add(licenseOnixpl);
337         try {
338             getDocstoreClientLocator().getDocstoreClient().createLicenses(licenses);
339         }
340          catch (Exception e) {
341              LOG.error("Exception while ingesting aggrement content", e);
342          }
343         return licenseOnixpl.getId();
344     }
345 
346     /**
347      * This method returns the agreement content for the given uniqueId
348      * @param uuid
349      * @return agreementContent
350      */
351     public String getAgreementContent(String uuid){
352         String agreementContent = "";
353         try {
354             LOG.info("License content id to retrieve : " + uuid);
355             License license = getDocstoreClientLocator().getDocstoreClient().retrieveLicense(uuid);
356             agreementContent = license.getContent();
357         }
358         catch (Exception e) {
359             LOG.error("Exception while getting agreement content", e);
360         }
361 
362         return agreementContent;
363     }
364 
365     /**
366      * This method returns the License request documents based on the criterias map
367      * @param licenseId
368      * @return  licenseRequestList
369      */
370     public int getLicenseAttachments(String licenseId){
371 
372 
373         BusinessObjectService service = KRADServiceLocator.getBusinessObjectService();
374         Map<String,String> documentCriteria = new HashMap<String,String>();
375         documentCriteria.put(OLEConstants.NAME, OLEConstants.OleLicenseRequest.LICENSE_REQUEST_DOC_TYPE);
376         List<DocumentType> documentTypeList= (List<DocumentType>) service.findMatching(DocumentType.class,documentCriteria);
377         List<OleAgreementDocumentMetadata> list = null;
378         Map<String,String> searchCriteria = new HashMap<String,String>();
379         for(int k=0;k<documentTypeList.size();k++){
380             searchCriteria.put(OLEConstants.DOC_TYP_ID,documentTypeList.get(k).getDocumentTypeId());
381             searchCriteria.put("documentId",licenseId);
382             List<DocumentRouteHeaderValue> documentList= ( List<DocumentRouteHeaderValue>)  service.findMatching(DocumentRouteHeaderValue.class,searchCriteria);
383             OleLicenseRequestBo licenseRequestBo ;
384             for(int i=0;i<documentList.size();i++){
385 
386                 LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentList.get(i).getDocContent());
387 
388                 licenseRequestBo=(OleLicenseRequestBo)bo.getDataObject();
389                 list=licenseRequestBo.getAgreementDocumentMetadataList();
390 
391             }
392 
393         }
394         return list.size();
395 
396     }
397     public OLEEResourceSearchService getOleEResourceSearchService() {
398         if (oleEResourceSearchService == null) {
399             oleEResourceSearchService = GlobalResourceLoader.getService(OLEConstants.OLEEResourceRecord.ERESOURSE_SEARCH_SERVICE);
400         }
401         return oleEResourceSearchService;
402     }
403 
404     public List<OleLicenseRequestBo> findLicenseRequestByCriteria( Map<String, String> criteria)throws Exception{
405         boolean add =false ;
406         BusinessObjectService service = KRADServiceLocator.getBusinessObjectService();
407         List<OleLicenseRequestBo> licenseRequestList = new ArrayList<OleLicenseRequestBo>();
408         //List<String> uuids = new ArrayList<String>();
409         //boolean isTitlePresent = false;
410         boolean isValidDate = false;
411         String createdFromDate=criteria.get(OLEConstants.OleLicenseRequest.CREATED_FROM_DATE);
412         String createdToDate=criteria.get(OLEConstants.OleLicenseRequest.CREATED_TO_DATE);
413         String lastModifiedDateFrom = criteria.get(OLEConstants.OleLicenseRequest.LAST_MOD_FROM_DATE);
414         String lastModifiedDateTo = criteria.get(OLEConstants.OleLicenseRequest.LAST_MOD_TO_DATE);
415         String lastModifiedDateSearchType = criteria.get(OLEConstants.OleLicenseRequest.LAST_MOD_SEARCH_TYPE);
416         try {
417             //createdToDate=createdToDate.length()!=0?createdToDate:dateFormat.format(new Date());
418             //Timestamp createdDateTo = new Timestamp(dateFormat.parse(createdToDate).getTime());
419             //lastModifiedDateTo=lastModifiedDateTo.length()!=0?lastModifiedDateTo:dateFormat.format(new Date());
420             //Timestamp lastModifiedToDate = new Timestamp(dateFormat.parse(lastModifiedDateTo).getTime());
421             /*if(!("".equals(criteria.get(OLEConstants.OleLicenseRequest.BIB_TITLE)))) {
422                 isTitlePresent =  true;
423                 uuids = getUUIDs(criteria.get(OLEConstants.OleLicenseRequest.BIB_TITLE));
424             }*/
425             Map<String,String> documentCriteria = new HashMap<String,String>();
426             documentCriteria.put(OLEConstants.NAME, OLEConstants.OleLicenseRequest.LICENSE_REQUEST_DOC_TYPE);
427             List<DocumentType> documentTypeList= (List<DocumentType>) service.findMatching(DocumentType.class,documentCriteria);
428             Map<String,String> searchCriteria = new HashMap<String,String>();
429             for(int k=0;k<documentTypeList.size();k++){
430                 searchCriteria.put(OLEConstants.DOC_TYP_ID,documentTypeList.get(k).getDocumentTypeId());
431                 List<DocumentRouteHeaderValue> documentList= ( List<DocumentRouteHeaderValue>)  service.findMatching(DocumentRouteHeaderValue.class,searchCriteria);
432                 OleLicenseRequestBo licenseRequestBo ;
433                 for(int i=0;i<documentList.size();i++){
434                     add = false;
435                     LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentList.get(i).getDocContent());
436                     Date createDateInBo=documentList.get(i).getCreateDate();
437                     //String strCreateDateInBo=dateFormat.format(createDateInBo);
438                     //String lastModifiedDateInBo = dateFormat.format(documentList.get(i).getDateModified());
439                     boolean isValidCreateDate = false;
440                     boolean  isValidModifiedDate = false;
441                     boolean  isDateBlank = false;
442                     if (createdFromDate.isEmpty() && createdToDate.isEmpty() && lastModifiedDateFrom.isEmpty() && lastModifiedDateTo.isEmpty()){
443                         isDateBlank=true;
444                     }
445                     isValidCreateDate = validateDate(createDateInBo,createdFromDate,createdToDate);
446                     isValidModifiedDate = validateDate(documentList.get(i).getDateModified(),lastModifiedDateFrom,lastModifiedDateTo);
447                     if(lastModifiedDateSearchType.equalsIgnoreCase("true")){
448                         isValidDate =  isValidCreateDate && isValidModifiedDate;
449                     }
450                     else {
451                         isValidDate = (isValidCreateDate && !(createdFromDate .isEmpty() && createdToDate.isEmpty()))||
452                                 (isValidModifiedDate && !(lastModifiedDateFrom.isEmpty() && lastModifiedDateTo.isEmpty()));
453                     }
454                     if(bo!=null && (isValidDate || isDateBlank)){
455                         licenseRequestBo =  (OleLicenseRequestBo) bo.getDataObject();
456                         Map<String, String> tempId = new HashMap<String, String>();
457                         tempId.put(OLEConstants.DOC_NUM, licenseRequestBo.geteResourceDocNumber());
458                         OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, tempId);
459                         if (oleeResourceRecordDocument != null) {
460                             licenseRequestBo.seteResourceName(oleeResourceRecordDocument.getTitle());
461                         }
462                         if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.ASSIGNEE))) || (licenseRequestBo.getAssignee()!=null&&!licenseRequestBo.getAssignee().isEmpty()
463                                 && licenseRequestBo.getAssignee().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.ASSIGNEE)))){
464                             if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.LOCATION_ID))) || (licenseRequestBo.getLocationId()!=null&&!licenseRequestBo.getLocationId().isEmpty()
465                                     &&licenseRequestBo.getLocationId().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.LOCATION_ID)))){
466                                 if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.STATUS_CODE))) || (licenseRequestBo.getLicenseRequestStatusCode()!=null
467                                         && !licenseRequestBo.getLicenseRequestStatusCode().isEmpty()&&licenseRequestBo.getOleLicenseRequestStatus().getName().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.STATUS_CODE)))){
468                                     if(("".equals(criteria.get(OLEConstants.OleLicenseRequest.LICENSE_REQUEST_TYPE_ID))) || (licenseRequestBo.getLicenseRequestTypeId()!=null
469                                             && !licenseRequestBo.getLicenseRequestTypeId().isEmpty()&&licenseRequestBo.getLicenseRequestTypeId().equalsIgnoreCase(criteria.get(OLEConstants.OleLicenseRequest.LICENSE_REQUEST_TYPE_ID)))){
470                                         if (licenseRequestBo.geteResourceName() != null && !licenseRequestBo.geteResourceName().isEmpty()) {
471                                             DocumentSearchCriteria.Builder docSearchCriteria = DocumentSearchCriteria.Builder.create();
472                                             docSearchCriteria.setDocumentTypeName(OLEConstants.OLEEResourceRecord.OLE_ERS_DOC);
473                                             Map<String, List<String>> eResNameMap = new HashMap<>();
474                                             List<String> eResNameList = new ArrayList<>();
475                                             if (!"".equals(criteria.get(OLEConstants.OleLicenseRequest.E_RES_NAME)))
476                                                 eResNameList.add(criteria.get(OLEConstants.OleLicenseRequest.E_RES_NAME));
477                                             eResNameMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_TITLE, eResNameList);
478                                             List<OLEEResourceRecordDocument> oleeResourceRecordDocumentList = getOleEResourceSearchService().findMatching(eResNameMap, docSearchCriteria);
479                                             for (OLEEResourceRecordDocument oleEResourceRecordDocument : oleeResourceRecordDocumentList) {
480                                                 if (oleEResourceRecordDocument.getTitle().equals(licenseRequestBo.geteResourceName())) {
481                                                     add = true;
482                                                 }
483                                             }
484                                         }
485                                     }
486                                 }
487                             }
488                         }
489                         if(add){
490                             OleLicenseRequestBo oleLicenseRequestBo=getOleLicenseRequestBoWithDocNumb(licenseRequestBo);
491                             List<OleLicenseRequestItemTitle> itemTitleList = oleLicenseRequestBo.getOleLicenseRequestItemTitles();
492                             List<OleLicenseRequestItemTitle> newItemTitleList = new ArrayList<OleLicenseRequestItemTitle>();
493                             if(itemTitleList!=null && itemTitleList.size()>0 ){
494                                 OleLicenseRequestBo newLicenseRequestBo;
495                                 for(int j=0;j<itemTitleList.size();j++){
496                                     newLicenseRequestBo = (OleLicenseRequestBo) ObjectUtils.deepCopy(licenseRequestBo);
497                                     newLicenseRequestBo.setOleLicenseRequestItemTitles(null);
498                                     newItemTitleList.add(itemTitleList.get(j));
499                                     newLicenseRequestBo.setOleLicenseRequestItemTitles(newItemTitleList);
500                                     newLicenseRequestBo.setDocumentNumber(documentList.get(i).getDocumentContent().getDocumentId());
501                                     newLicenseRequestBo.setCreatedDate(documentList.get(i).getCreateDate());
502                                     newLicenseRequestBo.setCreatedDateFrom(documentList.get(i).getCreateDate());
503                                     /*if(isTitlePresent) {*/
504                                         /*if(uuids.size() > 0 && uuids.contains(itemTitleList.get(j).getItemUUID())) {*/
505                                     //String bibliographicTitle= getDescription(itemTitleList.get(j).getItemUUID());
506                                     //newLicenseRequestBo.setBibliographicTitle(bibliographicTitle);
507                                     if (newLicenseRequestBo.getLocationId() != null && !newLicenseRequestBo.getLocationId().isEmpty()) {
508                                         newLicenseRequestBo.setOleLicenseRequestLocation(getLicenseRequestLocation(newLicenseRequestBo.getLocationId()));
509                                     }
510                                     if (newLicenseRequestBo.getLicenseRequestTypeId() != null && !newLicenseRequestBo.getLicenseRequestTypeId().isEmpty()) {
511                                         newLicenseRequestBo.setOleLicenseRequestType(getLicenseRequestType(newLicenseRequestBo.getLicenseRequestTypeId()));
512                                     }
513                                     licenseRequestList.add(newLicenseRequestBo);
514                                         /*}*/
515                                     /*}*/
516                                     /*else {*/
517                                     //String bibliographicTitle= getDescription(itemTitleList.get(j).getItemUUID());
518                                     //newLicenseRequestBo.setBibliographicTitle(bibliographicTitle);
519                                         /*if (newLicenseRequestBo.getLocationId() != null && !newLicenseRequestBo.getLocationId().isEmpty()) {
520                                             newLicenseRequestBo.setOleLicenseRequestLocation(getLicenseRequestLocation(newLicenseRequestBo.getLocationId()));
521                                         }
522                                         if (newLicenseRequestBo.getLicenseRequestTypeId() != null && !newLicenseRequestBo.getLicenseRequestTypeId().isEmpty()) {
523                                             newLicenseRequestBo.setOleLicenseRequestType(getLicenseRequestType(newLicenseRequestBo.getLicenseRequestTypeId()));
524                                         }
525                                         licenseRequestList.add(newLicenseRequestBo);*/
526                                    /* }*/
527                                 }
528                             }
529                             else /*if (!isTitlePresent)*/{
530                                 licenseRequestBo.setDocumentNumber(documentList.get(i).getDocumentContent().getDocumentId());
531                                 licenseRequestBo.setCreatedDate(documentList.get(i).getCreateDate());
532                                 licenseRequestBo.setCreatedDateFrom(documentList.get(i).getCreateDate());
533                                 licenseRequestList.add(licenseRequestBo);
534                             }
535 
536                         }
537                     }  }
538             }
539         }catch  (ParseException e) {
540             e.printStackTrace();
541         }
542         return licenseRequestList;
543     }
544 
545     private OleLicenseRequestLocation getLicenseRequestLocation(String id) {
546         OleLicenseRequestLocation oleLicenseRequestLocation = KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleLicenseRequestLocation.class,
547                 id);
548         return oleLicenseRequestLocation;
549     }
550 
551     private OleLicenseRequestType getLicenseRequestType (String licenseRequestTypeId) {
552         OleLicenseRequestType oleLicenseRequestType = KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleLicenseRequestType.class, licenseRequestTypeId);
553         return oleLicenseRequestType;
554     }
555 
556 
557     public OleLicenseRequestBo getLicenseRequestFromDocumentContent(String documentContent) {
558         OleLicenseRequestBo oleLicenseRequestBo = null;
559         LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentContent);
560         oleLicenseRequestBo =  (OleLicenseRequestBo) bo.getDataObject();
561         return oleLicenseRequestBo;
562     }
563     /**
564      * This method returns the license request documentNum for the given requisition documet number
565      * @param reqDocNum
566      * @return  licenseRequestDocNum
567      */
568    /* public String getLicenseRequestByRequisitionDocNum(String reqDocNum) {
569         BusinessObjectService service = KRADServiceLocator.getBusinessObjectService();
570         Map<String,String> documentCriteria = new HashMap<String,String>();
571         documentCriteria.put(OLEConstants.NAME,OLEConstants.OleLicenseRequest.LICENSE_REQUEST_DOC_TYPE);
572         List<DocumentType> documentTypeList= (List<DocumentType>) service.findMatching(DocumentType.class,documentCriteria);
573         Map<String,String> searchCriteria = new HashMap<String,String>();
574         for(int i=0;i<documentTypeList.size();i++){
575             searchCriteria.put(OLEConstants.DOC_TYP_ID,documentTypeList.get(i).getDocumentTypeId());
576         }
577         List<DocumentRouteHeaderValue> documentList= ( List<DocumentRouteHeaderValue>)  service.findMatching(DocumentRouteHeaderValue.class,searchCriteria);
578         String licenseRequestDocNum = "";
579         OleLicenseRequestBo licenseRequestBo ;
580         for(int i=0;i<documentList.size();i++){
581             LicenceRoutingRuleDelegationMaintainable bo = (LicenceRoutingRuleDelegationMaintainable) getDataObjectFromXML(documentList.get(i).getDocContent());
582 
583             if(bo!=null){
584                 licenseRequestBo =  (OleLicenseRequestBo) bo.getDataObject();
585                 if(("".equals(reqDocNum)) || (licenseRequestBo.getRequisitionDocNumber()!=null&&!licenseRequestBo.getRequisitionDocNumber().isEmpty()
586                         && licenseRequestBo.getRequisitionDocNumber().equals(reqDocNum))){
587                     licenseRequestDocNum = licenseRequestBo.getDocumentNumber();
588                 }
589             }
590         }
591         return licenseRequestDocNum;
592     }*/
593 
594     /**
595      * This method converts the xml content into bussinessObjectBase class
596      * @param xmlDocumentContents
597      * @return   businessObject
598      */
599     private Object getDataObjectFromXML(String xmlDocumentContents) {
600         if(xmlDocumentContents!=null || !"".equals(xmlDocumentContents) || !xmlDocumentContents.isEmpty()) {
601             String maintXml = StringUtils.substringBetween(xmlDocumentContents, OLEConstants.OleLicenseRequest.START_TAG,
602                     OLEConstants.OleLicenseRequest.END_TAG);
603             Object businessObject =null;
604             if(maintXml!=null){
605                 maintXml = maintXml.substring(2,maintXml.length());
606                 businessObject = KRADServiceLocator.getXmlObjectSerializerService().fromXml(maintXml);
607             }
608             return businessObject;                                                                            }
609         else{
610             return null;
611         }
612     }
613 
614     /**
615      * This method returns the bibliographic title for the given uuid
616      * @param bibUuid
617      * @return   itemDescription
618      */
619     private String getDescription(String bibUuid){
620         String itemDescription=null;
621         String title=null;
622         String author=null;
623         String publisher=null;
624         String isbn=null;
625         try{
626             List<HashMap<String, Object>> bibDocumentList= QueryServiceImpl.getInstance().retriveResults("id:"+bibUuid);
627             HashMap<String, Object> bibValues = bibDocumentList.get(0);
628 
629             ArrayList<String> titleList= (ArrayList<String>) bibValues.get("Title_display");
630             ArrayList<String> authorList= (ArrayList<String>) bibValues.get("Author_display");
631             ArrayList<String> publisherList= (ArrayList<String>) bibValues.get("Publisher_display");
632             ArrayList<String> isbnList= (ArrayList<String>) bibValues.get("ISBN_display");
633             if(titleList!=null){
634                 title=titleList.get(0);
635             }
636             if(authorList!=null){
637                 author=authorList.get(0);
638             }
639             if(publisherList!=null){
640                 publisher=publisherList.get(0);}
641             if(isbnList!=null) {
642                 isbn=isbnList.get(0);
643             }
644             itemDescription  = (( title!=null && ! title.isEmpty()) ? title+"," : "");
645             /*+
646       (( author!=null&&!author.isEmpty())? author+"," : "") +
647       ((publisher!=null&&!publisher.isEmpty()) ?   publisher+"," : "") +
648       ((isbn!=null&&!isbn.isEmpty() ) ?  isbn+"," : "");*/
649             if(itemDescription != null && !(itemDescription.equals(""))){
650                 itemDescription = itemDescription.lastIndexOf(",") < 0 ? itemDescription :
651                         itemDescription.substring(0, itemDescription.lastIndexOf(","));
652             }
653 
654         }catch(Exception e){
655             e.printStackTrace();
656         }
657         return itemDescription;
658     }
659 
660 
661     /**
662      * This method returns the uuids for the given bibliographic Title
663      * @param title
664      * @return   uuids
665      */
666     private List<String> getUUIDs(String title){
667         StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
668         List<String> uuids = new ArrayList<String>();
669         try{
670             List<HashMap<String, Object>> bibDocumentList= QueryServiceImpl.getInstance().retriveResults(queryString+ stringEscapeUtils.escapeXml(title));
671             if(bibDocumentList.size() > 0) {
672                 Iterator listIterator = bibDocumentList.iterator();
673                 while(listIterator.hasNext()) {
674                     Map results = (Map)listIterator.next();
675                     uuids.add((String)results.get("uniqueId"));
676                 }
677             }
678         }catch(Exception e){
679             e.printStackTrace();
680         }
681         return uuids;
682     }
683     private ConfigurationService getKualiConfigurationService() {
684         return GlobalResourceLoader.getService("kualiConfigurationService");
685     }
686 
687     /**
688      * This method will delete the Agreement Document Content from the docstore
689      * @param metadata
690      * * @return boolean
691      */
692     public boolean deleteAgreementDocument(OleAgreementDocumentMetadata metadata) {
693         try{
694             getDocstoreClientLocator().getDocstoreClient().deleteLicense(metadata.getAgreementUUID());
695             return true;
696         }
697         catch (Exception e) {
698             return false;
699         }
700 
701     }
702 
703     /**
704      * This method will generate the request xml for the delete operation.
705      * @param metadata
706      * @return  rollBackXml
707      */
708 //    private String buildDeleteAgreementRequestXml(OleAgreementDocumentMetadata metadata){
709 //        ResponseHandler responseHandler = new ResponseHandler();
710 //        RequestHandler requestHandler = new RequestHandler();
711 //        Request request = new Request();
712 //        request.setUser("khuntley");
713 //        request.setOperation("delete");
714 //        RequestDocument requestDocument = new RequestDocument();
715 //        requestDocument.setId("1");
716 //        requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
717 //        requestDocument.setType("license");
718 //        requestDocument.setUuid(metadata.getAgreementUUID());
719 //        String agreementFormat = metadata.getAgreementFileName().substring(metadata.getAgreementFileName().indexOf(".")+1
720 //                ,metadata.getAgreementFileName().length());
721 //        if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
722 //            requestDocument.setFormat(agreementFormat);
723 //        }
724 //        else {
725 //            requestDocument.setFormat("doc");
726 //        }
727 //        //requestDocument.setFormat(agreementFormat);
728 //        List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
729 //        requestDocuments.add(requestDocument);
730 //        request.setRequestDocuments(requestDocuments);
731 //        String rollBackXml = requestHandler.toXML(request);
732 //        return rollBackXml;
733 //    }
734     @Override
735     public boolean validateDate (Date documentDate, String fromDate, String toDate)throws Exception{
736         boolean isValidDate = false ;
737         String dateToCompare = "";
738         if(documentDate != null ) {
739             dateToCompare=dateFormat.format(documentDate);
740         }
741         try {
742             if (((toDate == null || toDate.isEmpty()) && fromDate != null && !fromDate.isEmpty())
743                     && (dateToCompare.equals(fromDate) || (documentDate != null && documentDate.after(dateFormat.parse(fromDate))))) {
744                 isValidDate = true;
745             }
746             else if ( ((fromDate == null || fromDate.isEmpty()) && toDate != null && !toDate.isEmpty())
747                     && (dateToCompare.equals(toDate) || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))) {
748                 isValidDate = true;
749             }
750             else if (((fromDate == null || fromDate.isEmpty() ) && ((toDate == null) || toDate.isEmpty())) ||
751                     ((fromDate != null && (dateToCompare.equals(fromDate) || (documentDate != null && documentDate.after(dateFormat.parse(fromDate))))) &&
752                             (toDate != null && (dateToCompare.equals(toDate) || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))))) {
753                 isValidDate = true;
754             }
755         }
756         catch (Exception e) {
757             LOG.error("Error while comparing the date" + e.getMessage());
758             throw new RuntimeException(e);
759         }
760         return isValidDate;
761 
762     }
763     public OleLicenseRequestBo getOleLicenseRequestBoWithDocNumb(OleLicenseRequestBo oleLicenseRequestBo){
764         Map<String,String> map=new HashMap<>();
765         map.put(OLEConstants.OLEEResourceRecord.ERESOURCE_DOC_NUMBER,oleLicenseRequestBo.geteResourceDocNumber());
766         return KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleLicenseRequestBo.class,map);
767     }
768 }