View Javadoc

1   package org.kuali.ole.docstore.discovery.service;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.apache.solr.client.solrj.SolrQuery;
5   import org.apache.solr.client.solrj.SolrServer;
6   import org.apache.solr.client.solrj.SolrServerException;
7   import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
8   import org.apache.solr.client.solrj.response.QueryResponse;
9   import org.apache.solr.common.SolrDocument;
10  import org.apache.solr.common.SolrDocumentList;
11  import org.kuali.ole.docstore.discovery.model.SearchCondition;
12  import org.kuali.ole.docstore.discovery.model.SearchParams;
13  import org.kuali.ole.docstore.discovery.solr.work.bib.WorkBibCommonFields;
14  import org.kuali.ole.docstore.discovery.util.PropertyUtil;
15  import org.kuali.ole.docstore.model.bo.*;
16  import org.kuali.ole.docstore.model.enums.DocType;
17  import org.kuali.ole.utility.callnumber.CallNumber;
18  import org.kuali.ole.utility.callnumber.CallNumberFactory;
19  import org.slf4j.Logger;
20  import org.slf4j.LoggerFactory;
21  
22  import java.io.IOException;
23  import java.util.*;
24  
25  /**
26   * User: tirumalesh.b
27   * Date: 16/1/12 Time: 12:49 PM
28   */
29  public class QueryServiceImpl
30          implements QueryService  {
31      private static final Logger LOG = LoggerFactory.getLogger(QueryServiceImpl.class);
32      private static       QueryService            queryService = null;
33      private static       String                  docSearchUrl = null;
34      private final String INSTANCE_IDENTIFIER ="instanceIdentifier";
35      private final String BIBLIOGRAPHIC="bibliographic";
36      private final String DOC_TYPE ="DocType";
37      private final String DOC_FORMAT ="DocFormat";
38      private final String HOLDINGS_IDENTIFIER ="holdingsIdentifier";
39      private final String ITEM_IDENTIFIER ="itemIdentifier";
40      private final String INSTANCE="instance";
41      private final String OLEML="oleml";
42      private final String DELETE_WITH_LINKED_DOCS="deleteWithLinkedDocs";
43      private final String DELETE="delete";
44  
45      private QueryServiceImpl() {
46          init();
47      }
48  
49      public static QueryService getInstance() {
50          if (null == queryService) {
51              queryService = new QueryServiceImpl();
52          }
53          return queryService;
54      }
55  
56      protected void init() {
57          LOG.debug("QueryServiceImpl init ");
58          docSearchUrl = PropertyUtil.getPropertyUtil().getProperty("docSearchURL");
59          if ((null != docSearchUrl) && !docSearchUrl.endsWith("/")) {
60              docSearchUrl = docSearchUrl + "/";
61          }
62      }
63  
64      @Override
65      public List<OleDocument> queryForDocs(OleDocument queryDoc) throws Exception {
66          List<OleDocument> oleDocuments;
67          List<Map<String, Object>> solrHits;
68          String queryString = buildQueryForDoc(queryDoc);
69          solrHits = getSolrHitsForQuery(queryString);
70          oleDocuments = buildOleDocuments(solrHits);
71          return oleDocuments;
72      }
73  
74      private List<Map<String, Object>> getSolrHits(SearchParams searchParams) throws Exception {
75          List<Map<String, Object>> solrHits;
76          String queryString = buildQuery(searchParams);
77          solrHits = getSolrHitsForQuery(queryString);
78          return solrHits;
79      }
80  
81      @Override
82      public List<WorkBibDocument> getBibDocuments (SearchParams searchParams) throws Exception {
83          List<WorkBibDocument> workBibDocuments;
84          List<Map<String, Object>> solrHits = getSolrHits(searchParams);
85          workBibDocuments = buildWorkBibDocuments(solrHits);
86          return workBibDocuments;
87      }
88  
89      @Override
90      public List<WorkHoldingsDocument> getHoldingDocuments (SearchParams searchParams) throws Exception {
91          List<WorkHoldingsDocument> workHoldingsDocuments;
92          List<Map<String, Object>> solrHits = getSolrHits(searchParams);
93          workHoldingsDocuments = buildWorkHoldingDocuments(solrHits);
94          return workHoldingsDocuments;
95      }
96  
97      @Override
98      public List<WorkItemDocument> getItemDocuments (SearchParams searchParams) throws Exception {
99          List<WorkItemDocument> workItemDocuments;
100         List<Map<String, Object>> solrHits = getSolrHits(searchParams);
101         workItemDocuments = buildWorkItemDocuments(solrHits);
102         return workItemDocuments;
103     }
104 
105     @Override
106     public String queryField(SearchParams searchParams, String fieldName) throws Exception {
107         SolrQuery solrQuery = new SolrQuery();
108         SolrServer server = SolrServerManager.getInstance().getSolrServer();
109         String query = ServiceLocator.getDiscoveryService().buildQuery(searchParams);
110         int i=query.indexOf("=");
111         String query1=query.substring(i+1);
112         solrQuery.setQuery(query1);
113         solrQuery.setStart(1);
114         solrQuery.setRows(10);
115         QueryResponse response = server.query(solrQuery);
116         return getFieldValue(response, fieldName);
117     }
118 
119     public String getFieldValue(QueryResponse response, String fieldName) {
120         String result = null;
121         SolrDocumentList docs = response.getResults();
122         if (docs != null) {
123             SolrDocument doc = docs.get(0);
124             result = (String) doc.getFieldValue(fieldName);
125         }
126         return result;
127     }
128 
129 
130     /**
131      * @param hitsOnPage
132      * @return List of OleDocuments
133      */
134     public List<OleDocument> buildOleDocuments(List<Map<String, Object>> hitsOnPage) {
135         List<OleDocument> oleDocuments = new ArrayList<OleDocument>();
136         for (Map<String, Object> hitsOnPageItr : hitsOnPage) {
137             WorkBibDocument workBibDocument = new WorkBibDocument();
138             Map map = hitsOnPageItr;
139             Set keys = map.keySet();
140             for (Object key : keys) {
141                 if (key.toString().equalsIgnoreCase("Title_display")) {
142                     Object value = map.get(key);
143                     if (value instanceof String) {
144                         workBibDocument.setTitle((String) value);
145                     } else if (value instanceof List) {
146                         workBibDocument.setTitles((List<String>) value);
147                     }
148                 }
149 
150                 if (key.toString().equalsIgnoreCase("Author_display")) {
151                     Object value = map.get(key);
152                     if (value instanceof String) {
153                         workBibDocument.setAuthor((String) value);
154                     } else if (value instanceof List) {
155                         workBibDocument.setAuthors((List<String>) value);
156                     }
157                 }
158 
159                 if (key.toString().equalsIgnoreCase("PublicationDate_display")) {
160                     Object value = map.get(key);
161                     if (value instanceof String) {
162                         workBibDocument.setPublicationDate((String) value);
163                     } else if (value instanceof List) {
164                         workBibDocument.setPublicationDates((List<String>) value);
165                     }
166                 }
167 
168                 if (key.toString().equalsIgnoreCase("ISBN_display")) {
169                     Object value = map.get(key);
170                     if (value instanceof String) {
171                         workBibDocument.setIsbn((String) value);
172                     } else if (value instanceof List) {
173                         workBibDocument.setIsbns((List<String>) value);
174                     }
175                 }
176 
177                 if (key.toString().equalsIgnoreCase("Publisher_display")) {
178                     Object value = map.get(key);
179                     if (value instanceof String) {
180                         workBibDocument.setPublisher((String) value);
181                     } else if (value instanceof List) {
182                         workBibDocument.setPublishers((List<String>) value);
183                     }
184                 }
185                 if (key.toString().equalsIgnoreCase("id")) {
186                     workBibDocument.setId((String)map.get(key));
187                 }
188                 if (key.toString().equalsIgnoreCase("bibIdentifier")) {
189                     workBibDocument.setId((String) map.get(key));
190                 }
191 
192             }
193             oleDocuments.add(workBibDocument);
194         }
195         return oleDocuments;
196     }
197 
198     /**
199      * @param hitsOnPage
200      * @return List of workBibDocuments
201      */
202     public List<WorkBibDocument> buildWorkBibDocuments(List<Map<String, Object>> hitsOnPage) {
203         List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
204         for (Map<String, Object> hitsOnPageItr : hitsOnPage) {
205             WorkBibDocument workBibDocument = new WorkBibDocument();
206             Map map = hitsOnPageItr;
207             Set keys = map.keySet();
208             for (Object key : keys) {
209                 if (key.toString().equalsIgnoreCase("Title_display")) {
210                     Object value = map.get(key);
211                     if (value instanceof String) {
212                         workBibDocument.setTitle((String) value);
213                     } else if (value instanceof List) {
214                         workBibDocument.setTitles((List<String>) value);
215                     }
216                 }
217 
218                 if (key.toString().equalsIgnoreCase("Author_display")) {
219                     Object value = map.get(key);
220                     if (value instanceof String) {
221                         workBibDocument.setAuthor((String) value);
222                     } else if (value instanceof List) {
223                         workBibDocument.setAuthors((List<String>) value);
224                     }
225                 }
226 
227                 if (key.toString().equalsIgnoreCase("PublicationDate_display")) {
228                     Object value = map.get(key);
229                     if (value instanceof String) {
230                         workBibDocument.setPublicationDate((String) value);
231                     } else if (value instanceof List) {
232                         workBibDocument.setPublicationDates((List<String>) value);
233                     }
234                 }
235 
236                 if (key.toString().equalsIgnoreCase("ISBN_display")) {
237                     Object value = map.get(key);
238                     if (value instanceof String) {
239                         workBibDocument.setIsbn((String) value);
240                     } else if (value instanceof List) {
241                         workBibDocument.setIsbns((List<String>) value);
242                     }
243                 }
244 
245                 if (key.toString().equalsIgnoreCase("Publisher_display")) {
246                     Object value = map.get(key);
247                     if (value instanceof String) {
248                         workBibDocument.setPublisher((String) value);
249                     } else if (value instanceof List) {
250                         workBibDocument.setPublishers((List<String>) value);
251                     }
252                 }
253 
254                 if (key.toString().equalsIgnoreCase("instanceIdentifier")) {
255                     Object value = map.get(key);
256                     if (value instanceof String) {
257                         workBibDocument.setInstanceIdentifier((String) value);
258                     } else if (value instanceof List) {
259                         ArrayList<String> list = (ArrayList<String>) value;
260                         workBibDocument.setInstanceIdentifier(list.get(0));
261                     }
262                 }
263 
264                 if (key.toString().equalsIgnoreCase("DocFormat")) {
265                     Object value = map.get(key);
266                     if (value instanceof String) {
267                         workBibDocument.setDocFormat((String) value);
268                     } else if (value instanceof List) {
269                         ArrayList<String> list = (ArrayList<String>) value;
270                         workBibDocument.setDocFormat(list.get(0));
271                     }
272                 }
273 
274                 if (key.toString().equalsIgnoreCase("id")) {
275                     workBibDocument.setId((String) map.get(key));
276                 }
277 
278             }
279             workBibDocuments.add(workBibDocument);
280         }
281         return workBibDocuments;
282     }
283 
284     /**
285      * @param hitsOnPage
286      * @return List of workHoldingsDocuments
287      */
288     public List<WorkHoldingsDocument> buildWorkHoldingDocuments(List<Map<String, Object>> hitsOnPage) {
289         List<WorkHoldingsDocument> workHoldingsDocuments = new ArrayList<WorkHoldingsDocument>();
290         for (Map<String, Object> hitsOnPageItr : hitsOnPage) {
291             WorkHoldingsDocument workHoldingsDocument = new WorkHoldingsDocument();
292             Map map = hitsOnPageItr;
293             Set keys = map.keySet();
294             for (Object key : keys) {
295                 if (key.toString().equalsIgnoreCase("LocationLevel_display")) {
296                     Object value = map.get(key);
297                     if (value instanceof String) {
298                         workHoldingsDocument.setLocationName((String) value);
299                     }
300                 }
301                 if (key.toString().equalsIgnoreCase("CallNumber_display")) {
302                     Object value = map.get(key);
303                     if (value instanceof String) {
304                         workHoldingsDocument.setCallNumber((String) value);
305                     }
306                 }
307                 if (key.toString().equalsIgnoreCase("id")) {
308                     workHoldingsDocument.setHoldingsIdentifier((String) map.get(key));
309                 }
310                 if (key.toString().equalsIgnoreCase("bibIdentifier")) {
311                     Object value = map.get(key);
312                     if (value instanceof String) {
313                         workHoldingsDocument.setBibIdentifier((String) value);
314                     } else if (value instanceof List) {
315                         ArrayList<String> list = (ArrayList<String>) value;
316                         workHoldingsDocument.setBibIdentifier(list.get(0));
317                     }
318                 }
319             }
320             workHoldingsDocuments.add(workHoldingsDocument);
321         }
322         return workHoldingsDocuments;
323     }
324 
325     /**
326      * @param hitsOnPage
327      * @return List of workItemDocuments
328      */
329     public List<WorkItemDocument> buildWorkItemDocuments(List<Map<String, Object>> hitsOnPage) {
330         List<WorkItemDocument> workItemDocuments = new ArrayList<WorkItemDocument>();
331         for (Map<String, Object> hitsOnPageItr : hitsOnPage) {
332             WorkItemDocument workItemDocument = new WorkItemDocument();
333             Map map = hitsOnPageItr;
334             Set keys = map.keySet();
335             for (Object key : keys) {
336                 if (key.toString().equalsIgnoreCase("LocationLevel_display")) {
337                     Object value = map.get(key);
338                     if (value instanceof String) {
339                         workItemDocument.setLocation((String) value);
340                     }
341                     else if (value instanceof List) {
342                         ArrayList<String> list = (ArrayList<String>) value;
343                         workItemDocument.setLocation(list.get(0));
344                     }
345                 }
346                 if (key.toString().equalsIgnoreCase("CallNumber_display")) {
347                     Object value = map.get(key);
348                     if (value instanceof String) {
349                         workItemDocument.setCallNumber((String) value);
350                     }
351                     else if (value instanceof List) {
352                         ArrayList<String> list = (ArrayList<String>) value;
353                         workItemDocument.setCallNumber(list.get(0));
354                     }
355                 }
356                 if (key.toString().equalsIgnoreCase("ItemBarcode_display")) {
357                     Object value = map.get(key);
358                     if (value instanceof String) {
359                         workItemDocument.setBarcode((String) value);
360                     }
361                     else if (value instanceof List) {
362                         ArrayList<String> list = (ArrayList<String>) value;
363                         workItemDocument.setBarcode(list.get(0));
364                     }
365                 }
366                 if (key.toString().equalsIgnoreCase("ShelvingOrder_display")) {
367                     Object value = map.get(key);
368                     if (value instanceof String) {
369                         workItemDocument.setShelvingOrder((String) value);
370                     }
371                     else if (value instanceof List) {
372                         ArrayList<String> list = (ArrayList<String>) value;
373                         workItemDocument.setShelvingOrder(list.get(0));
374                     }
375                 }
376                 if (key.toString().equalsIgnoreCase("Enumeration_display")) {
377                     Object value = map.get(key);
378                     if (value instanceof String) {
379                         workItemDocument.setEnumeration((String) value);
380                     }
381                     else if (value instanceof List) {
382                         ArrayList<String> list = (ArrayList<String>) value;
383                         workItemDocument.setEnumeration(list.get(0));
384                     }
385                 }
386                 if (key.toString().equalsIgnoreCase("Chronology_display")) {
387                     Object value = map.get(key);
388                     if (value instanceof String) {
389                         workItemDocument.setChronology((String) value);
390                     }
391                     else if (value instanceof List) {
392                         ArrayList<String> list = (ArrayList<String>) value;
393                         workItemDocument.setChronology(list.get(0));
394                     }
395                 }
396                 if (key.toString().equalsIgnoreCase("CopyNumber_display")) {
397                     Object value = map.get(key);
398                     if (value instanceof String) {
399                         workItemDocument.setCopyNumber((String) value);
400                     }
401                     else if (value instanceof List) {
402                         ArrayList<String> list = (ArrayList<String>) value;
403                         workItemDocument.setCopyNumber(list.get(0));
404                     }
405                 }
406 
407                 if (key.toString().equalsIgnoreCase("bibIdentifier")) {
408                     Object value = map.get(key);
409                     if (value instanceof String) {
410                         workItemDocument.setBibIdentifier((String) value);
411                     }
412                     else if (value instanceof List) {
413                         ArrayList<String> list = (ArrayList<String>) value;
414                         workItemDocument.setBibIdentifier(list.get(0));
415                     }
416                 }
417 
418                 if (key.toString().equalsIgnoreCase("id")) {
419                     workItemDocument.setId((String) map.get(key));
420                 }
421 
422                 if (key.toString().equalsIgnoreCase("id")) {
423                     workItemDocument.setItemIdentifier((String) map.get(key));
424                 }
425 
426                 if (key.toString().equalsIgnoreCase("instanceIdentifier")) {
427                     Object value = map.get(key);
428                     if (value instanceof String) {
429                         workItemDocument.setInstanceIdentifier((String) value);
430                     }
431                     else if (value instanceof List) {
432                         ArrayList<String> list = (ArrayList<String>) value;
433                         workItemDocument.setInstanceIdentifier(list.get(0));
434                     }
435                 }
436 
437             }
438             workItemDocuments.add(workItemDocument);
439         }
440         return workItemDocuments;
441     }
442 
443 
444     /**
445      *
446      * @param queryDoc
447      * @return
448      * @throws Exception
449      */
450     @Override
451     public WorkBibDocument queryForBibTree(WorkBibDocument queryDoc) throws Exception {
452         String id = queryDoc.getId();
453         LOG.info("id-->" + id);
454         List<WorkInstanceDocument> workInstanceDocumentList = new ArrayList<WorkInstanceDocument>();
455         List<WorkHoldingsDocument> workHoldingsDocumentList = new ArrayList<WorkHoldingsDocument>();
456         List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
457         WorkInstanceDocument workInstanceDocument = null;
458         WorkHoldingsDocument workHoldingsDocument;
459         WorkItemDocument workItemDocument;
460         queryDoc = buildBibDocumentInfo(queryDoc);
461         String queryString = buildQueryForBibTree(queryDoc);
462         SolrQuery solrQuery = new SolrQuery();
463         SolrServer server = SolrServerManager.getInstance().getSolrServer();
464         solrQuery.setQuery(queryString);
465         solrQuery.addSortField("LocationLevel_sort", SolrQuery.ORDER.asc);
466         solrQuery.addSortField("ShelvingOrder_sort", SolrQuery.ORDER.asc);
467         solrQuery.setRows(500);
468         LOG.info("solr query-->" + solrQuery);
469         QueryResponse response = server.query(solrQuery);
470         List<SolrDocument> solrDocumentList = response.getResults();
471         for (SolrDocument solrDocument : solrDocumentList) {
472 
473             //build instance document
474             String docType = (String) solrDocument.getFieldValue("DocType");
475             if (docType.equalsIgnoreCase(DocType.HOLDINGS.getCode())) {
476                 workInstanceDocument = new WorkInstanceDocument();
477                 String instanceIdentifier = (String) solrDocument.getFieldValue("instanceIdentifier");
478                 String holdingsIdentifier = (String) solrDocument.getFieldValue("id");
479                 workItemDocumentList = new ArrayList<WorkItemDocument>();
480                 workHoldingsDocumentList = new ArrayList<WorkHoldingsDocument>();
481                 workHoldingsDocument = new WorkHoldingsDocument();
482                 workHoldingsDocument.setHoldingsIdentifier(holdingsIdentifier);
483                 String locationName = (String) solrDocument.getFieldValue("LocationLevel_display");
484                 workHoldingsDocument.setLocationName(locationName);
485                 workHoldingsDocument.setCallNumberType(getFieldVal(solrDocument, "CallNumberType_display"));
486                 workHoldingsDocument.setCallNumberPrefix(getFieldVal(solrDocument, "CallNumberPrefix_display"));
487                 workHoldingsDocument.setCallNumber(getFieldVal(solrDocument, "CallNumber_display"));
488                 workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
489 
490                 for (SolrDocument itemSolrDocument : solrDocumentList) {
491                     docType = (String) itemSolrDocument.getFieldValue("DocType");
492                     if ((docType.equalsIgnoreCase(DocType.ITEM.getCode())) && (itemSolrDocument.getFieldValue("holdingsIdentifier").equals(holdingsIdentifier))) {
493 
494                         workItemDocument = new WorkItemDocument();
495                         String itemIdentifier = (String) itemSolrDocument.getFieldValue("id");
496                         workItemDocument.setItemIdentifier(itemIdentifier);
497                         String callNumberType = (String) itemSolrDocument.getFieldValue("CallNumberType_display");
498                         String callNumberPrefix = (String) itemSolrDocument.getFieldValue("CallNumberPrefix_display");
499                         String callNumber = (String) itemSolrDocument.getFieldValue("CallNumber_display");
500                         workItemDocument.setLocation(getFieldVal(itemSolrDocument, "LocationLevel_display"));
501                         workItemDocument.setCopyNumber(getFieldVal(itemSolrDocument, "CopyNumber_display"));
502                         workItemDocument.setEnumeration(getFieldVal(itemSolrDocument, "Enumeration_display"));
503                         workItemDocument.setChronology(getFieldVal(itemSolrDocument, "Chronology_display"));
504                         workItemDocument.setItemStatus(getFieldVal(itemSolrDocument, "ItemStatus_display"));
505                         workItemDocument.setBarcode(getFieldVal(itemSolrDocument, "ItemBarcode_display"));
506                         workItemDocument.setVolumeNumber(getFieldVal(itemSolrDocument, "VolumeNumber_display"));
507                         workItemDocument.setCallNumberType(callNumberType);
508                         workItemDocument.setCallNumberPrefix(callNumberPrefix);
509                         workItemDocument.setItemType(getFieldVal(itemSolrDocument, "ItemTypeCodeValue_display"));
510                         workItemDocument.setCallNumber(callNumber);
511                         workItemDocumentList.add(workItemDocument);
512                         workInstanceDocument.setItemDocumentList(workItemDocumentList);
513                         LOG.debug("workItemDocumentList size-->" + workItemDocumentList.size());
514                     }
515                 }
516                 workInstanceDocument.setInstanceIdentifier(instanceIdentifier);
517                 workInstanceDocumentList.add(workInstanceDocument);
518             }
519 
520             queryDoc.setInstanceDocument(workInstanceDocument);
521             queryDoc.setWorkInstanceDocumentList(workInstanceDocumentList);
522         }
523 
524         return queryDoc;
525     }
526 
527     private String getFieldVal(SolrDocument solrDocument, String field) {
528         String fieldValue = null;
529         if( solrDocument.getFieldValue(field) instanceof String){
530             fieldValue = (String) solrDocument.getFieldValue(field);
531         }
532         else if (solrDocument.getFieldValue(field) instanceof List){
533             List<String> locList = (List<String>) solrDocument.getFieldValue(field);
534             fieldValue = locList.get(0);
535         }
536         return fieldValue;
537     }
538 
539 
540     public WorkBibDocument buildBibDocumentInfo(WorkBibDocument bibDocument) throws SolrServerException, IOException {
541         String queryString = buildQueryForBibInfo(bibDocument);
542         SolrQuery solrQuery = new SolrQuery();
543         SolrServer server = SolrServerManager.getInstance().getSolrServer();
544         solrQuery.setQuery(queryString);
545         QueryResponse response = server.query(solrQuery);
546         List<SolrDocument> solrDocumentList = response.getResults();
547 
548         for (SolrDocument solrDocument : solrDocumentList) {
549             String title = (String) solrDocument.getFieldValue("Title_display");
550             String format = (String) solrDocument.getFieldValue("DocFormat");
551             bibDocument.setTitle(title);
552             bibDocument.setAuthor(getFieldVal(solrDocument, "Author_display"));
553             bibDocument.setPublicationDate(getFieldVal(solrDocument, "PublicationDate_display"));
554             bibDocument.setEdition(getFieldVal(solrDocument, "Edition_display"));
555             bibDocument.setDocFormat(format);
556         }
557 
558         return bibDocument;
559     }
560 
561 
562     /**
563      * @param workBibDocumentList
564      * @return
565      * @throws Exception
566      */
567     @Override
568     public List<WorkBibDocument> queryForBibTree(List<WorkBibDocument> workBibDocumentList) throws Exception {
569         for (WorkBibDocument bibDocument : workBibDocumentList) {
570             bibDocument = queryForBibTree(bibDocument);
571             workBibDocumentList.add(bibDocument);
572         }
573         return workBibDocumentList;
574     }
575 
576 
577     /**
578      * This method returns the Bib ids for the selected bound-with instance.
579      * @param instancedId
580      * @return
581      * @throws SolrServerException
582      */
583    @Override
584    public List<String> queryForBibs(String instancedId) throws SolrServerException {
585        List<String> bibUuidList = new ArrayList<String>();
586        SolrQuery solrQuery = new SolrQuery();
587        SolrServer server = SolrServerManager.getInstance().getSolrServer();
588        solrQuery.setQuery("instanceIdentifier:" + instancedId);
589        LOG.info("solr query-->" + solrQuery);
590        QueryResponse response = server.query(solrQuery);
591        List<SolrDocument> solrDocumentList = response.getResults();
592        for (SolrDocument solrDocument : solrDocumentList) {
593            String docType = (String) solrDocument.getFieldValue("DocType");
594            if (docType.equalsIgnoreCase(DocType.BIB.getDescription())) {
595                bibUuidList.add((String) solrDocument.getFieldValue("id"));
596            }
597 
598        }
599        return bibUuidList;
600    }
601 
602 
603     /**
604      * This method used to get the instances for the selected bibs.
605      * @param uuid
606      * @return
607      * @throws SolrServerException
608      */
609     @Override
610     public List<String> queryForInstances(String uuid) throws SolrServerException {
611         List<String> instanceIdList = new ArrayList<String>();
612         SolrQuery solrQuery = new SolrQuery();
613         SolrServer server = SolrServerManager.getInstance().getSolrServer();
614         solrQuery.setQuery("id:" + uuid);
615         LOG.info("solr query-->" + solrQuery);
616         QueryResponse response = server.query(solrQuery);
617         List<SolrDocument> solrDocumentList = response.getResults();
618         for (SolrDocument solrDocument : solrDocumentList) {
619             String docType = (String) solrDocument.getFieldValue("DocType");
620             if (docType.equalsIgnoreCase(DocType.BIB.getDescription())) {
621                 Object instanceId = solrDocument.getFieldValue("instanceIdentifier");
622                 if (instanceId instanceof String) {
623                     instanceIdList.add((String) instanceId);
624                 }
625                 if (instanceId instanceof List) {
626                     instanceIdList = (List<String>) instanceId;
627                 }
628             }
629 
630         }
631         return instanceIdList;
632     }
633 
634     @Override
635     public WorkInstanceDocument queryForInstanceTree(WorkInstanceDocument instanceDocument) throws SolrServerException {
636 
637         String id = instanceDocument.getId();
638         LOG.info("id-->" + id);
639         List<WorkInstanceDocument> workInstanceDocumentList = new ArrayList<WorkInstanceDocument>();
640         List<WorkHoldingsDocument> workHoldingsDocumentList = new ArrayList<WorkHoldingsDocument>();
641         List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
642         WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
643         WorkHoldingsDocument workHoldingsDocument;
644         WorkItemDocument workItemDocument;
645         //String queryString = buildQueryForInstanceTree(instanceDocument);
646         SolrQuery solrQuery = new SolrQuery();
647         SolrServer server = SolrServerManager.getInstance().getSolrServer();
648         solrQuery.setQuery("instanceIdentifier:"+id);
649         LOG.info("solr query-->" + solrQuery);
650         QueryResponse response = server.query(solrQuery);
651         List<SolrDocument> solrDocumentList = response.getResults();
652         String docType;
653         workItemDocumentList = new ArrayList<WorkItemDocument>();
654         workHoldingsDocumentList = new ArrayList<WorkHoldingsDocument>();
655         for (SolrDocument itemSolrDocument : solrDocumentList) {
656             docType = (String) itemSolrDocument.getFieldValue("DocType");
657             if ((docType.equalsIgnoreCase(DocType.ITEM.getCode())) && (itemSolrDocument.getFieldValue("instanceIdentifier").equals(id))) {
658 
659                 workItemDocument = new WorkItemDocument();
660 //                String itemIdentifier = (String) itemSolrDocument.getFieldValue("id");
661 //                String callNumberType = (String) itemSolrDocument.getFieldValue("CallNumberType_display");
662 //                String callNumberPrefix = (String) itemSolrDocument.getFieldValue("CallNumberPrefix_display");
663 //                String bibIndetifier=(String) itemSolrDocument.getFieldValue("bibIdentifier");
664 //                String callNumber = (String) itemSolrDocument.getFieldValue("CallNumber_display");
665 
666                 String itemIdentifier = getFieldVal(itemSolrDocument, "id");
667                 String callNumberType = getFieldVal(itemSolrDocument, "CallNumberType_display");
668                 String callNumberPrefix = getFieldVal(itemSolrDocument, "CallNumberPrefix_display");
669                 String bibIdentifier = getFieldVal(itemSolrDocument, "bibIdentifier");
670                 String callNumber = getFieldVal(itemSolrDocument, "CallNumber_display");
671 
672                 workItemDocument.setLocation(getFieldVal(itemSolrDocument, "LocationLevel_display"));
673                 workItemDocument.setBarcode(getFieldVal(itemSolrDocument, "ItemBarcode_display"));
674                 workItemDocument.setItemType(getFieldVal(itemSolrDocument, "ItemTypeCodeValue_display"));
675                 workItemDocument.setLocationName(getFieldVal(itemSolrDocument, "LocationLevelName_display"));
676                 workItemDocument.setItemStatus(getFieldVal(itemSolrDocument,"ItemStatus_display"));
677                 workItemDocument.setCallNumberType(callNumberType);
678                 workItemDocument.setCallNumberPrefix(callNumberPrefix);
679                // workItemDocument.setItemType(getFieldVal(itemSolrDocument, "ItemTypeCodeValue_display"));
680                 workItemDocument.setCallNumber(callNumber);
681                 workItemDocument.setItemIdentifier(itemIdentifier);
682                 workItemDocumentList.add(workItemDocument);
683                 workInstanceDocument.setBibIdentifier(bibIdentifier);
684                 workInstanceDocument.setItemDocumentList(workItemDocumentList);
685             }
686 
687         }
688         for (SolrDocument holdingSolrDocument : solrDocumentList) {
689             docType = (String) holdingSolrDocument.getFieldValue("DocType");
690 
691             if ((docType.equalsIgnoreCase(DocType.HOLDINGS.getCode())) && (holdingSolrDocument.getFieldValue("instanceIdentifier").equals(id))) {
692                 workHoldingsDocument = new WorkHoldingsDocument();
693                 String holdingsIdentifier = (String) holdingSolrDocument.getFieldValue("id");
694 //                String bibIndetifier=(String) holdingSolrDocument.getFieldValue("bibIdentifier");
695                 String bibIdentifier = getFieldVal(holdingSolrDocument, "bibIdentifier");
696                 workHoldingsDocument.setHoldingsIdentifier(holdingsIdentifier);
697 //                String locationName = (String) holdingSolrDocument.getFieldValue("LocationLevel_display");
698                 String locationName = getFieldVal(holdingSolrDocument, "LocationLevel_display");
699                 workHoldingsDocument.setLocationName(locationName);
700                 workHoldingsDocument.setCallNumberType(getFieldVal(holdingSolrDocument, "CallNumberType_display"));
701                 workHoldingsDocument.setCallNumberPrefix(getFieldVal(holdingSolrDocument, "CallNumberPrefix_display"));
702                 workHoldingsDocument.setCallNumber(getFieldVal(holdingSolrDocument, "CallNumber_display"));
703                 workHoldingsDocumentList.add(workHoldingsDocument);
704                 workInstanceDocument.setBibIdentifier(bibIdentifier);
705                 workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
706             }
707         }
708 
709         workInstanceDocument.setInstanceIdentifier(id);
710         workInstanceDocumentList.add(workInstanceDocument);
711 
712 
713         return workInstanceDocument;
714     }
715 
716     @Override
717     public WorkItemDocument queryForItemTree(WorkItemDocument itemDocument) throws SolrServerException {
718 
719         String id = itemDocument.getId();
720         LOG.info("id-->" + id);
721         List<WorkHoldingsDocument> workHoldingsDocumentList = new ArrayList<WorkHoldingsDocument>();
722         List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
723         WorkItemDocument workItemDocument;
724         //String queryString = buildQueryForItemTree(itemDocument);
725         SolrQuery solrQuery = new SolrQuery();
726         SolrServer server = SolrServerManager.getInstance().getSolrServer();
727         solrQuery.setQuery("id:"+id);
728         LOG.info("solr query-->" + solrQuery);
729         QueryResponse response = server.query(solrQuery);
730         List<SolrDocument> solrDocumentList = response.getResults();
731         String docType;
732         workItemDocument = new WorkItemDocument();
733         workItemDocumentList = new ArrayList<WorkItemDocument>();
734 
735         for (SolrDocument itemSolrDocument : solrDocumentList) {
736             docType = (String) itemSolrDocument.getFieldValue("DocType");
737             if ((docType.equalsIgnoreCase(DocType.ITEM.getCode())) && (itemSolrDocument.getFieldValue("id").equals(id))) {
738 
739 
740                 String itemIdentifier = (String) itemSolrDocument.getFieldValue("id");
741 //                String instanceIdentifier = (String) itemSolrDocument.getFieldValue("instanceIdentifier");
742 //                String bibIdentifier = (String) itemSolrDocument.getFieldValue("bibIdentifier");
743 //                String callNumberType = (String) itemSolrDocument.getFieldValue("CallNumberType_display");
744 //                String callNumberPrefix = (String) itemSolrDocument.getFieldValue("CallNumberPrefix_display");
745 //                String callNumber = (String) itemSolrDocument.getFieldValue("CallNumber_display");
746 
747                 String instanceIdentifier = getFieldVal(itemSolrDocument,"instanceIdentifier");
748                 String bibIdentifier = getFieldVal(itemSolrDocument,"bibIdentifier");
749                 String callNumberType = getFieldVal(itemSolrDocument,"CallNumberType_display");
750                 String callNumberPrefix = getFieldVal(itemSolrDocument,"CallNumberPrefix_display");
751                 String callNumber = getFieldVal(itemSolrDocument,"CallNumber_display");
752 
753                 workItemDocument.setLocation(getFieldVal(itemSolrDocument, "LocationLevel_display"));
754                 workItemDocument.setBarcode(getFieldVal(itemSolrDocument, "ItemBarcode_display"));
755                 workItemDocument.setItemType(getFieldVal(itemSolrDocument, "ItemTypeCodeValue_display"));
756                 workItemDocument.setLocationName(getFieldVal(itemSolrDocument, "LocationLevelName_display"));
757                 workItemDocument.setCopyNumber(getFieldVal(itemSolrDocument, "CopyNumber_display"));
758                 workItemDocument.setVolumeNumber(getFieldVal(itemSolrDocument, "VolumeNumber_display"));
759                 workItemDocument.setItemStatus(getFieldVal(itemSolrDocument,"ItemStatus_display"));
760                 workItemDocument.setCallNumber(callNumber);
761                 workItemDocument.setCallNumberType(callNumberType);
762                 workItemDocument.setCallNumberPrefix(callNumberPrefix);
763                 workItemDocument.setItemIdentifier(itemIdentifier);
764                 workItemDocument.setInstanceIdentifier(instanceIdentifier);
765                 workItemDocument.setBibIdentifier(bibIdentifier);
766                 workItemDocumentList.add(workItemDocument);
767                 LOG.debug("workItemDocumentList size-->" + workItemDocumentList.size());
768             }
769         }
770 
771 
772         return workItemDocument;  //To change body of implemented methods use File | Settings | File Templates.
773     }
774 
775     private String buildQueryForBibTree(OleDocument queryDoc) {
776         StringBuilder query = new StringBuilder();
777 
778         if (((WorkBibDocument) queryDoc).getId() != null && query.length() > 0) {
779             query.append("(bibIdentifier :").append((((WorkBibDocument) queryDoc).getId())).append(")");
780         } else if (((WorkBibDocument) queryDoc).getId() != null) {
781             query.append("(bibIdentifier :").append((((WorkBibDocument) queryDoc).getId())).append(")");
782 
783 
784         }
785         return query.toString();
786     }
787 
788     private String buildQueryForInstanceTree(OleDocument queryDoc) {
789         StringBuilder query = new StringBuilder();
790 
791         if (((WorkInstanceDocument) queryDoc).getId() != null && query.length() > 0) {
792             query.append("(instanceIdentifier :").append((((WorkInstanceDocument) queryDoc).getId())).append(")");
793         } else if (((WorkInstanceDocument) queryDoc).getId() != null) {
794             query.append("(instanceIdentifier :").append((((WorkInstanceDocument) queryDoc).getId())).append(")");
795 
796 
797         }
798         return query.toString();
799     }
800 
801     private String buildQueryForItemTree(OleDocument queryDoc) {
802         StringBuilder query = new StringBuilder();
803 
804         if (((WorkItemDocument) queryDoc).getId() != null && query.length() > 0) {
805             query.append("(id :").append((((WorkItemDocument) queryDoc).getId())).append(")");
806         } else if (((WorkItemDocument) queryDoc).getId() != null) {
807             query.append("(id :").append((((WorkItemDocument) queryDoc).getId())).append(")");
808 
809 
810         }
811         return query.toString();
812     }
813 
814     private String buildQueryForBibInfo(OleDocument queryDoc) {
815         StringBuilder query = new StringBuilder();
816 
817         if (((WorkBibDocument) queryDoc).getId() != null && query.length() > 0) {
818             query.append("(id :").append((((WorkBibDocument) queryDoc).getId())).append(")");
819         } else if (((WorkBibDocument) queryDoc).getId() != null) {
820             query.append("(id :").append((((WorkBibDocument) queryDoc).getId())).append(")");
821 
822 
823         }
824         return query.toString();
825     }
826 
827     /**
828      * @param queryDoc
829      * @return query
830      *         Usage: Builds query string using OleDocument Data
831      */
832     public String buildQueryForDoc(OleDocument queryDoc) {
833         StringBuilder query = new StringBuilder();
834         if ((((WorkBibDocument) queryDoc).getInstanceDocument() == null)
835                                       || ((WorkBibDocument) queryDoc).getInstanceDocument().getInstanceIdentifier() == null) {
836             if (((WorkBibDocument) queryDoc).getTitle() != null) {
837                 query.append("(Title_display:").append(((WorkBibDocument) queryDoc).getTitle()).append(")");
838             }
839             if (((WorkBibDocument) queryDoc).getAuthor() != null && query.length() > 0) {
840                 query.append("AND (Author_display:").append(((WorkBibDocument) queryDoc).getAuthor()).append(")");
841             } else if (((WorkBibDocument) queryDoc).getAuthor() != null) {
842                 query.append("(Author_display:").append(((WorkBibDocument) queryDoc).getAuthor()).append(")");
843             }
844             if (((WorkBibDocument) queryDoc).getPublicationDate() != null && query.length() > 0) {
845                 query.append("AND (PublicationDate_display:").append(((WorkBibDocument) queryDoc).getPublicationDate()).append(")");
846             } else if (((WorkBibDocument) queryDoc).getPublicationDate() != null) {
847                 query.append("(PublicationDate_display:").append(((WorkBibDocument) queryDoc).getPublicationDate()).append(")");
848             }
849             if (((WorkBibDocument) queryDoc).getIsbn() != null && query.length() > 0) {
850                 query.append("AND (ISBN_display:").append(((WorkBibDocument) queryDoc).getIsbn()).append(")");
851             } else if (((WorkBibDocument) queryDoc).getIsbn() != null) {
852                 query.append("(ISBN_display:").append(((WorkBibDocument) queryDoc).getIsbn()).append(")");
853             }
854             if (((WorkBibDocument) queryDoc).getPublisher() != null && query.length() > 0) {
855                 query.append("AND (Publisher_display:").append(((WorkBibDocument) queryDoc).getPublisher()).append(")");
856             } else if (((WorkBibDocument) queryDoc).getPublisher() != null) {
857                 query.append("(Publisher_display:").append(((WorkBibDocument) queryDoc).getPublisher()).append(")");
858             }
859             if (((WorkBibDocument) queryDoc).getId() != null && query.length() > 0) {
860                 query.append("(id:").append((((WorkBibDocument)queryDoc).getId())).append(")");
861             } else if (((WorkBibDocument) queryDoc).getId() != null) {
862                 query.append("(id:").append((((WorkBibDocument)queryDoc).getId())).append(")");
863 
864             }
865         }
866 
867         else {
868             query.append("(" + DOC_TYPE + ":" + queryDoc.getDocType().getDescription() + ")");
869             if (((WorkBibDocument) queryDoc).getInstanceDocument() != null) {
870                 query.append(" AND ");
871                 String instanseIdentifier = ((WorkBibDocument) queryDoc).getInstanceDocument().getInstanceIdentifier();
872                 query.append("(" + INSTANCE_IDENTIFIER + ":" + instanseIdentifier + ")");
873             }
874         }
875         query.append(
876                 "&fl=id,instanceIdentifier,Title_display,Author_display,PublicationDate_display,ISBN_display,Publisher_display");
877         return query.toString();
878     }
879 
880 
881     /**
882      * @param inputQuery
883      * @return hitsOnPage
884      * @throws Exception Usage: Gets Solr response for input query and builds List of Maps holding Solr Doc Data
885      */
886     public List<Map<String, Object>> getSolrHitsForQuery(String inputQuery) throws Exception {
887         SolrServer server;
888         List<Map<String, Object>> hitsOnPage = new ArrayList<Map<String, Object>>();
889         server = SolrServerManager.getInstance().getSolrServer();
890         SolrQuery solrQuery = new SolrQuery();
891         solrQuery.setQuery(inputQuery);
892         solrQuery.setSortField("Title_sort", SolrQuery.ORDER.asc);
893         solrQuery.setIncludeScore(true);
894         solrQuery.setRows(1000);
895         LOG.info("solr Query -->"+solrQuery.getQuery());
896         QueryResponse queryResponse = server.query(solrQuery);
897         SolrDocumentList solrDocumentList = queryResponse.getResults();
898 
899         for (SolrDocument solrDocument : solrDocumentList) {
900             hitsOnPage.add(solrDocument);
901         }
902         return hitsOnPage;
903     }
904 
905 
906     /**
907      *
908      * @param idList
909      * @param identifierType
910      * @return
911      */
912     @Override
913     public List<String> getUUIDList(List<String> idList, String identifierType) {
914         SolrServer solrServer;
915         SolrQuery solrQuery = new SolrQuery();
916         SolrDocumentList solrDocumentList;
917         String id;
918         StringBuilder builder = new StringBuilder();
919         List<String> uuidList = new ArrayList<String>();
920         String searchField = null;
921         if (identifierType.equalsIgnoreCase("SCN")) {
922             searchField = WorkBibCommonFields.SYSTEM_CONTROL_NUMBER + ":";
923         } else if (identifierType.equalsIgnoreCase("ISBN")) {
924             searchField = WorkBibCommonFields.ISBN_SEARCH + ":";
925         }
926         try {
927             solrServer = SolrServerManager.getInstance().getSolrServer();
928             for (String ssn : idList) {
929                 if (builder.length() > 0) {
930                     builder.append(" OR " );
931                 }
932                 builder.append("(");
933                 builder.append(searchField);
934                 builder.append(ssn);
935                 builder.append(")");
936             }
937 
938             LOG.debug("query-->"+builder.toString());
939             solrQuery.setQuery(builder.toString());
940             LOG.debug("solr query-->" + solrQuery);
941             QueryResponse response = solrServer.query(solrQuery);
942             solrDocumentList = response.getResults();
943             for (SolrDocument solrDocument : solrDocumentList) {
944                 id = (String) solrDocument.getFieldValue("id");
945                 LOG.debug("id-->" + id);
946                 uuidList.add(id);
947             }
948 
949         } catch (SolrServerException e) {
950 
951         }
952         return uuidList;
953     }
954 
955     /**
956      * This method returns the list of titles based on the given search value.
957      * @param fieldValue
958      * @return
959      */
960    @Override
961    public List<String> getTitleValues(String fieldValue) {
962        SolrServer solrServer;
963        SolrQuery solrQuery = new SolrQuery();
964        SolrDocumentList solrDocumentList;
965        Object title;
966        StringBuilder builder = new StringBuilder();
967        List<String> titleList = new ArrayList<String>();
968        String searchField = null;
969        searchField = WorkBibCommonFields.TITLE_SEARCH + ":";
970        try {
971            solrServer = SolrServerManager.getInstance().getSolrServer();
972            builder.append("(");
973            builder.append("DocType");
974            builder.append(":");
975            builder.append("bibliographic");
976            builder.append(")");
977            builder.append("AND");
978            builder.append("(");
979            builder.append("(");
980            builder.append(searchField);
981            builder.append("(");
982            builder.append(fieldValue);
983            builder.append(")");
984            builder.append(")");
985            builder.append(")");
986            LOG.debug("query-->" + builder.toString());
987            solrQuery.setQuery(builder.toString());
988            LOG.info("solr query-->" + solrQuery);
989            QueryResponse response = solrServer.query(solrQuery);
990            solrDocumentList = response.getResults();
991            for (SolrDocument solrDocument : solrDocumentList) {
992                title = solrDocument.getFieldValue("Title_search");
993                LOG.debug("title-->" + title);
994                if (title instanceof List) {
995                    titleList.addAll((Collection<? extends String>) title);
996                } else {
997                    titleList.add(title.toString());
998                }
999            }
1000 
1001        } catch (SolrServerException e) {
1002 
1003        }
1004        return titleList;
1005 
1006    }
1007 
1008     public String buildQuery(SearchParams searchParams) {
1009         StringBuffer query = new StringBuffer();
1010         buildInitialQuery(query, searchParams);
1011         if (searchParams.getSearchFieldsList().size() > 0) {
1012             query.append("AND(");
1013         }
1014         query.append(buildQueryWithSearchParameters(searchParams.getSearchFieldsList()));
1015         if (searchParams.getResultPageSize() != null) {
1016             query.append("&rows=" + searchParams.getResultPageSize());
1017         }
1018         if (searchParams.getResultFromIndex() != null) {
1019             query.append("&start=" + searchParams.getResultFromIndex());
1020         }
1021         query.append(buildQueryWithSortFields(searchParams.getSortField(), searchParams.getSortOrder()));
1022         query.append(buildQueryWithFieldListParameters(searchParams.getFieldList()));
1023         return query.toString();
1024     }
1025 
1026     /**
1027      * @param query
1028      * @param searchParams Usage: This method builds initial SOLR query with DocType and DocFormat as SolrParams
1029      */
1030     private void buildInitialQuery(StringBuffer query, SearchParams searchParams) {
1031 
1032         query.append("(DocType:" + searchParams.getDocType() + ")");
1033 
1034         /*  if (searchParams.getDocFormat().equalsIgnoreCase("marc")) {
1035             query.append("((DocType:" + searchParams.getDocType() + ")" + "OR(DocType:item))");
1036         }
1037         else {
1038             query.append("(DocType:" + searchParams.getDocType() + ")");
1039         }*/
1040 
1041         if (searchParams.getDocFormat() != null && !searchParams.getDocFormat().equalsIgnoreCase("all")) {
1042             query.append("AND(DocFormat:" + searchParams.getDocFormat() + ")");
1043         }
1044     }
1045 
1046     public String buildQueryWithSearchParameters(List<SearchCondition> searchFieldsList) {
1047         SearchCondition docSearchFieldsDTO = null;
1048         StringBuffer queryStringbuffer = new StringBuffer();
1049         StringBuffer highlightBuffer = new StringBuffer("&hl.fl=");
1050         if (searchFieldsList != null && searchFieldsList.size() > 0) {
1051             for (int i = 0; i < searchFieldsList.size(); i++) {
1052                 int searchScopeAddLimit = i;
1053                 docSearchFieldsDTO = searchFieldsList.get(i);
1054                 if (docSearchFieldsDTO.getOperator() != null) {
1055                     // queryStringbuffer.append(docSearchFieldsDTO.getOperator());
1056                 }
1057                 queryStringbuffer.append("(");
1058                 if (docSearchFieldsDTO.getDocField().equalsIgnoreCase("all") || (
1059                         docSearchFieldsDTO.getDocField() == null || docSearchFieldsDTO.getDocField().length() == 0)) {
1060                     queryStringbuffer.append("all_text");
1061                     highlightBuffer.append("*");
1062 
1063                 }
1064                 else {
1065                     queryStringbuffer.append(docSearchFieldsDTO.getDocField());
1066                     highlightBuffer.append(docSearchFieldsDTO.getDocField());
1067 
1068                     if (i != searchFieldsList.size() - 1) {
1069                         highlightBuffer.append(",");
1070                     }
1071                 }
1072                 queryStringbuffer.append(":");
1073                 String searchScope = docSearchFieldsDTO.getSearchScope();
1074                 String searchText = docSearchFieldsDTO.getSearchText();
1075                 String operator = docSearchFieldsDTO.getOperator();
1076                 if (searchText.equalsIgnoreCase("")) {
1077                     searchText = "(*:*)";
1078                 }
1079                 else {
1080                     searchText = searchText.toLowerCase();
1081                     searchText = searchText.replaceAll("[~!(){}\\[\\]':-]+", " ");
1082                     searchText.replaceAll(" ", "+");
1083                 }
1084                 LOG.debug("searchText-->" + searchText);
1085                 String searchTextVal = null;
1086                 if (searchText.length() > 0) {
1087                     queryStringbuffer.append("(");
1088                     if (searchScope.equalsIgnoreCase("AND")) {
1089                         searchText = searchText.replaceAll("\\s+", " ");
1090                         searchTextVal = searchText.trim().replace(" ", " AND ");
1091                     }
1092                     else if (searchScope.equalsIgnoreCase("OR")) {
1093                         searchText = searchText.replaceAll("\\s+", " ");
1094                         searchTextVal = searchText.trim().replace(" ", " OR ");
1095                     }
1096                     else if (searchScope.equalsIgnoreCase("phrase")) {
1097                         searchTextVal = "\"" + searchText + "\"";
1098                     }
1099                     /* try {
1100                         searchTextVal = URLEncoder.encode(searchTextVal, "UTF-8");
1101                     }
1102                     catch (UnsupportedEncodingException e) {
1103                         e.printStackTrace();
1104                     }*/
1105                     queryStringbuffer.append(searchTextVal);
1106                     LOG.debug("searchTextVal............" + searchTextVal + "........" + queryStringbuffer.toString());
1107                     queryStringbuffer.append(")");
1108                 }
1109                 queryStringbuffer.append(")");
1110                 ++searchScopeAddLimit;
1111                 if (operator == null) {
1112                     break;
1113                 }
1114                 if (searchScopeAddLimit != searchFieldsList.size()) {
1115                     queryStringbuffer.append(operator);
1116                 }
1117             }
1118             queryStringbuffer.append(")");
1119             queryStringbuffer.append(highlightBuffer.toString());
1120 
1121             queryStringbuffer.append("&hl=true");
1122         }
1123         return queryStringbuffer.toString();
1124     }
1125 
1126     public String buildQueryWithSortFields(String sortField, String sortOrder) {
1127         StringBuffer sortFieldsQuery = new StringBuffer();
1128         if (null != sortField) {
1129             sortFieldsQuery.append("&");
1130             sortFieldsQuery.append("sort=");
1131             sortFieldsQuery.append(sortField);
1132             if (null != sortOrder) {
1133                 sortFieldsQuery.append(" ");
1134                 sortFieldsQuery.append(sortOrder);
1135             }
1136         }
1137         return sortFieldsQuery.toString();
1138     }
1139 
1140     public String buildQueryWithFieldListParameters(List<String> fieldsList) {
1141         String queryWithFieldListParameters = "";
1142         if (fieldsList != null) {
1143             StringBuffer fieldsListQueryStringbuffer = new StringBuffer();
1144             fieldsListQueryStringbuffer.append("&");
1145             fieldsListQueryStringbuffer.append("fl=");
1146             for (int i = 0; i < fieldsList.size(); i++) {
1147                 fieldsListQueryStringbuffer.append(fieldsList.get(i));
1148                 fieldsListQueryStringbuffer.append(",");
1149             }
1150             queryWithFieldListParameters = fieldsListQueryStringbuffer
1151                     .substring(0, fieldsListQueryStringbuffer.length() - 1);
1152         }
1153         return queryWithFieldListParameters;
1154     }
1155 
1156     /**
1157      * Prepares the solr query based on user input values location, classification and call number browse text
1158      * Calculates totalCallNumberCount and totalForwardCallNumberCount based on solr query results
1159      * Evaluates matchIndex based on totalCallNumberCount and totalForwardCallNumberCount
1160      *
1161      * @param callNumberBrowseParams contains required parameters for call number browse functionality
1162      * @throws Exception
1163      */
1164     public void initCallNumberBrowse(CallNumberBrowseParams callNumberBrowseParams) throws Exception {
1165         int matchIndex = 0;
1166         int totalCallNumberCount = 0;
1167         int totalForwardCallNumberCount = 0;
1168         String location = callNumberBrowseParams.getLocation();
1169         String classificationScheme = callNumberBrowseParams.getClassificationScheme();
1170         String callNumberBrowseText = callNumberBrowseParams.getCallNumberBrowseText();
1171         String docType=callNumberBrowseParams.getDocTye();
1172         if (StringUtils.isNotEmpty(classificationScheme)) {
1173             String queryString = buildQueryForTotalCallNumberCount(location, classificationScheme,docType);
1174             List<Map<String, Object>> solrHits;
1175             totalCallNumberCount = getSolrHitsForCallNumberBrowse(queryString);
1176             LOG.info("Total Call Number count:" + totalCallNumberCount);
1177 
1178             if (StringUtils.isNotEmpty(callNumberBrowseText)) {
1179                 CallNumber callNumber = CallNumberFactory.getInstance().getCallNumber(classificationScheme);
1180                 String normalizedCallNumberBrowseText = callNumber.getSortableKey(callNumberBrowseText);
1181                 normalizedCallNumberBrowseText = normalizedCallNumberBrowseText.replaceAll(" ", "-");
1182 
1183                 queryString = buildQueryForTotalForwardCallNumberCount(location, classificationScheme, normalizedCallNumberBrowseText,docType);
1184                 totalForwardCallNumberCount = getSolrHitsForCallNumberBrowse(queryString);
1185             }
1186             else
1187                 totalForwardCallNumberCount=totalCallNumberCount;
1188         }
1189 
1190         LOG.info("Total Forward Call Number Count:" + totalForwardCallNumberCount);
1191         matchIndex = (totalCallNumberCount - totalForwardCallNumberCount) + 1;
1192         callNumberBrowseParams.setMatchIndex(matchIndex);
1193         callNumberBrowseParams.setTotalCallNumberCount(totalCallNumberCount);
1194         callNumberBrowseParams.setTotalForwardCallNumberCount(totalForwardCallNumberCount);
1195     }
1196 
1197     /**
1198      * Used to display closest record based on input fields classification, rows and start index
1199      *
1200      * @param callNumberBrowseParams contains required parameters for call number browse functionality
1201      * @return
1202      * @throws Exception
1203      */
1204     public List<WorkBibDocument> browseCallNumbers(CallNumberBrowseParams callNumberBrowseParams) throws Exception {
1205         List<WorkBibDocument> workBibDocuments=new ArrayList<WorkBibDocument>();
1206         if (StringUtils.isNotEmpty(callNumberBrowseParams.getClassificationScheme())) {
1207             int startIndex = callNumberBrowseParams.getStartIndex();
1208             if (startIndex > 0) {
1209                 startIndex = startIndex - 1;
1210             }
1211             String queryString = buildQueryForBrowseCallNumbers(callNumberBrowseParams.getLocation(), callNumberBrowseParams.getClassificationScheme(), callNumberBrowseParams.getNumRows(), startIndex,callNumberBrowseParams.getDocTye());
1212             List<Map<String, Object>> solrHits;
1213             solrHits = getSolrHitsForCallNumberBrowse(queryString, startIndex, callNumberBrowseParams.getNumRows());
1214             List<WorkItemDocument> workItemDocuments = buildWorkItemDocuments(solrHits);
1215             buildItemCallNumber(workItemDocuments);
1216             workBibDocuments = getWorkBibDocuments(workItemDocuments);
1217             LOG.info("Before Merging");
1218             LOG.info("Item list size:" + workItemDocuments.size());
1219             LOG.info("Bib list size:" + workBibDocuments.size());
1220             workBibDocuments = mergeBibAndItemDocuments(workItemDocuments, workBibDocuments);
1221             LOG.info("After Merging");
1222             LOG.info("Item list size:" + workItemDocuments.size());
1223             LOG.info("Bib list size:" + workBibDocuments.size());
1224         }
1225         return workBibDocuments;
1226     }
1227 
1228     /**
1229      * Merges the item documents with corresponding Bib document.
1230      * The main intention is to make equal count for both Item and Bib documents.
1231      *
1232      * @param workItemDocumentList contains list of Item records
1233      * @param workBibDocumentList  contains list of Bib records.
1234      * @return
1235      */
1236     public List<WorkBibDocument> mergeBibAndItemDocuments(List<WorkItemDocument> workItemDocumentList, List<WorkBibDocument> workBibDocumentList) {
1237 
1238         List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
1239         for (WorkItemDocument workItemDocument : workItemDocumentList) {
1240 //            WorkBibDocument workBibDocument=new WorkBibDocument();
1241             for (WorkBibDocument workBibDoc : workBibDocumentList) {
1242                 WorkBibDocument workBibDocument = new WorkBibDocument();
1243                 if (workBibDoc.getId().equals(workItemDocument.getBibIdentifier())) {
1244                     //workBibDocument = workBibDoc;
1245                     workBibDocument.setAuthor(workBibDoc.getAuthor());
1246                     workBibDocument.setTitle(workBibDoc.getTitle());
1247                     workBibDocument.setId(workBibDoc.getId());
1248                     workBibDocument.setDocFormat(workBibDoc.getDocFormat());
1249                     workBibDocument.setInstanceIdentifier(workBibDoc.getInstanceIdentifier());
1250                     List<WorkInstanceDocument> workInstanceDocuments = new ArrayList<WorkInstanceDocument>();
1251                     WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
1252                     List<WorkItemDocument> workitemDocuments = new ArrayList<WorkItemDocument>();
1253                     workitemDocuments.add(workItemDocument);
1254                     workInstanceDocument.setItemDocumentList(workitemDocuments);
1255                     workInstanceDocuments.add(workInstanceDocument);
1256                     workBibDocument.setWorkInstanceDocumentList(workInstanceDocuments);
1257                     workBibDocuments.add(workBibDocument);
1258                     break;
1259                 }
1260             }
1261 
1262         }
1263         return workBibDocuments;
1264     }
1265 
1266     /**
1267      * Prepares a list of Bib records based on available Item records.
1268      *
1269      * @param workItemDocuments contains list of Item documents
1270      * @return
1271      * @throws Exception
1272      */
1273     public List<WorkBibDocument> getWorkBibDocuments(List<WorkItemDocument> workItemDocuments) throws Exception {
1274         List<WorkBibDocument> workBibDocumentList = new ArrayList<WorkBibDocument>();
1275         if (workItemDocuments.size() <= 0)
1276             return workBibDocumentList;
1277         String queryString = buildQueryForBib(workItemDocuments);
1278         List<Map<String, Object>> solrHits = getSolrHitsForQuery(queryString);
1279         workBibDocumentList = buildWorkBibDocuments(solrHits);
1280         return workBibDocumentList;
1281     }
1282 
1283     /**
1284      * Building solr query with list of Item records
1285      * The solr query is used to get Bib records.
1286      *
1287      * @param workItemDocumentList contains list of Item records
1288      * @return the solr query for Bib records
1289      */
1290     public String buildQueryForBib(List<WorkItemDocument> workItemDocumentList) {
1291         if (workItemDocumentList != null && workItemDocumentList.size() > 0) {
1292             StringBuilder query = new StringBuilder();
1293             StringBuilder idQuery = new StringBuilder();
1294             query.append("(DocType:Bibliographic) AND");
1295             int i = 0;
1296             for (; i < workItemDocumentList.size() - 1; i++) {
1297                 idQuery.append(("(id:" + workItemDocumentList.get(i).getBibIdentifier()) + ") OR ");
1298             }
1299             idQuery.append("(id:" + workItemDocumentList.get(i).getBibIdentifier() + ")");
1300             if (idQuery.length() > 0)
1301                 query.append("(" + idQuery + ")");
1302             return query.toString();
1303         }
1304         return null;
1305     }
1306 
1307 
1308     /**
1309      * Preparing solr query based on user input fields location and classification scheme.
1310      *
1311      * @param location             contains user input location
1312      * @param classificationScheme user input classification
1313      * @return solr query for total call number count
1314      */
1315     public String buildQueryForTotalCallNumberCount(String location, String classificationScheme,String docType) {
1316         StringBuffer query = new StringBuffer();
1317         query.append("(DocCategory:work)AND(DocType:"+docType+")AND(DocFormat:oleml)");
1318         if (StringUtils.isNotEmpty(location))
1319             query.append("AND (LocationLevel_search:" + location + ")");
1320         if (StringUtils.isNotEmpty(classificationScheme))
1321             query.append("AND(ShelvingSchemeCode_search:" + classificationScheme + ")");
1322         query.append("AND (ShelvingOrder_sort:{* TO *})");
1323         query.append("&sort=ShelvingOrder_sort asc");
1324         return query.toString();
1325     }
1326 
1327     /**
1328      * Building solr query for getting Item/Holdings records with call number
1329      *
1330      * @param location             the Item/Holdings location
1331      * @param classificationScheme the Item/Holdings classification
1332      * @param numRows              the number of rows for displaying results
1333      * @param startIndex           index used to specify the
1334      * @return the solr query for browse call numbers.
1335      */
1336     public String buildQueryForBrowseCallNumbers(String location, String classificationScheme, int numRows, int startIndex,String docType) {
1337         StringBuffer query = new StringBuffer();
1338         String queryString = buildCommonQueryForForwardCallNumber(location, classificationScheme, "",docType);
1339         query.append(queryString);
1340         query.append("&fl=");
1341         // query.append("CallNumber_display,ShelvingSchemeCode_display,bibIdentifier,id");
1342         query.append("CallNumber_display,bibIdentifier,id");
1343         query.append("&rows=" + numRows + "&start=" + startIndex);
1344         query.append("&sort=ShelvingOrder_sort asc");
1345         return query.toString();
1346     }
1347 
1348     /**
1349      * @param location             the Item/Holdings location.
1350      * @param classificationScheme the Item/Holdings classification.
1351      * @param callNumberBrowseText the user input field callNumberBrowseText.
1352      * @return the solr query for getting forward call number count.
1353      */
1354     public String buildQueryForTotalForwardCallNumberCount(String location, String classificationScheme, String callNumberBrowseText,String docType) {
1355         StringBuffer query = new StringBuffer();
1356         String queryString = buildCommonQueryForForwardCallNumber(location, classificationScheme, callNumberBrowseText,docType);
1357         query.append(queryString);
1358         return query.toString();
1359     }
1360 
1361     /**
1362      * @param location             the Item/Holdings location
1363      * @param classificationScheme the Item/Holdings classification
1364      * @param callNumberBrowseText the user input field callNumberBrowseText.
1365      * @return solr query
1366      */
1367     public String buildCommonQueryForForwardCallNumber(String location, String classificationScheme, String callNumberBrowseText,String docType) {
1368         StringBuffer query = new StringBuffer();
1369         //TODO: Supporting other DocType
1370         query.append("(DocCategory:work)AND(DocType:"+docType+")AND(DocFormat:oleml)");
1371         if (StringUtils.isNotEmpty(location))
1372             query.append("AND (LocationLevel_search:" + location + ")");
1373         if (StringUtils.isNotEmpty(classificationScheme))
1374             query.append("AND(ShelvingSchemeCode_search:" + classificationScheme + ")");
1375         if (StringUtils.isNotEmpty(callNumberBrowseText))
1376             query.append("AND (ShelvingOrder_sort:{\"" + callNumberBrowseText + "*\" TO *})");
1377         else
1378             query.append("AND (ShelvingOrder_sort:{* TO *})");
1379         return query.toString();
1380     }
1381 
1382     public List<WorkBibDocument> getWorkBibRecords(List<LinkedHashMap<String,String>> uuidsMapList) throws Exception {
1383         List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
1384         for(LinkedHashMap<String,String> uuidsMap : uuidsMapList){
1385             WorkBibDocument workBibDocument = new WorkBibDocument();
1386             if(uuidsMap.containsKey(DocType.BIB.getDescription())){
1387                 String bibId = uuidsMap.get(DocType.BIB.getDescription());
1388                 if(LOG.isInfoEnabled()) {
1389                     LOG.info(" bibId ---------------> " + bibId);
1390                 }
1391                 workBibDocument.setId(bibId.toString());
1392                 workBibDocument = queryForBibTree(workBibDocument);
1393             }
1394             else if(uuidsMap.containsKey(DocType.INSTANCE.getDescription())) {
1395                 WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
1396                 List<WorkInstanceDocument> workInstanceDocuments = new ArrayList<WorkInstanceDocument>();
1397                 String instanceId = uuidsMap.get(DocType.INSTANCE.getDescription());
1398                 if(LOG.isInfoEnabled()) {
1399                     LOG.info(" instanceId ---------------> " + instanceId);
1400                 }
1401                 workInstanceDocument.setId(instanceId.toString());
1402                 workInstanceDocument.setInstanceIdentifier(instanceId.toString());
1403                 workInstanceDocument = queryForInstanceTree(workInstanceDocument);
1404                 workInstanceDocuments.add(workInstanceDocument);
1405                 workBibDocument.setId(workInstanceDocument.getBibIdentifier());
1406                 workBibDocument.setWorkInstanceDocumentList(workInstanceDocuments);
1407                 workBibDocument = queryForBibTree(workBibDocument);
1408             }
1409             else if(uuidsMap.containsKey(DocType.ITEM.getDescription())) {
1410                 WorkItemDocument workItemDocument = new WorkItemDocument();
1411                 List<WorkInstanceDocument> workInstanceDocuments = new ArrayList<WorkInstanceDocument>();
1412                 List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
1413                 WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
1414                 String itemId = uuidsMap.get(DocType.ITEM.getDescription());
1415                 if(LOG.isInfoEnabled()) {
1416                     LOG.info(" itemId ---------------> " + itemId);
1417                 }
1418                 workItemDocument.setId(itemId.toString());
1419                 workItemDocument = queryForItemTree(workItemDocument);
1420                 workItemDocumentList.add(workItemDocument);
1421                 workInstanceDocument.setItemDocumentList(workItemDocumentList);
1422                 workInstanceDocument.setId(workItemDocument.getInstanceIdentifier());
1423                 //workInstanceDocument = queryForInstanceTree(workInstanceDocument);
1424                 workInstanceDocuments.add(workInstanceDocument);
1425                 workBibDocument.setId(workItemDocument.getBibIdentifier());
1426                 workBibDocument.setWorkInstanceDocumentList(workInstanceDocuments);
1427                 workBibDocument = queryForBibTree(workBibDocument);
1428             }
1429             else if(uuidsMap.containsKey(DocType.HOLDINGS.getDescription())){
1430                 WorkHoldingsDocument workHoldingsDocument = new WorkHoldingsDocument();
1431                 List<WorkInstanceDocument> workInstanceDocuments = new ArrayList<WorkInstanceDocument>();
1432                 WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
1433                 String holdingsId = uuidsMap.get(DocType.HOLDINGS.getDescription());
1434                 if(LOG.isInfoEnabled()) {
1435                     LOG.info(" holdingsId ---------------> " + holdingsId);
1436                 }
1437                 workHoldingsDocument.setHoldingsIdentifier(holdingsId);
1438                 workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
1439                 workInstanceDocument = queryForInstanceTree(workInstanceDocument);
1440                 workInstanceDocuments.add(workInstanceDocument);
1441                 workBibDocument.setId(workInstanceDocument.getBibIdentifier());
1442                 workBibDocument.setWorkInstanceDocumentList(workInstanceDocuments);
1443                 workBibDocument = queryForBibTree(workBibDocument);
1444             }
1445             workBibDocuments.add(workBibDocument);
1446         }
1447         return workBibDocuments;
1448     }
1449 
1450     /**
1451      * @param inputQuery input query
1452      * @param start      start index
1453      * @param numRows    the number of rows for displaying results
1454      * @return the list of solr hits for call number browse
1455      * @throws Exception
1456      */
1457     public List<Map<String, Object>> getSolrHitsForCallNumberBrowse(String inputQuery, int start, int numRows) throws Exception {
1458         SolrServer server;
1459         List<Map<String, Object>> hitsOnPage = new ArrayList<Map<String, Object>>();
1460         server = SolrServerManager.getInstance().getSolrServer();
1461         SolrQuery solrQuery = new SolrQuery();
1462         solrQuery.setQuery(inputQuery);
1463         solrQuery.setIncludeScore(true);
1464         solrQuery.setRows(numRows);
1465         solrQuery.setStart(start);
1466         solrQuery.setSortField("ShelvingOrder_sort", SolrQuery.ORDER.asc);
1467         LOG.info("solr Query -->" + solrQuery.getQuery());
1468         QueryResponse queryResponse = server.query(solrQuery);
1469         SolrDocumentList solrDocumentList = queryResponse.getResults();
1470 
1471         for (SolrDocument solrDocument : solrDocumentList) {
1472             hitsOnPage.add(solrDocument);
1473         }
1474         return hitsOnPage;
1475     }
1476 
1477     public int getSolrHitsForCallNumberBrowse(String inputQuery) throws Exception {
1478         SolrServer server;
1479         List<Map<String, Object>> hitsOnPage = new ArrayList<Map<String, Object>>();
1480         server = SolrServerManager.getInstance().getSolrServer();
1481         SolrQuery solrQuery = new SolrQuery();
1482         solrQuery.setQuery(inputQuery);
1483         solrQuery.setIncludeScore(true);
1484         solrQuery.setRows(0);
1485         solrQuery.setSortField("ShelvingOrder_sort", SolrQuery.ORDER.asc);
1486         LOG.info("solr Query -->"+solrQuery.getQuery());
1487         QueryResponse queryResponse = server.query(solrQuery);
1488         int numFound= (int)queryResponse.getResults().getNumFound();
1489         return numFound;
1490     }
1491 
1492     /**
1493      * Verify solr for the field and return true if exists (Ingest)
1494      * Verify solr for the field other updating record (Update)
1495      * @param docType
1496      * @param field
1497      * @param value
1498      * @param id
1499      * @return
1500      * @throws Exception
1501      */
1502     public boolean isFieldValueExists(String docType, String field, String value, String id) throws Exception {
1503         String queryString = "(DocType:" + docType + ")AND(" + field + ":" + value + ")";
1504         QueryResponse queryResponse = getSolrResponse(queryString, field);
1505         long i = queryResponse.getResults().getNumFound();
1506         // verify barcode while updating an item
1507         if (id != null) {
1508             if (i == 1) {      // verify the result record id with given id.
1509                 SolrDocumentList solrDocumentList = queryResponse.getResults();
1510                 for (SolrDocument solrDocument : solrDocumentList) {
1511                     if (!id.equalsIgnoreCase(solrDocument.getFieldValue("id").toString())) {
1512                         return true;   // other record is having barcode value
1513                     }
1514                 }
1515             } else if (i > 1) {
1516                 return true;   // other records having same barcode value.
1517             }
1518         } else if (i > 0) {    // verify barcode while ingesting an item.
1519             return true;
1520         }
1521         return false;
1522     }
1523 
1524     private QueryResponse getSolrResponse(String queryString, String field) throws SolrServerException {
1525         SolrQuery solrQuery = new SolrQuery();
1526         SolrServer server = SolrServerManager.getInstance().getSolrServer();
1527         solrQuery.setQuery(queryString);
1528         solrQuery.setRows(500);
1529         solrQuery.setFields("id");
1530         return server.query(solrQuery);
1531     }
1532 
1533 
1534     /**
1535      * Append 'Enumeration', 'Chronology' and 'Copy Number' to item call number based on their availability.
1536      *
1537      * @param itemDocuments
1538      */
1539     public void buildItemCallNumber(List<WorkItemDocument> itemDocuments) {
1540         String itemCallNumber = "";
1541         for (WorkItemDocument workItemDocument : itemDocuments) {
1542             itemCallNumber = workItemDocument.getCallNumber();
1543             if (StringUtils.isNotEmpty(itemCallNumber)) {
1544                 itemCallNumber = itemCallNumber + " " + StringUtils.trimToEmpty(workItemDocument.getEnumeration()) + " "
1545                                  + StringUtils.trimToEmpty(workItemDocument.getChronology()) + " " + StringUtils
1546                         .trimToEmpty(workItemDocument.getCopyNumber());
1547 
1548             }
1549             workItemDocument.setCallNumber(itemCallNumber);
1550         }
1551     }
1552 
1553 
1554 
1555     public List retriveResults(String queryString) {
1556         CommonsHttpSolrServer server = null;
1557         ArrayList<HashMap<String, Object>> hitsOnPage = new ArrayList<HashMap<String, Object>>();
1558         try {
1559             String serverUrl = PropertyUtil.getPropertyUtil().getProperty("ole.docstore.url.base")+"/bib";
1560             server = new CommonsHttpSolrServer(serverUrl);
1561         } catch (Exception e) {
1562             e.printStackTrace();
1563         }
1564         SolrQuery query = new SolrQuery();
1565         query.setQuery(queryString);
1566         query.setIncludeScore(true);
1567         try {
1568             QueryResponse qr = server.query(query);
1569 
1570             SolrDocumentList sdl = qr.getResults();
1571 
1572 
1573             for (SolrDocument d : sdl) {
1574                 HashMap<String, Object> values = new HashMap<String, Object>();
1575 
1576                 for (Iterator<Map.Entry<String, Object>> i = d.iterator(); i.hasNext(); ) {
1577                     Map.Entry<String, Object> e2 = i.next();
1578 
1579                     values.put(e2.getKey(), e2.getValue());
1580                 }
1581 
1582                 hitsOnPage.add(values);
1583             }
1584         } catch (SolrServerException e) {
1585             e.printStackTrace();
1586         }
1587         return hitsOnPage;
1588     }
1589 
1590 
1591    /**
1592      * Retrieve instance,item and bib uuid using item barcode or item uuid.
1593      * @param itemBarcode
1594      * @return  Map
1595      */
1596     public Map getItemDetails(String itemBarcode,String itemUUID) throws Exception{
1597         LOG.debug("Inside the getItemDetails method");
1598 
1599         HashMap itemAndTitleDetails = new HashMap();
1600         HashMap<String, Object> itemvalues = new HashMap<String, Object>();
1601         try {
1602             if(itemBarcode != null && !"".equals(itemBarcode)){
1603                 List<HashMap<String, Object>> documentList= retriveResults("ItemBarcode_display:" + itemBarcode);
1604                 itemvalues = documentList.get(0);
1605                 itemAndTitleDetails.put("instanceUuid",(String)((ArrayList)itemvalues.get("instanceIdentifier")).get(0));
1606                 itemAndTitleDetails.put("itemUuid",(String)((ArrayList)itemvalues.get("ItemIdentifier_display")).get(0));
1607                 if(itemvalues.get("bibIdentifier")!= null){
1608                     itemAndTitleDetails.put("bibUuid",(String)((ArrayList)itemvalues.get("bibIdentifier")).get(0));
1609                 }
1610             }else{
1611                 List<HashMap<String, Object>> documentList= retriveResults("id:" + itemUUID);
1612                 itemvalues = documentList.get(0);
1613                 itemAndTitleDetails.put("instanceUuid",(String)((ArrayList)itemvalues.get("instanceIdentifier")).get(0));
1614                 itemAndTitleDetails.put("itemUuid",(String)((ArrayList)itemvalues.get("ItemIdentifier_display")).get(0));
1615                 if(itemvalues.get("bibIdentifier")!= null){
1616                     itemAndTitleDetails.put("bibUuid",(String)((ArrayList)itemvalues.get("bibIdentifier")).get(0));
1617                 }
1618 
1619             }
1620             return itemAndTitleDetails;
1621         }
1622         catch (Exception e) {
1623             LOG.error("Item barcode does not exist.");
1624             throw new Exception("Item barcode does not exist.");
1625         }
1626     }
1627 
1628     /**
1629      * Retrieve title and author from docstore using solr query.
1630      * @param bibUuid
1631      * @return
1632      * @throws Exception
1633      */
1634     public Map getTitleAndAuthorfromBib(String bibUuid) throws Exception{
1635         LOG.debug("Inside the getTitleAndAuthorfromBib method");
1636         Map<String,String> bibInformationMap = new HashMap<String, String>();
1637         try{
1638             List<HashMap<String, Object>> bibDocumentList= QueryServiceImpl.getInstance().retriveResults("id:"+bibUuid);
1639             HashMap<String, Object> bibvalues = bibDocumentList.get(0);
1640             bibInformationMap.put("title", (String) ((ArrayList) bibvalues.get("245a")).get(0));
1641             if(bibvalues.get("100a")!=null)
1642                 bibInformationMap.put("author",(String)((ArrayList)bibvalues.get("100a")).get(0));
1643             else
1644                 bibInformationMap.put("author","No Author");
1645             return bibInformationMap;
1646         }catch (Exception e){
1647             LOG.error("Title does not exist.");
1648             throw new Exception("Title does not exist.");
1649         }
1650     }
1651 
1652 
1653     public Map<String, String> getBibInformation(String bibIdentifier,Map<String, String> searchCriteria) {
1654 
1655         HashMap bibDetails = new HashMap();
1656         String title=(String)searchCriteria.get("title");
1657         String author=(String)searchCriteria.get("author");
1658         String publisher=(String)searchCriteria.get("publisher");
1659 
1660         StringBuffer solrQuery=new StringBuffer();
1661         solrQuery.append("(id:"+bibIdentifier+") AND ");
1662 
1663         if(title!=null && !title.equals(""))
1664             solrQuery.append("(Title_search:"+title.toLowerCase()+"*) AND ");
1665         if(author !=null && !author.equals(""))
1666             solrQuery.append("(Author_search:"+author.toLowerCase()+"*) AND ");
1667         if(publisher!=null && !publisher.equals(""))
1668             solrQuery.append("(Publisher_search:"+publisher.toLowerCase()+"*) AND");
1669 
1670         String query=solrQuery.substring(0,solrQuery.lastIndexOf("AND"));
1671 
1672         List<HashMap<String, Object>> documentList= retriveResults("(DocType:bibliographic) AND ("+query+")");
1673         if(documentList.size()>0){
1674             HashMap<String, Object> itemvalues = documentList.get(0);
1675             if(itemvalues.get("Title_display")!=null)
1676                 bibDetails.put("Title",(String)((ArrayList)itemvalues.get("Title_display")).get(0));
1677             else  if(itemvalues.get("Title_search")!=null)
1678                 bibDetails.put("Title",(String)((ArrayList)itemvalues.get("Title_search")).get(0));
1679             if(itemvalues.get("Author_display")!=null)
1680                 bibDetails.put("Author",(String)((ArrayList)itemvalues.get("Author_display")).get(0));
1681             else if(itemvalues.get("Author_search")!=null)
1682                 bibDetails.put("Author",(String)((ArrayList)itemvalues.get("Author_search")).get(0));
1683             if(itemvalues.get("Publisher_display")!=null)
1684                 bibDetails.put("Publisher",(String)((ArrayList)itemvalues.get("Publisher_display")).get(0));
1685             else if(itemvalues.get("Publisher_search")!=null)
1686                 bibDetails.put("Publisher",(String)((ArrayList)itemvalues.get("Publisher_search")).get(0));
1687         }
1688 
1689         if((title!=null && !title.equals("")) || (author!=null &&!author.equals("")) || (publisher!=null && !publisher.equals("")))
1690             if(bibDetails!=null && bibDetails.isEmpty())
1691                 return null;
1692 
1693         return bibDetails;
1694 
1695     }
1696 
1697     /**
1698      *     This method is for item search in deliver
1699      * @param queryString
1700      * @param rowSize
1701      * @return
1702      */
1703     public List retriveResults(String queryString,int rowSize) {
1704         CommonsHttpSolrServer server = null;
1705         ArrayList<HashMap<String, Object>> hitsOnPage = new ArrayList<HashMap<String, Object>>();
1706         try {
1707             String serverUrl = PropertyUtil.getPropertyUtil().getProperty("ole.docstore.url.base")+"/bib";
1708             server = new CommonsHttpSolrServer(serverUrl);
1709         } catch (Exception e) {
1710             e.printStackTrace();
1711         }
1712         SolrQuery query = new SolrQuery();
1713         query.setQuery(queryString);
1714         query.setIncludeScore(true);
1715         query.setRows(rowSize);
1716         try {
1717             QueryResponse qr = server.query(query);
1718 
1719             SolrDocumentList sdl = qr.getResults();
1720 
1721 
1722             for (SolrDocument d : sdl) {
1723                 HashMap<String, Object> values = new HashMap<String, Object>();
1724 
1725                 for (Iterator<Map.Entry<String, Object>> i = d.iterator(); i.hasNext(); ) {
1726                     Map.Entry<String, Object> e2 = i.next();
1727 
1728                     values.put(e2.getKey(), e2.getValue());
1729                 }
1730 
1731                 hitsOnPage.add(values);
1732             }
1733         } catch (SolrServerException e) {
1734             e.printStackTrace();
1735         }
1736         return hitsOnPage;
1737     }
1738 
1739 
1740     /**
1741      * Verifies whether the given field for the given document id has a value from the given value list.
1742      * Returns true if the field has a value.
1743      *
1744      * @param uuid
1745      * @param fieldName
1746      * @param fieldValueList - "," separated values
1747      * @return
1748      * @throws SolrServerException
1749      */
1750     @Override
1751     public boolean verifyFieldValue(String uuid, String fieldName, List<String> fieldValueList) throws SolrServerException {
1752         SolrQuery solrQuery = new SolrQuery();
1753         SolrServer server = SolrServerManager.getInstance().getSolrServer();
1754         solrQuery.setQuery("id:" + uuid);
1755         solrQuery.setFields(fieldName);
1756         QueryResponse queryResponse = server.query(solrQuery);
1757         SolrDocumentList solrDocuments = queryResponse.getResults();
1758 
1759         for (String fieldValue : fieldValueList) {
1760             for (SolrDocument solrDocument : solrDocuments) {
1761                 if (solrDocument.getFieldValue(fieldName) instanceof String) {
1762                     String fieldVal = "";
1763                     fieldVal = (String) solrDocument.getFieldValue(fieldName);
1764                     if ((fieldVal != null) && (fieldVal.equalsIgnoreCase(fieldValue))) {
1765                         return true;
1766                     }
1767                 }
1768                 else if (solrDocument.getFieldValue(fieldName) instanceof List) {
1769                     List<String> fieldValuesFromSolr = (List<String>) solrDocument.getFieldValue(fieldName);
1770                     for (String fieldVal : fieldValuesFromSolr) {
1771                         if (fieldVal.equalsIgnoreCase(fieldValue)) {
1772                             return true;
1773                         }
1774                     }
1775                 }
1776             }
1777         }
1778         return false;
1779     }
1780 
1781     /**
1782      *
1783      * @param instanceIds
1784      * @return
1785      * @throws SolrServerException
1786      */
1787     @Override
1788     public List<String> getItemIdsForInstanceIds(List<String> instanceIds) throws SolrServerException {
1789 
1790         List<String> itemIds = new ArrayList<String>();
1791 
1792         for (String uuid : instanceIds) {
1793             SolrQuery solrQuery = new SolrQuery();
1794             SolrServer server = SolrServerManager.getInstance().getSolrServer();
1795             solrQuery.setQuery("id:" + uuid);
1796             solrQuery.setFields("itemIdentifier");
1797             QueryResponse queryResponse = server.query(solrQuery);
1798             SolrDocumentList solrDocuments = queryResponse.getResults();
1799             for (SolrDocument solrDocument : solrDocuments) {
1800                 if (solrDocument.getFieldValue("itemIdentifier") instanceof String) {
1801                     String fieldVal = (String) solrDocument.getFieldValue("itemIdentifier");
1802                     itemIds.add(fieldVal);
1803                 }
1804                 else if (solrDocument.getFieldValue("itemIdentifier") instanceof List) {
1805                     List<String> fieldValuesFromSolr = (List<String>) solrDocument.getFieldValue("itemIdentifier");
1806                     itemIds.addAll(fieldValuesFromSolr);
1807                 }
1808             }
1809         }
1810         return itemIds;
1811     }
1812 }