1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  package org.kuali.ole.select.service.impl;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.incubator.SolrRequestReponseHandler;
20  import org.kuali.ole.docstore.common.document.Bib;
21  import org.kuali.ole.docstore.model.bo.OleDocument;
22  import org.kuali.ole.docstore.model.bo.WorkBibDocument;
23  import org.kuali.ole.docstore.model.bo.WorkInstanceDocument;
24  import org.kuali.ole.docstore.model.xmlpojo.ingest.*;
25  import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler;
26  import org.kuali.ole.select.OleSelectConstant;
27  import org.kuali.ole.select.businessobject.BibInfoBean;
28  import org.kuali.ole.select.businessobject.DocInfoBean;
29  import org.kuali.ole.select.service.*;
30  import org.kuali.ole.sys.OLEConstants;
31  import org.kuali.ole.sys.context.SpringContext;
32  import org.kuali.rice.core.api.config.property.ConfigurationService;
33  import org.kuali.rice.krad.util.GlobalVariables;
34  import org.springframework.core.io.ClassPathResource;
35  import org.w3c.dom.Document;
36  import org.w3c.dom.Node;
37  import org.w3c.dom.NodeList;
38  
39  import javax.xml.parsers.DocumentBuilder;
40  import javax.xml.parsers.DocumentBuilderFactory;
41  import javax.xml.xpath.XPath;
42  import javax.xml.xpath.XPathConstants;
43  import javax.xml.xpath.XPathExpression;
44  import javax.xml.xpath.XPathFactory;
45  import java.io.File;
46  import java.io.IOException;
47  import java.net.URLEncoder;
48  import java.text.DateFormat;
49  import java.text.SimpleDateFormat;
50  import java.util.*;
51  import org.kuali.ole.docstore.common.client.DocstoreClient;
52  
53  public class BibInfoServiceImpl implements BibInfoService {
54  
55      
56      private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BibInfoServiceImpl.class);
57  
58      protected ConfigurationService configurationService;
59      protected WebClientService webClientService;
60      protected BibMarcXMLGenerationService bibMarcXMLGenerationService;
61      protected ItemMarcXMLGenerationService itemMarcXMLGenerationService;
62      protected FileProcessingService fileProcessingService;
63      private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
64  
65      private DocstoreClient docstoreClient;
66  
67      protected BibInfoServiceImpl() {
68  
69      }
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84      @Override
85      public String save(BibInfoBean bibInfoBean) throws Exception {
86          if (LOG.isDebugEnabled()) {
87              LOG.debug("inside BibInfoService save..............");
88          }
89          BibInfoBeanToBibXML bibInfoBeanToBibXML = new BibInfoBeanToBibXML();
90          bibInfoBeanToBibXML.exportToXMLFile(bibInfoBean);
91          return bibInfoBean.getTitleId();
92      }
93  
94  
95  
96  
97  
98  
99  
100 
101 
102 
103 
104 
105 
106 
107     @Override
108     public String save(BibInfoBean bibInfoBean, HashMap dataMap) throws Exception {
109         LOG.debug("inside BibInfoService save(BibInfoBean bibInfoBean, HashMap dataMap)");
110         String xmlString = generateXMLStringForIngest(bibInfoBean, dataMap);
111         String userName;
112         
113         if (GlobalVariables.getUserSession() != null) {
114             userName = GlobalVariables.getUserSession().getPrincipalName();
115         } else {
116             userName = configurationService.getPropertyValueAsString("userName");
117         }
118         xmlString = xmlString.concat("&userId=" + userName + "&userAction=" + bibInfoBean.getRequestSource());
119         String encodedXMLString = URLEncoder.encode(xmlString, "UTF-8");
120         dataMap.put(OleSelectConstant.DOCSTORE_REQUEST_XMLSTRING, encodedXMLString);
121         if (LOG.isDebugEnabled()) {
122             LOG.debug("XMLString ------------->>>>>> " + xmlString);
123         }
124         String response = getDocStoreResponse(dataMap);
125         String responseElement = getDocStoreResponseElement(response, dataMap);
126         return responseElement;
127     }
128 
129     @Override
130     public List<BibInfoBean> getUUID(List<BibInfoBean> bibInfoBeanList, HashMap dataMap) throws Exception {
131         LOG.debug("inside BibInfoService save(BibInfoBean bibInfoBean, HashMap dataMap)");
132         String xmlString = generateXMLStringForIngest(bibInfoBeanList, dataMap);
133         String userName;
134         if (GlobalVariables.getUserSession() != null) {
135             userName = GlobalVariables.getUserSession().getPrincipalName();
136         } else {
137             userName = configurationService.getPropertyValueAsString("userName");
138         }
139         xmlString = xmlString.concat("&userId=" + userName + "&userAction=" + OleSelectConstant.REQUEST_SRC_TYPE_BATCHINGEST);
140         String encodedXMLString = URLEncoder.encode(xmlString, "UTF-8");
141         dataMap.put(OleSelectConstant.DOCSTORE_REQUEST_XMLSTRING, encodedXMLString);
142         if (LOG.isDebugEnabled()) {
143             LOG.debug("XMLString ------------->>>>>> " + xmlString);
144         }
145         String response = getDocStoreResponse(dataMap);
146         if (LOG.isDebugEnabled()) {
147             LOG.debug("responseXMLString ------------->>>>>> " + response);
148         }
149         bibInfoBeanList = getDocStoreResponseElement(response, dataMap, bibInfoBeanList);
150         return bibInfoBeanList;
151     }
152 
153     @Override
154     public String getDocStoreResponse(HashMap<String, String> dataMap) throws Exception {
155         String urlString = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_URL_KEY_FOR_POS);
156         
157         String contentType = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_CONTENT_TYPE_KEY);
158         if (LOG.isDebugEnabled()) {
159             LOG.debug("docstoreurl-------->" + urlString);
160         }
161         String data = getFormData(dataMap);
162         String response = webClientService.sendRequest(urlString, contentType, data);
163         return response;
164     }
165 
166     private String getDocStoreResponseElement(String response, HashMap<String, String> dataMap) throws Exception {
167         String responseElement = webClientService.getDataFromResponseXMLForDocStore(response, dataMap);
168         return responseElement;
169     }
170 
171     private List<BibInfoBean> getDocStoreResponseElement(String response, HashMap<String, String> dataMap, List<BibInfoBean> bibInfoBeanList) throws Exception {
172         bibInfoBeanList = webClientService.getUUIDFromResponseXMLForDocStore(response, dataMap, bibInfoBeanList);
173         return bibInfoBeanList;
174     }
175 
176     @Override
177     public String getDocSearchResponse(BibInfoBean bibInfoBean) throws Exception {
178         String urlString = configurationService.getPropertyValueAsString(OLEConstants.DOCSEARCH_URL_KEY);
179         if (LOG.isDebugEnabled()) {
180             LOG.debug("docstoreurl-------->" + urlString);
181         }
182         String contentType = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_CONTENT_TYPE_KEY);
183         String query = buildDocSearchQuery(bibInfoBean);
184         String response = webClientService.sendRequest(urlString, contentType, query);
185         return response;
186     }
187 
188     @Override
189     public String convertBibInfoBeanToMarcXMLString(BibInfoBean bibInfoBean, HashMap<String, String> dataMap) throws Exception {
190         String xmlString = bibMarcXMLGenerationService.getMarcXML(bibInfoBean, dataMap);
191         
192         return xmlString;
193     }
194 
195     @Override
196     public String generateItemMarcXMLString(BibInfoBean bibInfoBean, HashMap<String, String> dataMap) throws Exception {
197         String xmlString = itemMarcXMLGenerationService.getMarcXML(bibInfoBean, dataMap);
198         
199         return xmlString;
200     }
201 
202     public String generateInstanceMarcXMLString(BibInfoBean bibInfoBean, HashMap<String, String> dataMap) throws Exception {
203         String xmlString = OLEConstants.INSTANCE_MARC_XML_STRING;
204         return xmlString;
205     }
206 
207     @Override
208     public String generateXMLStringForIngest(BibInfoBean bibInfoBean, HashMap<String, String> dataMap) throws Exception {
209         String bibMarcXMLString;
210         String itemMarcXMLString;
211         if (!dataMap.containsKey(OleSelectConstant.BIB_MARC_XMLSTRING)) {
212             bibMarcXMLString = convertBibInfoBeanToMarcXMLString(bibInfoBean, dataMap);
213             dataMap.put(OleSelectConstant.BIB_MARC_XMLSTRING, bibMarcXMLString);
214         }
215         if (!dataMap.containsKey(OleSelectConstant.ITEM_MARC_XMLSTRING)) {
216             itemMarcXMLString = generateItemMarcXMLString(bibInfoBean, dataMap);
217             dataMap.put(OleSelectConstant.ITEM_MARC_XMLSTRING, itemMarcXMLString);
218         }
219         if (!dataMap.containsKey(OleSelectConstant.INSTANCE_MARC_XMLSTRING)) {
220             itemMarcXMLString = generateInstanceMarcXMLString(bibInfoBean, dataMap);
221             dataMap.put(OleSelectConstant.INSTANCE_MARC_XMLSTRING, itemMarcXMLString);
222         }
223         String requestXMLString = generateRequestXMLString(bibInfoBean, dataMap);
224         
225         if (LOG.isDebugEnabled()) {
226             LOG.debug("requestXMLString ------------->" + requestXMLString);
227         }
228         return requestXMLString;
229     }
230 
231     public String generateXMLStringForIngest(List<BibInfoBean> bibInfoBeanList, HashMap<String, String> dataMap) throws Exception {
232         String requestXMLString = generateRequestXMLString(bibInfoBeanList, dataMap);
233         
234         if (LOG.isDebugEnabled()) {
235             LOG.debug("requestXMLString ------------->" + requestXMLString);
236         }
237         return requestXMLString;
238     }
239 
240     private String replaceStringWithSymbols(String requestXMLString) throws Exception {
241         requestXMLString = requestXMLString.replaceAll("<", "<");
242         requestXMLString = requestXMLString.replaceAll(">", ">");
243         requestXMLString = requestXMLString.replaceAll(""", "\"");
244         requestXMLString = requestXMLString.replaceAll("'", "\'");
245         
246         return requestXMLString;
247     }
248 
249     @Override
250     public String generateRequestXMLString(BibInfoBean bibInfoBean, HashMap<String, String> dataMap) throws Exception {
251         Request requestObject = new Request();
252         int i = 0;
253         String bibId = String.valueOf(i++);
254         String itemId = String.valueOf(i++);
255         if (GlobalVariables.getUserSession() != null) {
256             requestObject.setUser(GlobalVariables.getUserSession().getPrincipalName());
257         } else {
258             requestObject.setUser(configurationService.getPropertyValueAsString("userName"));
259         }
260         requestObject.setOperation(OleSelectConstant.DOCSTORE_OPERATION_INGEST);
261         RequestDocument requestDocument = new RequestDocument();
262         requestDocument.setId(bibId);
263         requestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
264         requestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_BIB);
265         requestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_MARC);
266         requestDocument.setContent(new Content(dataMap.get(OleSelectConstant.BIB_MARC_XMLSTRING)));
267 
268         AdditionalAttributes additionalAttributes = new AdditionalAttributes();
269         additionalAttributes.setDateEntered(String.valueOf(dateFormat.format(new Date())));
270         additionalAttributes.setLastUpdated(String.valueOf(dateFormat.format(new Date())));
271         additionalAttributes.setFastAddFlag("true");
272         additionalAttributes.setSupressFromPublic("false");
273         additionalAttributes.setHarvestable("false");
274         additionalAttributes.setStatus("n");
275         requestDocument.setAdditionalAttributes(additionalAttributes);
276 
277         RequestDocument linkedRequestDocument = new RequestDocument();
278         linkedRequestDocument.setId(itemId);
279         linkedRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
280         linkedRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_INSTANCE);
281         linkedRequestDocument.setContent(new Content(dataMap.get(OleSelectConstant.INSTANCE_MARC_XMLSTRING)));
282         linkedRequestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_OLEML);
283 
284         ArrayList<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
285         linkedRequestDocuments.add(linkedRequestDocument);
286 
287         requestDocument.setLinkedRequestDocuments(linkedRequestDocuments);
288 
289 
290         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
291         requestDocuments.add(requestDocument);
292         removeElements(dataMap);
293         requestObject.setRequestDocuments(requestDocuments);
294         RequestHandler requestHandler = new RequestHandler();
295         String requestXMLString = requestHandler.toXML(requestObject);
296         return requestXMLString;
297     }
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
348     public String generateRequestXMLString(List<BibInfoBean> bibInfoBeanList, HashMap<String, String> dataMap) throws Exception {
349         Request requestObject = new Request();
350         ArrayList<String> bibMarcXMLStringList = new ArrayList<String>();
351         ArrayList<String> itemMarcXMLStringList = new ArrayList<String>();
352         ArrayList<String> instanceMarcXMLStringList = new ArrayList<String>();
353         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
354         ArrayList<LinkInfo> links = new ArrayList<LinkInfo>();
355         Iterator bibInfoBeanListIterator = bibInfoBeanList.iterator();
356         RequestDocument docStoreDocument;
357         int i = 0;
358         String bibId;
359         String itemId;
360         if (GlobalVariables.getUserSession() != null) {
361             requestObject.setUser(GlobalVariables.getUserSession().getPrincipalName());
362         } else {
363             requestObject.setUser(configurationService.getPropertyValueAsString("userName"));
364         }
365         requestObject.setOperation(OleSelectConstant.DOCSTORE_OPERATION_BATCHINGEST);
366         while (bibInfoBeanListIterator.hasNext()) {
367             BibInfoBean bibInfoBean = (BibInfoBean) bibInfoBeanListIterator.next();
368             String bibMarcXMLString = convertBibInfoBeanToMarcXMLString(bibInfoBean, dataMap);
369             
370             String instanceXMLString = generateInstanceMarcXMLString(bibInfoBean, dataMap);
371 
372             bibMarcXMLStringList.add(bibMarcXMLString);
373             
374             instanceMarcXMLStringList.add(instanceXMLString);
375 
376         }
377         Iterator bibMarcXMLStringListIterator = bibMarcXMLStringList.iterator();
378         Iterator itemMarcXMLStringListIterator = itemMarcXMLStringList.iterator();
379         int idCounter = 0;
380         bibInfoBeanListIterator = bibInfoBeanList.iterator();
381         while (bibMarcXMLStringListIterator.hasNext()) {
382             docStoreDocument = getBibDocStoreDocument(bibMarcXMLStringListIterator.next().toString(), String.valueOf(idCounter));
383             requestDocuments.add(docStoreDocument);
384             BibInfoBean bibInfoBean = (BibInfoBean) bibInfoBeanListIterator.next();
385             bibInfoBean.setDocStoreIngestionId(String.valueOf(idCounter));
386             idCounter++;
387         }
388         
389 
390 
391 
392 
393 
394 
395 
396         requestObject.setRequestDocuments(requestDocuments);
397         links = getLinkInfo(bibInfoBeanList);
398         
399         RequestHandler requestHandler = new RequestHandler();
400         String requestXMLString = requestHandler.toXML(requestObject);
401         return requestXMLString;
402     }
403 
404 
405     private RequestDocument getBibDocStoreDocument(String xmlString, String id) throws Exception {
406         RequestDocument bibRequestDocument = new RequestDocument();
407         int itemId = Integer.valueOf(id);
408         bibRequestDocument.setId(id);
409         
410 
411 
412 
413         bibRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
414         bibRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_BIB);
415         bibRequestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_MARC);
416         bibRequestDocument.setContent(new Content(xmlString));
417         AdditionalAttributes additionalAttributes = new AdditionalAttributes();
418         additionalAttributes.setDateEntered(String.valueOf(dateFormat.format(new Date())));
419         additionalAttributes.setLastUpdated(String.valueOf(dateFormat.format(new Date())));
420         additionalAttributes.setFastAddFlag("true");
421         additionalAttributes.setSupressFromPublic("false");
422         additionalAttributes.setHarvestable("false");
423         additionalAttributes.setStatus("n");
424         bibRequestDocument.setAdditionalAttributes(additionalAttributes);
425 
426         RequestDocument linkedRequestDocument = new RequestDocument();
427         linkedRequestDocument.setId(String.valueOf(++itemId));
428         linkedRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
429         linkedRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_INSTANCE);
430         linkedRequestDocument.setContent(new Content(OLEConstants.INSTANCE_MARC_XML_STRING));
431         linkedRequestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_OLEML);
432 
433         ArrayList<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
434         linkedRequestDocuments.add(linkedRequestDocument);
435 
436         bibRequestDocument.setLinkedRequestDocuments(linkedRequestDocuments);
437         return bibRequestDocument;
438     }
439 
440     private RequestDocument getItemDocStoreDocument(String xmlString, String id) throws Exception {
441         RequestDocument bibRequestDocument = new RequestDocument();
442         int itemId = Integer.valueOf(id);
443         bibRequestDocument.setId(id);
444         bibRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
445         bibRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_BIB);
446         bibRequestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_MARC);
447         bibRequestDocument.setContent(new Content(xmlString));
448         AdditionalAttributes additionalAttributes = new AdditionalAttributes();
449         additionalAttributes.setDateEntered(String.valueOf(dateFormat.format(new Date())));
450         additionalAttributes.setLastUpdated(String.valueOf(dateFormat.format(new Date())));
451         additionalAttributes.setFastAddFlag("true");
452         additionalAttributes.setSupressFromPublic("false");
453         additionalAttributes.setHarvestable("false");
454         additionalAttributes.setStatus("n");
455         bibRequestDocument.setAdditionalAttributes(additionalAttributes);
456 
457         RequestDocument linkedRequestDocument = new RequestDocument();
458         linkedRequestDocument.setId(String.valueOf(++itemId));
459         linkedRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
460         linkedRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_INSTANCE);
461         linkedRequestDocument.setContent(new Content(OLEConstants.INSTANCE_MARC_XML_STRING));
462         linkedRequestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_OLEML);
463 
464         ArrayList<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
465         linkedRequestDocuments.add(linkedRequestDocument);
466         return bibRequestDocument;
467     }
468 
469     private ArrayList<LinkInfo> getLinkInfo(List<BibInfoBean> bibInfoBeanList) throws Exception {
470         ArrayList<LinkInfo> links = new ArrayList<LinkInfo>();
471         for (int i = 0; i < bibInfoBeanList.size(); i++) {
472             LinkInfo linkInfo = new LinkInfo();
473             linkInfo.setFrom(String.valueOf(i));
474             linkInfo.setTo(bibInfoBeanList.get(i).getDocStoreIngestionId());
475             links.add(linkInfo);
476         }
477         return links;
478     }
479 
480     private void removeElements(HashMap<String, String> dataMap) throws Exception {
481         dataMap.remove(OleSelectConstant.BIB_MARC_XMLSTRING);
482         dataMap.remove(OleSelectConstant.ITEM_MARC_XMLSTRING);
483     }
484 
485     private Properties loadPropertiesFromClassPath(String classPath) throws Exception {
486         ClassPathResource classPathResource = new ClassPathResource(classPath);
487         Properties properties = new Properties();
488         try {
489             properties.load(classPathResource.getInputStream());
490         } catch (IOException e) {
491             throw new RuntimeException("Invalid class path: " + classPath, e);
492         }
493         return properties;
494     }
495 
496     public String getFormData(HashMap<String, String> dataMap) throws Exception {
497         String postdata = "";
498         if (dataMap.containsKey(OleSelectConstant.IS_BIB_EDIT)) {
499             if (dataMap.get(OleSelectConstant.IS_BIB_EDIT).equalsIgnoreCase("true")) {
500                 postdata = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_POST_DATA_EDIT_KEY);
501                 postdata = postdata + "&uuid=" + dataMap.get(OleSelectConstant.TITLE_ID) + "&fileContent=";
502             } else {
503                 postdata = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_POST_DATA_KEY);
504             }
505         } else {
506             postdata = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_POST_DATA_KEY);
507             postdata = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_POST_DATA_KEY);
508         }
509         postdata = postdata + dataMap.get(OleSelectConstant.DOCSTORE_REQUEST_XMLSTRING);
510         return postdata;
511     }
512 
513     public BibInfoBean retrieve(String titleId) throws Exception {
514         if (LOG.isDebugEnabled()) {
515             LOG.debug("inside BibInfoService retrieve-- titleid----------->" + titleId);
516         }
517         XPathFactory xFactory = XPathFactory.newInstance();
518         XPath xpath = xFactory.newXPath();
519         XPathExpression expr = xpath.compile("//bibData[titleId='" + titleId + "']");
520         Object result = expr.evaluate(parseDocStoreContent(), XPathConstants.NODESET);
521         NodeList nodes = (NodeList) result;
522         BibInfoBean bibInfoBean = new BibInfoBean();
523         if (nodes.getLength() > 0) {
524             Node node = nodes.item(0);
525             NodeList list = node.getChildNodes();
526             for (int i = 0; i < list.getLength(); i++) {
527                 Node tempNode = list.item(i);
528                 convertToBean(bibInfoBean, tempNode.getNodeName(), tempNode.getTextContent());
529                 if (LOG.isDebugEnabled()) {
530                     LOG.debug("node name--------->" + tempNode.getNodeName());
531                     LOG.debug("node text--------->" + tempNode.getTextContent());
532                 }
533             }
534         }
535         return bibInfoBean;
536     }
537 
538     
539     @Override
540     public BibInfoBean retrieveFromDocStore(HashMap<String, String> dataMap) throws Exception {
541         BibInfoBean bibInfoBean = new BibInfoBean();
542         bibInfoBean.setTitleId(dataMap.get(OleSelectConstant.TITLE_ID));
543         bibInfoBean.setDocCategoryType(dataMap.get(OleSelectConstant.DOC_CATEGORY_TYPE));
544         List<BibInfoBean> bibInfoBeanList = searchBibInfo(bibInfoBean);
545         if (LOG.isDebugEnabled()) {
546             LOG.debug("bibInfoBeanList.size----------->" + bibInfoBeanList.size());
547         }
548         for (int i = 0; i < bibInfoBeanList.size(); i++) {
549             if (bibInfoBeanList.get(i).getTitle() != null) {
550                 bibInfoBean = bibInfoBeanList.get(i);
551             }
552             if (LOG.isDebugEnabled()) {
553                 LOG.debug("title---------" + i + "->" + bibInfoBeanList.get(i).getTitle());
554             }
555         }
556 
557 
558 
559 
560 
561 
562 
563 
564         return bibInfoBean;
565     }
566 
567     private void convertToBean(BibInfoBean bibInfoBean, String nodeName, String textContent) {
568         if ("titleId".equals(nodeName)) {
569             bibInfoBean.setTitleId(textContent);
570         } else if ("title".equals(nodeName)) {
571             bibInfoBean.setTitle(textContent);
572         } else if ("author".equals(nodeName)) {
573             bibInfoBean.setAuthor(textContent);
574         } else if ("edition".equals(nodeName)) {
575             bibInfoBean.setEdition(textContent);
576         } else if ("standardNumber".equals(nodeName)) {
577             bibInfoBean.setStandardNumber(textContent);
578         } else if ("publisher".equals(nodeName)) {
579             bibInfoBean.setPublisher(textContent);
580         } else if ("placeOfPublication".equals(nodeName)) {
581             bibInfoBean.setPlaceOfPublication(textContent);
582         } else if ("yearOfPublication".equals(nodeName)) {
583             bibInfoBean.setYearOfPublication(textContent);
584         } else if ("physicalDescription".equals(nodeName)) {
585             bibInfoBean.setPhysicalDescription(textContent);
586         } else if ("format".equals(nodeName)) {
587             bibInfoBean.setFormat(textContent);
588         } else if ("series".equals(nodeName)) {
589             bibInfoBean.setSeries(textContent);
590         } else if ("subjects".equals(nodeName)) {
591             bibInfoBean.setSubjects(textContent);
592         } else if ("price".equals(nodeName)) {
593             bibInfoBean.setPrice(textContent);
594         } else if ("requestorContact".equals(nodeName)) {
595             bibInfoBean.setRequestorContact(textContent);
596         } else if ("requestersNotes".equals(nodeName)) {
597             bibInfoBean.setRequestersNotes(textContent);
598         } else if ("noOfCopies".equals(nodeName)) {
599             bibInfoBean.setNoOfCopies(textContent);
600         } else if ("category".equals(nodeName)) {
601             bibInfoBean.setCategory(textContent);
602         } else if ("requestSource".equals(nodeName)) {
603             bibInfoBean.setRequestSource(textContent);
604         } else if ("selector".equals(nodeName)) {
605             bibInfoBean.setSelector(textContent);
606         } else if ("selectorNotes".equals(nodeName)) {
607             bibInfoBean.setSelectorNotes(textContent);
608         } else if ("startPage".equals(nodeName)) {
609             if (textContent != null && !"".equals(textContent)) {
610                 bibInfoBean.setStartPage(Long.valueOf(textContent));
611             }
612         } else if ("endPage".equals(nodeName)) {
613             if (textContent != null && !"".equals(textContent)) {
614                 bibInfoBean.setEndPage(Long.valueOf(textContent));
615             }
616         }
617     }
618 
619     private List<BibInfoBean> convertToBibInfoBeanList(List<DocInfoBean> docInfoBeanList) throws Exception {
620         List<BibInfoBean> bibInfoBeanList = new ArrayList<BibInfoBean>();
621         for (DocInfoBean docInfoBean : docInfoBeanList) {
622             BibInfoBean bibInfoBean = new BibInfoBean();
623             bibInfoBean.setTitleId(manipulateStringValue(docInfoBean.getTitleId()));
624             bibInfoBean.setTitle(manipulateStringValue(docInfoBean.getTitle_display()));
625             bibInfoBean.setAuthor(manipulateStringValue(docInfoBean.getAuthor_display()));
626             bibInfoBean.setPublisher(manipulateStringValue(docInfoBean.getPublisher_display()));
627             bibInfoBean.setIsbn(manipulateStringValue(docInfoBean.getIsbn_display()));
628             bibInfoBean.setYearOfPublication(manipulateStringValue(docInfoBean.getYearOfPublication()));
629             bibInfoBeanList.add(bibInfoBean);
630         }
631         return bibInfoBeanList;
632     }
633 
634     private String manipulateStringValue(String value) throws Exception {
635         if (value != null) {
636             value = value.trim();
637             value = value.replace("||", "");
638         }
639         return value;
640     }
641 
642     private Document parseDocStoreContent() throws Exception {
643         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
644         factory.setNamespaceAware(true);
645         DocumentBuilder builder = factory.newDocumentBuilder();
646         String externalDirectory = configurationService.getPropertyValueAsString(OLEConstants.STAGING_DIRECTORY_KEY);
647         String fileName = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_FILE_KEY);
648         if (LOG.isInfoEnabled()) {
649             LOG.info("parseDocStoreContent externalDirectory------------>" + externalDirectory);
650             LOG.info("parseDocStoreContent fileName------------>" + fileName);
651         }
652         File file = new File(externalDirectory + fileName);
653         if (!file.exists()) {
654             return null;
655         }
656         Document doc = builder.parse(file.getAbsolutePath());
657         return doc;
658     }
659 
660     @Override
661     public boolean isExists(HashMap map) throws Exception {
662         String externalDirectory = configurationService.getPropertyValueAsString(OLEConstants.STAGING_DIRECTORY_KEY);
663         String fileName = configurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_FILE_KEY);
664         if (LOG.isInfoEnabled()) {
665             LOG.info("Doc Store file Path :" + externalDirectory + fileName);
666         }
667         File file = new File(externalDirectory + fileName);
668         if (!file.exists()) {
669             return false;
670         }
671         if (map.size() == 0) {
672             return false;
673         }
674         XPathFactory xFactory = XPathFactory.newInstance();
675         XPath xpath = xFactory.newXPath();
676         StringBuilder sBuff = new StringBuilder("//bibData");
677         Set set = map.keySet();
678         Iterator<String> setIt = set.iterator();
679         String value = null;
680         while (setIt.hasNext()) {
681             String key = setIt.next();
682             
683             value = (String) map.get(key);
684             if (value.indexOf("\"") != -1) {
685                 sBuff.append("[translate(" + key + ",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')=translate('" + map.get(key) + "','ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')]");
686             } else {
687                 sBuff.append("[translate(" + key + ",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')=translate(\"" + map.get(key) + "\",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')]");
688             }
689         }
690         if (LOG.isDebugEnabled()) {
691             LOG.debug("XPath expr :" + sBuff.toString());
692         }
693         XPathExpression expr = xpath.compile(sBuff.toString());
694         Object result = expr.evaluate(parseDocStoreContent(), XPathConstants.NODESET);
695         NodeList nodeList = (NodeList) result;
696         if (LOG.isDebugEnabled()) {
697             LOG.debug("NodeList length :" + nodeList.getLength());
698         }
699         if (nodeList.getLength() > 0) {
700             return true;
701         } else {
702             return false;
703         }
704     }
705 
706     @Override
707     public boolean isDuplicateRecord(BibInfoBean bibInfoBean) throws Exception {
708         List<DocInfoBean> docInfoBeanList = search(bibInfoBean);
709         for (DocInfoBean docInfoBean : docInfoBeanList) {
710             if (bibInfoBean.getTitle().trim().equalsIgnoreCase(docInfoBean.getTitle_display().trim())) {
711                 return true;
712             }
713         }
714         return false;
715     }
716 
717     @Override
718     public List<BibInfoBean> searchBibInfo(BibInfoBean bibInfoBean) throws Exception {
719         List<DocInfoBean> docInfoBeanList = search(bibInfoBean);
720         List<BibInfoBean> bibInfoBeanList = convertToBibInfoBeanList(docInfoBeanList);
721         return bibInfoBeanList;
722     }
723 
724     public List<DocInfoBean> search(BibInfoBean bibInfoBean) throws Exception {
725         List<DocInfoBean> docInfoBeanList;
726         String title = bibInfoBean.getTitle();
727         if (title != null) {
728             title = title.replaceAll(" ", "%20");
729         }
730         String query = buildDocSearchQuery(bibInfoBean);
731         docInfoBeanList = getResponse(query);
732         if (LOG.isDebugEnabled()) {
733             LOG.debug("docsearch query------>" + query);
734         }
735         return docInfoBeanList;
736     }
737 
738 
739     
740 
741 
742 
743 
744 
745     public String buildDocSearchQuery(Map map) {
746         LOG.debug(" BibInfoServiceImpl.buildDocSearchQuery(Map map) method starts ");
747         StringBuilder query = new StringBuilder();
748         query.append("q=");
749         Set set = map.keySet();
750         Iterator setIterator = set.iterator();
751         String key = null;
752         String value = null;
753         String operator = null;
754         int count = 0;
755         while (setIterator.hasNext()) {
756             key = (String) setIterator.next();
757             
758             value = map.get(key).toString().toLowerCase();
759             if (OleSelectConstant.DocStoreDetails.DOCSTORE_QUERY_KEYS.containsKey(key)) {
760                 if (!OleSelectConstant.DocStoreDetails.DOCSTORE_QUERY_KEYS.get(key).equals(OleSelectConstant.DocStoreDetails.ITEMLINKS_VALUE)) {
761                     if (value.indexOf("\"") == 0 && value.lastIndexOf("\"") == value.length() - 1) {
762                         operator = " AND ";
763                     } else {
764                         operator = " OR ";
765                     }
766                     value = value.replaceAll("[^a-zA-Z 0-9*]+", "");
767                     value = value.replaceAll("\\s+", " ");
768                     value = value.trim().replace(" ", operator);
769                 }
770                 if (count == 0) {
771                     query.append("(" + OleSelectConstant.DocStoreDetails.DOCSTORE_QUERY_KEYS.get(key) + ":(\"" + value + "\"))");
772                 } else {
773                     query.append("AND(" + OleSelectConstant.DocStoreDetails.DOCSTORE_QUERY_KEYS.get(key) + ":(\"" + value + "\"))");
774                 }
775                 count++;
776             }
777         }
778         query.append("&fl=instanceIdentifier,uniqueId,bibIdentifier,Title_display,Author_display,PublicationDate_search,ISBN_display,Publisher_search");
779         int noOfRows = Integer.parseInt(SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSEARCH_LIMIT_KEY));
780         query.append("&rows=" + noOfRows);
781         if (GlobalVariables.getUserSession() != null) {
782             query.append("&userId=" + GlobalVariables.getUserSession().getPerson().getPrincipalName());
783         }
784         if (LOG.isDebugEnabled()) {
785             LOG.debug("docsearch query1------>" + query.toString());
786             LOG.debug(" BibInfoServiceImpl.buildDocSearchQuery(Map map) method ends ");
787         }
788         return query.toString();
789     }
790 
791     private String buildDocSearchQuery(BibInfoBean bibInfoBean) throws Exception {
792         StringBuilder query = new StringBuilder();
793         String id = "instanceIdentifier";
794         if (bibInfoBean.getDocCategoryType() != null) {
795             id = bibInfoBean.getDocCategoryType();
796         }
797         query.append("q=");
798         if (bibInfoBean.getTitleId() != null) {
799             query.append("(" + id + ":" + bibInfoBean.getTitleId() + ")");
800         } else {
801             query.append("(Title_display:" + bibInfoBean.getTitle() + ")");
802             if (bibInfoBean.getAuthor() != null && !StringUtils.isEmpty(bibInfoBean.getAuthor())) {
803                 query.append("AND(Author_display:" + bibInfoBean.getAuthor() + ")");
804             }
805             if (bibInfoBean.getTypeOfStandardNumber() != null) {
806                 if (bibInfoBean.getTypeOfStandardNumber().equalsIgnoreCase("ISBN")) {
807                     query.append("AND(ISBN_display:" + bibInfoBean.getStandardNumber() + ")");
808                 } else if (bibInfoBean.getTypeOfStandardNumber().equalsIgnoreCase("ISSN")) {
809                     query.append("AND(ISSN_display:" + bibInfoBean.getTypeOfStandardNumber() + ")");
810                 }
811             }
812         }
813         query.append("&fl=" + id + ",Title_display,Author_display,YearOfPublication,ISBN_display,Publisher_display");
814         int noOfRows = Integer.parseInt(SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSEARCH_LIMIT_KEY));
815         query.append("&rows=" + noOfRows);
816         
817         if (GlobalVariables.getUserSession() != null) {
818             query.append("&userId=" + GlobalVariables.getUserSession().getPerson().getPrincipalName());
819         }
820         if (LOG.isDebugEnabled()) {
821             LOG.debug("docsearch query------>" + query.toString());
822         }
823         return query.toString();
824     }
825 
826     private List<DocInfoBean> getResponse(String query) {
827         LOG.debug(" BibInfoServiceImpl.getResponse method starts ");
828         List<DocInfoBean> docInfoBeanList = new ArrayList<DocInfoBean>(0);
829         BuildDocInfoBean buildVendorDocInfoBean = new BuildDocInfoBean();
830         docInfoBeanList = buildVendorDocInfoBean.getDocInfoBeanList(query);
831         LOG.debug(" BibInfoServiceImpl.getResponse method ends ");
832         return docInfoBeanList;
833     }
834 
835     
836 
837 
838     @Override
839     public List search(Map map) throws Exception {
840         LOG.debug(" BibInfoServiceImpl.search(Map map) method starts ");
841         List<DocInfoBean> docInfoBeanList;
842         String query = buildDocSearchQuery(map);
843         docInfoBeanList = getResponse(query);
844         LOG.debug(" BibInfoServiceImpl.search(Map map) method ends ");
845         return docInfoBeanList;
846     }
847 
848     @Override
849     public List search(HashMap map, int noOfRecords) throws Exception {
850         List<BibInfoBean> bibInfoBeanList = new ArrayList<BibInfoBean>();
851         XPathFactory xFactory = XPathFactory.newInstance();
852         XPath xpath = xFactory.newXPath();
853         StringBuilder stringExpression = new StringBuilder("//bibData");
854         Set set = map.keySet();
855         Iterator<String> setIt = set.iterator();
856         String value = null;
857         while (setIt.hasNext()) {
858             String key = setIt.next();
859             
860             value = (String) map.get(key);
861             if (value.indexOf("\"") != -1) {
862                 stringExpression.append("[translate(" + key + ",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')=translate('" + map.get(key) + "','ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')]");
863             } else {
864                 stringExpression.append("[translate(" + key + ",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')=translate(\"" + map.get(key) + "\",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')]");
865             }
866         }
867         if (LOG.isDebugEnabled()) {
868             LOG.debug("XPath expr :" + stringExpression.toString());
869         }
870         XPathExpression expr = xpath.compile(stringExpression.toString());
871         Object result = expr.evaluate(parseDocStoreContent(), XPathConstants.NODESET);
872         NodeList nodeList = (NodeList) result;
873 
874         BibInfoBean bibInfoBean;
875         for (int i = 0; i < nodeList.getLength(); i++) {
876             Node node = nodeList.item(i);
877             NodeList list = node.getChildNodes();
878             bibInfoBean = new BibInfoBean();
879             for (int j = 0; j < list.getLength(); j++) {
880                 Node tempNode = list.item(j);
881                 convertToBean(bibInfoBean, tempNode.getNodeName(), tempNode.getTextContent());
882             }
883             bibInfoBeanList.add(bibInfoBean);
884             if (i == (noOfRecords - 1)) {
885                 break;
886             }
887         }
888 
889         return bibInfoBeanList;
890     }
891 
892     @Override
893     public String getTitleIdByMarcXMLFileProcessing(BibInfoBean bibInfoBean, HashMap<String, String> dataMap) throws Exception {
894         String titleId = null;
895         BibInfoBean xmlBibInfoBean = new BibInfoBean();
896         FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
897         String bibMarcXmlString = fileProcessingService.getFileContentAndDeleteFile(dataMap).get(OleSelectConstant.XML_FILE_CONTENT);
898         if (bibMarcXmlString != null) {
899             
900             dataMap.put(OleSelectConstant.BIB_MARC_XMLSTRING, bibMarcXmlString);
901             dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEM);
902             titleId = save(bibInfoBean, dataMap);
903         }
904         return titleId;
905     }
906 
907 
908     public ConfigurationService getConfigurationService() {
909         return configurationService;
910     }
911 
912     public void setConfigurationService(ConfigurationService kualiConfigurationService) {
913         this.configurationService = kualiConfigurationService;
914     }
915 
916     public WebClientService getWebClientService() {
917         return webClientService;
918     }
919 
920     public void setWebClientService(WebClientService webClientService) {
921         this.webClientService = webClientService;
922     }
923 
924     public BibMarcXMLGenerationService getBibMarcXMLGenerationService() {
925         return bibMarcXMLGenerationService;
926     }
927 
928     public void setBibMarcXMLGenerationService(BibMarcXMLGenerationService bibMarcXMLGenerationService) {
929         this.bibMarcXMLGenerationService = bibMarcXMLGenerationService;
930     }
931 
932     public ItemMarcXMLGenerationService getItemMarcXMLGenerationService() {
933         return itemMarcXMLGenerationService;
934     }
935 
936     public void setItemMarcXMLGenerationService(ItemMarcXMLGenerationService itemMarcXMLGenerationService) {
937         this.itemMarcXMLGenerationService = itemMarcXMLGenerationService;
938     }
939 
940     public FileProcessingService getFileProcessingService() {
941         return fileProcessingService;
942     }
943 
944     public void setFileProcessingService(FileProcessingService fileProcessingService) {
945         this.fileProcessingService = fileProcessingService;
946     }
947 
948     @Override
949     public List<DocInfoBean> getResult(List isbnList) throws Exception {
950 
951         List<DocInfoBean> docInfoBeanList = new ArrayList<DocInfoBean>(0);
952         StringBuilder query = new StringBuilder("q=");
953         query.append("(");
954         HashMap titleIdMap = new HashMap();
955         for (int i = 0; i < isbnList.size(); i++) {
956             if (isbnList.get(i) != null && !("".equals(isbnList.get(i)))) {
957                 query.append("(ISBN_display:" + isbnList.get(i) + ")");
958             }
959         }
960         query.append(")");
961         
962         if (GlobalVariables.getUserSession() != null) {
963             query.append("&userId=" + GlobalVariables.getUserSession().getPerson().getPrincipalName());
964         }
965         if (isbnList.size() > 0) {
966             if (LOG.isDebugEnabled()) {
967                 LOG.debug("Doc Store Query :" + query.toString());
968             }
969             docInfoBeanList = getResponse(query.toString());
970         }
971         if (docInfoBeanList.size() > 0) {
972             String maxLimit = docInfoBeanList.get(0).getNoOfRecords();
973             query.append("&fl=uniqueId,bibIdentifier,ISBN_display");
974             query.append("&rows=" + maxLimit);
975             if (LOG.isDebugEnabled()) {
976                 LOG.debug("Doc Store Query :" + query.toString());
977             }
978             if (isbnList.size() > 0) {
979                 docInfoBeanList = getResponse(query.toString());
980             }
981         }
982         return docInfoBeanList;
983     }
984 
985 
986 
987 
988 
989 
990 
991 
992 
993 
994 
995 
996 
997 
998 
999 
1000 
1001 
1002 
1003 
1004 
1005     public BibInfoBean retrieveFromSolrQuery(Map map) throws Exception {
1006         String key = null;
1007         String value = null;
1008         OleDocument oleDocument = new WorkBibDocument();
1009         WorkInstanceDocument workInstance = new WorkInstanceDocument();
1010         Iterator iterator = map.keySet().iterator();
1011         StringBuffer sb = new StringBuffer();
1012         String id = null;
1013         while (iterator.hasNext()) {
1014             key = (String) iterator.next();
1015             value = (String) map.get(key);
1016             if (map.get("instanceIdentifier") != null) {
1017                 workInstance.setInstanceIdentifier((String) map.get("instanceIdentifier"));
1018                 ((org.kuali.ole.docstore.model.bo.WorkBibDocument) oleDocument).setInstanceDocument(workInstance);
1019                 id = (String) map.get("instanceIdentifier");
1020             }
1021         }
1022         String queryString = "instanceIdentifier:" + id;
1023         SolrRequestReponseHandler solrResponse = new SolrRequestReponseHandler();
1024         List<HashMap<String, Object>> bibInfo = solrResponse.retriveResults(queryString);
1025         BibInfoBean bibInfoList = setBibInfoBean(bibInfo);
1026         return bibInfoList;
1027     }
1028 
1029 
1030 
1031 
1032 
1033 
1034 
1035 
1036     public BibInfoBean setBibInfoBean(List<HashMap<String, Object>> bibInfo) {
1037         BibInfoBean bibInfoBean = new BibInfoBean();
1038         Iterator itr = bibInfo.iterator();
1039         String author = null;
1040         String title = null;
1041         String publisher = null;
1042         String isbn = null;
1043         while (itr.hasNext()) {
1044             HashMap<String, Object> resultMap = (HashMap<String, Object>) itr.next();
1045             if (resultMap.get("Author_display") != null) {
1046                 author = (String) resultMap.get("Author_display").toString();
1047                 author = author.replace('[', ' ').replace(']', ' ');
1048             }
1049             if (resultMap.get("Title_display") != null) {
1050                 title = (String) resultMap.get("Title_display").toString();
1051                 title = title.replace('[', ' ').replace(']', ' ');
1052             }
1053             if (resultMap.get("Publisher_display") != null) {
1054                 publisher = (String) resultMap.get("Publisher_display").toString();
1055                 publisher = publisher.replace('[', ' ').replace(']', ' ');
1056             }
1057             if (resultMap.get("ISBN_display") != null) {
1058                 isbn = (String) resultMap.get("ISBN_display").toString();
1059                 isbn = isbn.replace('[', ' ').replace(']', ' ');
1060             }
1061         }
1062         bibInfoBean.setAuthor(author);
1063         bibInfoBean.setTitle(title);
1064         bibInfoBean.setPublisher(publisher);
1065         bibInfoBean.setIsbn(isbn);
1066 
1067         return bibInfoBean;
1068     }
1069     public BibInfoBean setBibInfoBeanNew(Bib bib) {
1070         BibInfoBean bibInfoBean = new BibInfoBean();
1071         bibInfoBean.setTitle(bib.getTitle());
1072         bibInfoBean.setAuthor(bib.getAuthor());
1073         bibInfoBean.setIsbn(bib.getIsbn());
1074         return bibInfoBean;
1075     }
1076 }