View Javadoc
1   package org.kuali.ole.describe.controller;
2   
3   import org.apache.commons.collections.CollectionUtils;
4   import org.apache.commons.lang.StringUtils;
5   import org.apache.log4j.Logger;
6   import org.apache.solr.client.solrj.SolrServerException;
7   import org.kuali.ole.OLEConstants;
8   import org.kuali.ole.converter.MarcXMLConverter;
9   import org.kuali.ole.describe.bo.BibDocumentSearchResult;
10  import org.kuali.ole.describe.bo.ExternalDataSourceConfig;
11  import org.kuali.ole.describe.bo.ImportBibSearch;
12  import org.kuali.ole.describe.bo.ImportBibUserPreferences;
13  import org.kuali.ole.describe.form.ImportBibForm;
14  import org.kuali.ole.describe.service.ImportBibService;
15  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
16  import org.kuali.ole.docstore.common.document.Bib;
17  import org.kuali.ole.docstore.common.document.BibMarc;
18  import org.kuali.ole.docstore.common.document.BibMarcMapper;
19  import org.kuali.ole.docstore.common.document.BibTree;
20  import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecord;
21  import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecords;
22  import org.kuali.ole.docstore.common.document.content.bib.marc.ControlField;
23  import org.kuali.ole.docstore.common.document.content.bib.marc.xstream.BibMarcRecordProcessor;
24  import org.kuali.ole.docstore.common.search.SearchCondition;
25  import org.kuali.ole.docstore.common.search.SearchParams;
26  import org.kuali.ole.docstore.model.xstream.work.bib.marc.MRKToMARCXMLConverter;
27  import org.kuali.ole.externalds.DataSourceConfig;
28  import org.kuali.ole.externalds.ExternalDataSource;
29  import org.kuali.ole.externalds.ExternalDataSourceFactory;
30  import org.kuali.ole.sys.context.SpringContext;
31  import org.kuali.rice.core.api.config.property.ConfigContext;
32  import org.kuali.rice.kim.api.permission.PermissionService;
33  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
34  import org.kuali.rice.krad.service.BusinessObjectService;
35  import org.kuali.rice.krad.service.KRADServiceLocator;
36  import org.kuali.rice.krad.uif.UifParameters;
37  import org.kuali.rice.krad.util.GlobalVariables;
38  import org.kuali.rice.krad.util.KRADConstants;
39  import org.kuali.rice.krad.web.controller.UifControllerBase;
40  import org.kuali.rice.krad.web.form.UifFormBase;
41  import org.springframework.stereotype.Controller;
42  import org.springframework.validation.BindingResult;
43  import org.springframework.web.bind.annotation.ModelAttribute;
44  import org.springframework.web.bind.annotation.RequestMapping;
45  import org.springframework.web.multipart.MultipartFile;
46  import org.springframework.web.servlet.ModelAndView;
47  
48  import javax.servlet.ServletException;
49  import javax.servlet.http.HttpServletRequest;
50  import javax.servlet.http.HttpServletResponse;
51  import java.io.IOException;
52  import java.util.*;
53  
54  /**
55   * Created with IntelliJ IDEA.
56   * User: pj7789
57   * Date: 26/11/12
58   * Time: 11:46 AM
59   * To change this template use File | Settings | File Templates.
60   */
61  
62  @Controller
63  @RequestMapping(value = "/importBibController")
64  public class ImportBibController
65          extends UifControllerBase {
66  
67      private static final Logger LOG = Logger.getLogger(ImportBibController.class);
68  
69      BibMarcRecordProcessor workBibMarcRecordProcessor = new BibMarcRecordProcessor();
70      BibMarcMapper bibMarcMapper = BibMarcMapper.getInstance();
71  
72      private DocstoreClientLocator docstoreClientLocator;
73  
74      public DocstoreClientLocator getDocstoreClientLocator() {
75          if (null == docstoreClientLocator) {
76              return SpringContext.getBean(DocstoreClientLocator.class);
77          }
78          return docstoreClientLocator;
79      }
80  
81      /**
82       * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
83       */
84  
85  
86      /**
87       * This method creates a instance of ListBoxForm
88       *
89       * @param request
90       * @return ListBoxForm
91       */
92      @Override
93      protected ImportBibForm createInitialForm(HttpServletRequest request) {
94          return new ImportBibForm();
95      }
96  
97      private boolean canPerformImportBibLocal(String principalId) {
98          PermissionService service = KimApiServiceLocator.getPermissionService();
99          return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INGEST_BIB_LOCAL);
100     }
101 
102     private boolean canPerformImportBibExternal(String principalId) {
103         PermissionService service = KimApiServiceLocator.getPermissionService();
104         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INGEST_BIB_EXTERNAL);
105     }
106 
107     /**
108      * This method takes the initial request when click on DublinEditor Screen.
109      *
110      * @param form
111      * @param result
112      * @param request
113      * @param response
114      * @return ModelAndView
115      */
116     @Override
117     @RequestMapping(params = "methodToCall=start")
118     public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
119                               HttpServletRequest request, HttpServletResponse response) {
120         ImportBibForm importBibForm = (ImportBibForm) form;
121         boolean hasPermission = canPerformImportBibLocal(GlobalVariables.getUserSession().getPrincipalId()) && canPerformImportBibExternal(GlobalVariables.getUserSession().getPrincipalId());
122         if (!hasPermission) {
123             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_AUTHORIZATION);
124             return getUIFModelAndView(importBibForm);
125         }
126         request.getSession().removeAttribute("bibUuidsList");
127         return super.start(importBibForm, result, request, response);
128     }
129 
130     /**
131      * Used for Test-case
132      *
133      * @param result
134      * @param request
135      * @param response
136      * @param importBibForm
137      * @return ModelAndView
138      */
139     protected ModelAndView callSuper(BindingResult result, HttpServletRequest request, HttpServletResponse response,
140                                      ImportBibForm importBibForm) {
141         return super.navigate(importBibForm, result, request, response);
142     }
143 
144     @RequestMapping(params = "methodToCall=overLay")
145     public ModelAndView overLay(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
146                                 HttpServletRequest request, HttpServletResponse response) throws Exception {
147         String uuid = request.getParameter("docId");
148         ImportBibForm importBibForm = (ImportBibForm) form;
149         boolean hasPermission = canPerformImportBibLocal(GlobalVariables.getUserSession().getPrincipalId()) && canPerformImportBibExternal(GlobalVariables.getUserSession().getPrincipalId());
150         if (!hasPermission) {
151             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_AUTHORIZATION);
152             return getUIFModelAndView(importBibForm);
153         }
154         importBibForm.setUuid(uuid);
155         Bib bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(uuid);
156 
157         if (bib.getContent() != null && bib.getContent().length() > 0) {
158             BibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(bib.getContent());
159             if (marcRecords != null && marcRecords.getRecords() != null && marcRecords.getRecords().size() > 0) {
160                 importBibForm.setExistingBibMarcRecord(marcRecords.getRecords().get(0));
161             }
162         }
163         return getUIFModelAndView(importBibForm, "SearchBibViewPage");
164     }
165 
166     @RequestMapping(params = "methodToCall=load")
167     public ModelAndView load(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
168                              HttpServletRequest request, HttpServletResponse response) throws Exception {
169         LOG.info("Inside Search Method");
170         ImportBibForm importBibForm = (ImportBibForm) form;
171         MultipartFile multipartFile = importBibForm.getImportBibSearch().getLocationFile();
172         importBibForm.getImportBibSearch().setReturnCheck(false);
173         importBibForm.getMarcDocRecMap().clear();
174         importBibForm.getBibMarcRecordList().clear();
175         importBibForm.setMessage("");
176         String marcXmlContent = getMarcXml(multipartFile, importBibForm);
177         request.getSession().setAttribute("showDetailForLocalSearchRecord", marcXmlContent);
178         if (marcXmlContent != null && marcXmlContent.length() > 0) {
179             //convert xml to pojo
180             BibMarcRecords bibMarcRecords = workBibMarcRecordProcessor.fromXML(marcXmlContent);
181             List<BibMarcRecord> workBibMarcRecordList = new ArrayList<BibMarcRecord>();
182             List<BibMarcRecord> workBibMarcRecords = new ArrayList<BibMarcRecord>();
183             int uniCodeCount = 0;
184             int marcCount = 0;
185             if (bibMarcRecords != null) {
186                 for (BibMarcRecord workBibMarcRecord : bibMarcRecords.getRecords()) {
187                     String leader = workBibMarcRecord.getLeader();
188                     char unicode = leader.charAt(9);
189                     if (unicode == 'a') {
190                         workBibMarcRecordList.add(workBibMarcRecord);
191                         uniCodeCount = uniCodeCount + 1;
192                     } else {
193                         workBibMarcRecords.add(workBibMarcRecord);
194                         marcCount = marcCount + 1;
195                     }
196                 }
197                 importBibForm.setBibMarcRecordList(workBibMarcRecordList);
198             }
199             LOG.info("No of Unicode records: " + uniCodeCount);
200             LOG.info("No of Marc8 records: " + marcCount);
201             importBibForm.getImportBibSearch().setSelectedFileName(multipartFile.getOriginalFilename());
202             importBibForm.getImportBibSearch().setRecordsInFile(bibMarcRecords.getRecords().size());
203             bibMarcRecords.setRecords(workBibMarcRecordList);
204             importBibForm.getImportBibSearch().setRecordsInUnicode(workBibMarcRecordList.size());
205             importBibForm.getImportBibSearch().setRecordsInNonUnicode(workBibMarcRecords.size());
206             // convert pojo to workBibDoc
207             List<Bib> workBibDocumentList = getBibDocumens(bibMarcRecords);
208             List<BibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocumentList);
209             // Sorting the import bib result list and mapping it to corresponding marc record
210             SortedMap<BibDocumentSearchResult, BibMarcRecord> marcDocRecMapSorted = new TreeMap<BibDocumentSearchResult, BibMarcRecord>(new ImportBibService());
211             if (!workBibMarcRecordList.isEmpty()) {
212                 for (int i = 0; i < importBibResultsList.size(); i++) {
213                     marcDocRecMapSorted.put(importBibResultsList.get(i), importBibForm.getBibMarcRecordList().get(i));
214                 }
215                 importBibForm.setMarcDocRecMap(marcDocRecMapSorted);
216             }
217             List<BibDocumentSearchResult> searchList = new ArrayList<BibDocumentSearchResult>();
218             searchList.addAll(importBibForm.getMarcDocRecMap().keySet());
219             // adding the sorted key values to search results list to display in seacrch table
220             importBibForm.getImportBibSearch().setLocalBibDocumentSearchResults(searchList);
221             if (marcCount > 0 && uniCodeCount > 0) {
222                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "load.import.bib.unicode");
223             } else if (marcCount > 0 && uniCodeCount == 0) {
224                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "load.import.bib.unicode");
225             } else {
226                 importBibForm.setMessage("");
227             }
228         }
229         return getUIFModelAndView(importBibForm);
230     }
231 
232     @RequestMapping(params = "methodToCall=search")
233     public ModelAndView search(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
234                                HttpServletRequest request, HttpServletResponse response) throws Exception {
235         LOG.info("Inside Search Method");
236         ImportBibForm importBibForm = (ImportBibForm) form;
237         SearchParams searchParams = importBibForm.getSearchParams();
238         if (searchParams.getSearchConditions().get(0).getSearchField().getFieldValue() == "" || searchParams.getSearchConditions().get(0).getSearchField().getFieldValue() == null) {
239             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DESCRIBE_ENTER_SEARCH_TEXT);
240             importBibForm.setBibMarcRecordList(null);
241             importBibForm.setBibUuidsList(null);
242             importBibForm.setImportBibSearch(null);
243             searchParams.getSearchResultFields().clear();
244             return getUIFModelAndView(importBibForm);
245         }
246         String source = importBibForm.getImportBibSearch().getSource();
247         List<BibDocumentSearchResult> searchList = new ArrayList<BibDocumentSearchResult>();
248         importBibForm.getImportBibSearch().setExternalBibDocumentSearchResults(searchList);
249         if (source != null && source.length() > 0) {
250             List<String> results = null;
251             DataSourceConfig dataSourceConfig = new DataSourceConfig();
252             BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
253             Map parentCriteria = new HashMap();
254             parentCriteria.put("id", source);
255             ExternalDataSourceConfig externalDataSourceConfig = new ExternalDataSourceConfig();
256             externalDataSourceConfig = businessObjectService.findByPrimaryKey(ExternalDataSourceConfig.class, parentCriteria);
257             dataSourceConfig.setDomainName(externalDataSourceConfig.getDomainName());
258             dataSourceConfig.setPortNum(externalDataSourceConfig.getPortNum());
259             dataSourceConfig.setDatabaseName(externalDataSourceConfig.getDatabaseName());
260             dataSourceConfig.setLoginId(externalDataSourceConfig.getLoginId());
261             dataSourceConfig.setPassword(externalDataSourceConfig.getPassword());
262             dataSourceConfig.setAuthKey(externalDataSourceConfig.getAuthKey());
263             ExternalDataSource externalDataSource = ExternalDataSourceFactory.getInstance().getExternalDataSource(dataSourceConfig);
264             // NOTE: Uncomment this line to enable Searching external Z39.50 data sources.
265             /*try {
266                 results = externalDataSource.searchForBibs(searchParams, dataSourceConfig);
267             } catch (Exception e){
268                 LOG.error("Error occurred while fetching the records :"+e);
269                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.EXTERNAL_DATA_IMPORT_ERROR);
270                 return getUIFModelAndView(importBibForm);
271             }*/
272 
273             request.getSession().setAttribute("showDetailForExternalSearchRecord", results);
274             BibMarcRecords marcRecords = prepareWorkBibMarcRecords(results);
275             if (marcRecords != null && CollectionUtils.isNotEmpty(marcRecords.getRecords())) {
276                 importBibForm.setBibMarcRecordList(marcRecords.getRecords());
277                 List<Bib> workBibDocumentList = getBibDocumens(marcRecords);
278                 List<BibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocumentList);
279                 SortedMap<BibDocumentSearchResult, BibMarcRecord> marcDocRecMapSorted = new TreeMap<BibDocumentSearchResult, BibMarcRecord>(new ImportBibService());
280                 for (int i = 0; i < importBibResultsList.size(); i++) {
281                     marcDocRecMapSorted.put(importBibResultsList.get(i), importBibForm.getBibMarcRecordList().get(i));
282                 }
283 
284                 importBibForm.setMarcDocRecMap(marcDocRecMapSorted);
285                 searchList.addAll(importBibForm.getMarcDocRecMap().keySet());
286                 // adding the sorted key values to search results list to display in seacrch table
287                 importBibForm.getImportBibSearch().setExternalBibDocumentSearchResults(searchList);
288                 importBibForm.getImportBibSearch().setReturnCheck(true);
289             } else {
290                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_ERRORS, OLEConstants.NO_RECORD_FOUND);
291             }
292 
293         } else {
294             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.SOURCE_NOT_SELECTED);
295             importBibForm.setImportBibSearch(null);
296             return getUIFModelAndView(importBibForm);
297         }
298 
299         return getUIFModelAndView(importBibForm);
300     }
301 
302     public BibMarcRecords prepareWorkBibMarcRecords(List<String> results) {
303         MRKToMARCXMLConverter mrkToMARCXMLConverter = new MRKToMARCXMLConverter();
304         StringBuffer sb = new StringBuffer(
305                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><collection xmlns=\"http://www.loc.gov/MARC21/slim\">");
306         for (String marcString : results) {
307             String marcXML = mrkToMARCXMLConverter.convert(marcString);
308             sb.append(marcXML.substring(marcXML.indexOf("<record>"), marcXML.indexOf("</collection>")));
309         }
310         sb.append("</collection>");
311         String marcXmlContent = sb.toString();
312         BibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(marcXmlContent);
313         return marcRecords;
314     }
315 
316     /**
317      * @param form
318      * @param result
319      * @param request
320      * @param response
321      * @return
322      */
323     @RequestMapping(params = "methodToCall=clearSearch")
324     public ModelAndView clearSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
325                                     HttpServletRequest request, HttpServletResponse response) {
326         LOG.info("Inside clearSearch Method");
327         ImportBibForm importBibForm = (ImportBibForm) form;
328         importBibForm.getImportBibSearch().setReturnCheck(true);
329         importBibForm.getImportBibSearch().setExternalBibDocumentSearchResults(null);
330         importBibForm.getImportBibSearch().setSource("");
331         List<SearchCondition> searchConditions = new ArrayList<SearchCondition>();
332         searchConditions.add(new SearchCondition());
333         searchConditions.add(new SearchCondition());
334         importBibForm.getSearchParams().getSearchConditions().addAll(searchConditions);
335         return getUIFModelAndView(importBibForm);
336     }
337 
338     /**
339      * @param form
340      * @param result
341      * @param request
342      * @param response
343      * @return
344      */
345     @RequestMapping(params = "methodToCall=clearFile")
346     public ModelAndView clearFile(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
347                                   HttpServletRequest request, HttpServletResponse response) {
348         LOG.info("Inside clearSearch Method");
349 
350         ImportBibForm importBibForm = (ImportBibForm) form;
351         importBibForm.getImportBibSearch().setReturnCheck(false);
352         importBibForm.getImportBibSearch().setLocalBibDocumentSearchResults(null);
353         importBibForm.getImportBibSearch().setSelectedFileName("");
354         importBibForm.getImportBibSearch().setRecordsInFile(0);
355         importBibForm.getImportBibSearch().setRecordsImported(0);
356         importBibForm.setMessage("");
357         return getUIFModelAndView(importBibForm);
358     }
359 
360     @RequestMapping(params = "methodToCall=actionLink")
361     public ModelAndView actionLink(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
362                                    HttpServletRequest request, HttpServletResponse response) {
363         ImportBibForm importBibForm = (ImportBibForm) form;
364         int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
365         List<BibMarcRecord> marcRecList = importBibForm.getBibMarcRecordList();
366         BibMarcRecord marcRec = marcRecList.get(index);
367         LOG.info("Marc Rec is..." + marcRec);
368         return getUIFModelAndView(importBibForm);
369     }
370 
371     @RequestMapping(params = "methodToCall=localNext")
372     public ModelAndView next(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
373                              HttpServletRequest request, HttpServletResponse response) {
374         ImportBibForm importBibForm = (ImportBibForm) form;
375         if (importBibForm != null && importBibForm.getImportBibSearch() != null
376                 && importBibForm.getImportBibSearch().getLocalBibDocumentSearchResults() != null) {
377             List<BibDocumentSearchResult> bibDocumentSearchResultList = importBibForm.getImportBibSearch()
378                     .getLocalBibDocumentSearchResults();
379             boolean isSelected = true;
380             int i = 0;
381             for (BibDocumentSearchResult workBibDocumentResult : bibDocumentSearchResultList) {
382                 i++;
383                 if (workBibDocumentResult.isSelectedMarc() && isSelected) {
384                     isSelected = false;
385                     importBibForm.getImportBibSearch().setSelectedMarc(
386                             importBibForm.getImportBibSearch().getLocalBibDocumentSearchResults().get(i - 1));
387                     importBibForm.setNewBibMarcRecord(importBibForm.getMarcDocRecMap().get(workBibDocumentResult));
388                     importBibForm.getImportBibSearch().setSelectedRecordIndex(i - 1);
389                 }
390             }
391             if (isSelected) {
392                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "select.import.bib.record");
393                 return getUIFModelAndView(importBibForm, "SearchBibViewPage");
394             }
395         }
396         importBibForm.setMessage(null);
397         return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
398     }
399 
400     @RequestMapping(params = "methodToCall=externalNext")
401     public ModelAndView externalNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
402                                      HttpServletRequest request, HttpServletResponse response) {
403         ImportBibForm importBibForm = (ImportBibForm) form;
404         if (importBibForm != null && importBibForm.getImportBibSearch() != null
405                 && importBibForm.getImportBibSearch().getExternalBibDocumentSearchResults() != null) {
406             List<BibDocumentSearchResult> bibDocumentSearchResultList = importBibForm.getImportBibSearch()
407                     .getExternalBibDocumentSearchResults();
408             boolean isSelected = true;
409             int i = 0;
410             for (BibDocumentSearchResult workBibDocumentResult : bibDocumentSearchResultList) {
411                 i++;
412                 if (workBibDocumentResult.isSelectedExternalMarc() && isSelected) {
413                     isSelected = false;
414                     importBibForm.getImportBibSearch().setSelectedMarc(
415                             importBibForm.getImportBibSearch().getExternalBibDocumentSearchResults().get(i - 1));
416                     importBibForm.setNewBibMarcRecord(importBibForm.getMarcDocRecMap().get(workBibDocumentResult));
417                     importBibForm.getImportBibSearch().setSelectedRecordIndex(i - 1);
418                 }
419             }
420             if (isSelected) {
421                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "select.import.bib.record");
422                 return getUIFModelAndView(importBibForm, "SearchBibViewPage");
423             }
424         }
425         importBibForm.setMessage(null);
426         return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
427     }
428 
429     @RequestMapping(params = "methodToCall=loadUserPref")
430     public ModelAndView loadUserPref(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
431                                      HttpServletRequest request, HttpServletResponse response) throws Exception {
432         ImportBibForm importBibForm = (ImportBibForm) form;
433         ImportBibUserPreferences importBibUserPreferences = importBibForm.getImportBibUserPreferences();
434         if (importBibUserPreferences.getPrefId1().length() > 0) {
435             importBibUserPreferences.setPrefId(Integer.valueOf(importBibUserPreferences.getPrefId1()));
436             if (importBibUserPreferences.getPrefId() != null && importBibUserPreferences.getPrefId() > 0) {
437                 BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
438                 Map parentCriteria = new HashMap();
439                 parentCriteria.put("prefId", importBibUserPreferences.getPrefId());
440                 importBibUserPreferences = businessObjectService
441                         .findByPrimaryKey(ImportBibUserPreferences.class, parentCriteria);
442                 importBibForm.setImportBibUserPreferences(importBibUserPreferences);
443                 parentCriteria.put("prefId", 1);
444                 ImportBibUserPreferences importBibAdminPreferences = businessObjectService
445                         .findByPrimaryKey(ImportBibUserPreferences.class, parentCriteria);
446                 importBibForm.getImportBibUserPreferences()
447                         .setAdminProtectedTags(importBibAdminPreferences.getProtectedTags());
448                 importBibForm.getImportBibUserPreferences().setAdminRemovalTags(importBibAdminPreferences.getRemovalTags());
449             }
450             importBibUserPreferences.setPrefId1(String.valueOf(importBibUserPreferences.getPrefId()));
451         }
452 
453         if (importBibForm.getExistingBibMarcRecord() != null) {
454             //converting marc record to WorkBibDocument
455             BibMarcRecords marcRecords = new BibMarcRecords();
456             List<BibMarcRecord> workBibMarcRecordList = new ArrayList<BibMarcRecord>();
457             workBibMarcRecordList.add(importBibForm.getExistingBibMarcRecord());
458             marcRecords.setRecords(workBibMarcRecordList);
459             List<Bib> workBibDocumentList = getBibDocumens(marcRecords);
460             //setting uuid (control field 001) to WorkBibMarc Document
461             for (ControlField cf : importBibForm.getExistingBibMarcRecord().getControlFields()) {
462                 if (cf.getTag().equalsIgnoreCase("001")) {
463                     workBibDocumentList.get(0).setId(cf.getValue());
464                     break;
465                 }
466             }
467             // getting workbibdocument with Instance data.
468             List<String> uuids = new ArrayList<>();
469             for (Bib bib : workBibDocumentList) {
470                 uuids.add(bib.getId());
471             }
472             List<Bib> workBibDocuments = getDocstoreClientLocator().getDocstoreClient().retrieveBibs(uuids);
473             List<BibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocuments);
474             // setting workbibDocument to OverLayMarcRecord
475             if (importBibForm.getImportBibConfirmReplace() != null && importBibResultsList != null
476                     && importBibResultsList.size() > 0) {
477                 BibDocumentSearchResult bibDocumentSearchResult = importBibResultsList.get(0);
478                 BibTree bibTree = getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(bibDocumentSearchResult.getId());
479                 bibDocumentSearchResult.setHoldingsTree(bibTree.getHoldingsTrees().get(0));
480                 importBibForm.getImportBibConfirmReplace().setOverLayMarcRecord(bibDocumentSearchResult);
481             }
482         }
483         if (importBibForm.getExistingBibMarcRecord() != null) {
484             importBibUserPreferences.setImportType("overLay");
485         } else if (importBibUserPreferences != null && "overLay".equalsIgnoreCase(importBibUserPreferences.getImportType())) {
486             importBibUserPreferences.setImportType("newImport");
487         }
488 
489         return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
490     }
491 
492 
493     @RequestMapping(params = "methodToCall=userPrefNext")
494     public ModelAndView userPrefNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
495                                      HttpServletRequest request, HttpServletResponse response) throws Exception {
496         ImportBibForm importBibForm = (ImportBibForm) form;
497         ImportBibUserPreferences importBibUserPreferences = importBibForm.getImportBibUserPreferences();
498         ImportBibService importBibService = new ImportBibService();
499         if (importBibService.callNumValidation(importBibUserPreferences)) {
500             GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.callNumber.number", "error.import.bib.callnumber");
501             return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
502         }
503         if (importBibService.proNRemTagValidation(importBibUserPreferences)) {
504             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "invalid.import.bib.datafields");
505             return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
506         }
507         importBibForm.setMessage(null);
508         importBibService.applyUserPref(importBibForm);
509         request.getSession().setAttribute("importBibForm", importBibForm);
510         request.getSession().setAttribute("marcDocRecMap", importBibForm.getMarcDocRecMap());
511         request.getSession().setAttribute("bibMarcRecordList", importBibForm.getBibMarcRecordList());
512         request.getSession().setAttribute("bibUuidsList", importBibForm.getBibUuidsList());
513         request.getSession().setAttribute("importBibSearch", importBibForm.getImportBibSearch());
514         BibTree bibTree = importBibService.createBibTree(importBibForm.getNewBibMarcRecord(), importBibForm.getNewInstanceCollection(), importBibUserPreferences.getImportStatus());
515         if (StringUtils.isNotEmpty(importBibForm.getUuid())) {
516             bibTree.getBib().setId(importBibForm.getUuid());
517         }
518         request.getSession().setAttribute("bibTree", bibTree);
519         if (!importBibUserPreferences.getImportType().equalsIgnoreCase("newImport")) {
520             return getUIFModelAndView(importBibForm, "ConfirmReplace");
521         }
522         try {
523             String url = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
524             url = url + "/portal.do?channelTitle=Import Bib&channelUrl=" + url +
525                     "/ole-kr-krad/editorcontroller?viewId=EditorView&methodToCall=load&docCategory=work&docType" +
526                     "=bibliographic&docFormat=marc&loadFromSession=true&editable=true";
527             return performRedirect(importBibForm, url);
528         } catch (Exception e) {
529             LOG.error("Exception while forwarding to editor." + e);
530         }
531         return getUIFModelAndView(importBibForm, "ConfirmImport");
532     }
533 
534     @RequestMapping(params = "methodToCall=close")
535     public ModelAndView close(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
536                               HttpServletRequest request, HttpServletResponse response) {
537 
538         String url = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
539         return performRedirect(form, url);
540     }
541 
542 
543     @RequestMapping(params = "methodToCall=loadImportBibSearch")
544     public ModelAndView loadImportBibSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
545                                             HttpServletRequest request, HttpServletResponse response)
546             throws IOException, ServletException {
547         LOG.info("Inside confirmReplaceNext Method");
548         ImportBibForm importBibForm = (ImportBibForm) form;
549         if (importBibForm != null && importBibForm.getImportBibSearch() != null) {
550             if (importBibForm.getMarcDocRecMap() != null && importBibForm.getImportBibSearch() != null &&
551                     importBibForm.getImportBibSearch().getSelectedMarc() != null) {
552                 importBibForm.getMarcDocRecMap().remove(importBibForm.getImportBibSearch().getSelectedMarc());
553                 List<BibDocumentSearchResult> localRecList = new ArrayList<BibDocumentSearchResult>();
554                 List<BibMarcRecord> marcRecList = new ArrayList<BibMarcRecord>();
555                 for (Map.Entry<BibDocumentSearchResult, BibMarcRecord> record : importBibForm.getMarcDocRecMap().entrySet()) {
556                     localRecList.add(record.getKey());
557                     marcRecList.add(record.getValue());
558                 }
559                 importBibForm.getImportBibSearch().setLocalBibDocumentSearchResults(localRecList);
560                 importBibForm.setBibMarcRecordList(marcRecList);
561             }
562             importBibForm.getMarcDocRecMap().remove(importBibForm.getImportBibSearch().getSelectedMarc());
563             importBibForm.getImportBibSearch()
564                     .setRecordsImported(Math.max(0, importBibForm.getImportBibSearch().getRecordsImported() + 1));
565             importBibForm.getImportBibSearch()
566                     .setRecordsInFile(Math.max(0, importBibForm.getImportBibSearch().getRecordsInFile() - 1));
567         }
568         return getUIFModelAndView(importBibForm, "SearchBibViewPage");
569     }
570 
571     @RequestMapping(params = "methodToCall=viewRecordNext")
572     public ModelAndView viewRecordNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
573                                        HttpServletRequest request, HttpServletResponse response)
574             throws IOException, SolrServerException {
575         LOG.info("Inside Search Method");
576         ImportBibForm importBibForm = (ImportBibForm) form;
577         BibTree bibTree = null;
578         if (request != null && request.getSession() != null) {
579             bibTree = (BibTree) request.getSession().getAttribute("responseBibTree");
580             if (bibTree == null) {
581                 bibTree = (BibTree) request.getSession().getAttribute("bibTree");
582             }
583             if (request.getSession().getAttribute("importBibForm") != null) {
584                 ImportBibForm importBibForminSession = (ImportBibForm) request.getSession().getAttribute("importBibForm");
585                 if (importBibForminSession != null) {
586                     importBibForm.setImportBibSearch(importBibForminSession.getImportBibSearch());
587                     importBibForm.setBibMarcRecordList(importBibForminSession.getBibMarcRecordList());
588                     importBibForm.setBibUuidsList(importBibForminSession.getBibUuidsList());
589                     importBibForm.setMarcDocRecMap(importBibForminSession.getMarcDocRecMap());
590                     request.getSession().removeAttribute("importBibForm");
591                 }
592             }
593             if (importBibForm.getMarcDocRecMap().isEmpty()) {
594                 importBibForm.setMarcDocRecMap((SortedMap<BibDocumentSearchResult, BibMarcRecord>) request.getSession().getAttribute("marcDocRecMap"));
595                 request.getSession().removeAttribute("marcDocRecMap");
596             }
597             if (importBibForm.getImportBibSearch().getLocalBibDocumentSearchResults() == null || importBibForm.getImportBibSearch().getLocalBibDocumentSearchResults().isEmpty()) {
598                 importBibForm.setImportBibSearch((ImportBibSearch) request.getSession().getAttribute("importBibSearch"));
599                 request.getSession().removeAttribute("importBibSearch");
600             }
601             if (importBibForm.getBibUuidsList().isEmpty() && request.getSession().getAttribute("bibUuidsList") != null) {
602                 importBibForm.setBibUuidsList((List<BibDocumentSearchResult>) request.getSession().getAttribute("bibUuidsList"));
603                 // request.getSession().removeAttribute("bibUuidsList");
604             }
605             if (importBibForm.getBibMarcRecordList() == null || importBibForm.getBibMarcRecordList().isEmpty()) {
606                 importBibForm.setBibMarcRecordList((List<BibMarcRecord>) request.getSession().getAttribute("bibMarcRecordList"));
607                 request.getSession().removeAttribute("bibMarcRecordList");
608             }
609 
610 
611             request.getSession().removeAttribute("bibTree");
612             request.getSession().removeAttribute("responseBibTree");
613         }
614 
615         List<Bib> bibDocumentList = new ArrayList<Bib>();
616 
617         if (bibTree != null) {
618 
619             Bib bib = bibTree.getBib();
620             bib.deserializeContent(bib);
621             bibDocumentList.add(bib);
622             importBibForm.setUuid(bib.getId());
623         }
624 
625         List<BibDocumentSearchResult> uuidList = importBibForm.getBibUuidsList();
626         BibDocumentSearchResult bibDocumentSearchResult = new BibDocumentSearchResult();
627 
628         for (Bib workBibDocument : bibDocumentList) {
629             bibDocumentSearchResult = new BibDocumentSearchResult();
630             bibDocumentSearchResult.setId(workBibDocument.getId());
631             bibDocumentSearchResult.setUuid(workBibDocument.getId());
632             if (workBibDocument.getTitle() != null) {
633                 bibDocumentSearchResult.setDisplayField(workBibDocument.getTitle());
634                 bibDocumentSearchResult.setUuid(workBibDocument.getId());
635             }
636             uuidList.add(bibDocumentSearchResult);
637         }
638         importBibForm.setBibUuidsList(uuidList);
639         return getUIFModelAndView(importBibForm, "ConfirmImport");
640     }
641 
642 
643     @RequestMapping(params = "methodToCall=confirmReplaceNext")
644     public ModelAndView confirmReplaceNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
645                                            HttpServletRequest request, HttpServletResponse response)
646             throws IOException, ServletException {
647         LOG.info("Inside loadImportBibSearch Method");
648         ImportBibForm importBibForm = (ImportBibForm) form;
649 
650         try {
651             String url = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
652             url = url + "/portal.do?channelTitle=Import Bib&channelUrl=" + url
653                     + "/ole-kr-krad/editorcontroller?viewId=EditorView&methodToCall=load&docCategory=work&docType=bibliographic&docFormat=marc&loadFromSession=true&editable=true&docId="
654                     + importBibForm.getUuid();
655             return performRedirect(importBibForm, url);
656         } catch (Exception e) {
657             LOG.error("Exception while forwarding to editor." + e);
658         }
659         return getUIFModelAndView(importBibForm, "ConfirmImport");
660     }
661 
662     private String getMarcXml(MultipartFile file, UifFormBase form) throws IOException {
663         String marcXMLContent = null;
664         String modifiedXMLContent = null;
665         MultipartFile multipartFile = file;
666         String locationFileName = multipartFile.getOriginalFilename();
667         if (locationFileName.toLowerCase().endsWith(".mrc")) {
668             String fileContent = new String(multipartFile.getBytes());
669             try {
670                 MarcXMLConverter marcXMLConverter = new MarcXMLConverter();
671                 marcXMLContent = marcXMLConverter.convert(fileContent);
672                 modifiedXMLContent = marcXMLContent.replace(
673                         "collection xmlns=\"http://www.loc.gov/MARC21/slim\" xmlns=\"http://www.loc.gov/MARC21/slim",
674                         "collection xmlns=\"http://www.loc.gov/MARC21/slim");
675             } catch (Exception e) {
676                 LOG.error("Exception :", e);
677                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.encoding.message");
678             }
679         } else {
680             GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "select.import.bib.file");
681         }
682         return modifiedXMLContent;
683     }
684 
685     private List<BibDocumentSearchResult> mapMarcFieldValues(List<Bib> bibList) {
686         List<BibDocumentSearchResult> importBibResultsList = new ArrayList<BibDocumentSearchResult>();
687         for (Bib bibDoc : bibList) {
688             BibDocumentSearchResult workBibDocument = new BibDocumentSearchResult();
689             workBibDocument.setId(bibDoc.getId());
690             workBibDocument.setAuthor(bibDoc.getAuthor());
691             workBibDocument.setTitle(bibDoc.getTitle());
692             workBibDocument.setPublicationDate(bibDoc.getPublicationDate());
693             workBibDocument.setEdition(bibDoc.getEdition());
694             importBibResultsList.add(workBibDocument);
695         }
696         return importBibResultsList;
697     }
698 
699     @RequestMapping(params = "methodToCall=showDetailForLocalSearchRecord")
700     public ModelAndView showDetailForLocalSearchRecord(@ModelAttribute("KualiForm") UifFormBase form,
701                                                        BindingResult result, HttpServletRequest request,
702                                                        HttpServletResponse response) throws Exception {
703         MRKToMARCXMLConverter mrkToMARCXMLConverter = new MRKToMARCXMLConverter();
704         String bibId = request.getParameter("bibId");
705         LOG.info("showDetailForLocalSearchRecord bibId " + bibId);
706         ImportBibForm importBibForm = (ImportBibForm) form;
707         String marcXmlContent = (String) request.getSession().getAttribute("showDetailForLocalSearchRecord");
708         SortedMap<BibDocumentSearchResult, BibMarcRecord> marcDocRecMapSorted = sort(marcXmlContent);
709         List<BibDocumentSearchResult> searchList = new ArrayList<BibDocumentSearchResult>();
710         searchList.addAll(marcDocRecMapSorted.keySet());
711         if (marcXmlContent != null && marcXmlContent.length() > 0) {
712             BibMarcRecord workBibMarcRecord = marcDocRecMapSorted.get(searchList.get(Integer.parseInt(bibId)));
713             List<BibMarcRecord> workBibMarcRecordList = new ArrayList<BibMarcRecord>();
714             workBibMarcRecordList.add(workBibMarcRecord);
715             BibMarcRecords marcRecordsNew = new BibMarcRecords();
716             marcRecordsNew.setRecords(workBibMarcRecordList);
717             String detailXML = workBibMarcRecordProcessor.toXml(marcRecordsNew);
718             LOG.info("detailXML " + detailXML);
719             String marc = mrkToMARCXMLConverter.ConvertMarcXMLToMRK(detailXML);
720             importBibForm.setMessage("<pre>" + marc + "</pre>");
721             LOG.info("marc " + marc);
722         }
723         return getUIFModelAndView(form);
724     }
725 
726     @RequestMapping(params = "methodToCall=showDetailForExternalSearchRecord")
727     public ModelAndView showDetailForExternalSearchRecord(@ModelAttribute("KualiForm") UifFormBase form,
728                                                           BindingResult result, HttpServletRequest request,
729                                                           HttpServletResponse response) {
730         String bibId = request.getParameter("bibId");
731         ImportBibForm importBibForm = (ImportBibForm) form;
732         List<String> results = (List<String>) request.getSession().getAttribute("showDetailForExternalSearchRecord");
733         String resultvalue = results.get(Integer.parseInt(bibId));
734         importBibForm.setMessage("<pre>" + resultvalue + "</pre>");
735         return getUIFModelAndView(form);
736     }
737 
738     public SortedMap<BibDocumentSearchResult, BibMarcRecord> sort(String marcXmlContent) {
739         if (marcXmlContent != null && marcXmlContent.length() > 0) {
740             //convert xml to pojo
741             BibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(marcXmlContent);
742             List<BibMarcRecord> workBibMarcRecordList = marcRecords.getRecords();
743             // convert pojo to workBibDoc
744             List<Bib> workBibDocumentList = getBibDocumens(marcRecords);
745             List<BibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocumentList);
746             // Sorting the import bib result list and mapping it to corresponding marc record
747             SortedMap<BibDocumentSearchResult, BibMarcRecord> marcDocRecMapSorted
748                     = new TreeMap<BibDocumentSearchResult, BibMarcRecord>(new ImportBibService());
749             for (int i = 0; i < importBibResultsList.size(); i++) {
750                 marcDocRecMapSorted.put(importBibResultsList.get(i), workBibMarcRecordList.get(i));
751             }
752             return marcDocRecMapSorted;
753         } else {
754             SortedMap<BibDocumentSearchResult, BibMarcRecord> marcDocRecMapSortedZero
755                     = new TreeMap<BibDocumentSearchResult, BibMarcRecord>(new ImportBibService());
756             return marcDocRecMapSortedZero;
757         }
758     }
759 
760     private List<Bib> getBibDocumens(BibMarcRecords bibMarcRecords) {
761         List<Bib> workBibDocumentList = new ArrayList<>();
762         for (BibMarcRecord bibMarcRecord : bibMarcRecords.getRecords()) {
763             Bib bibMarc = new BibMarc();
764             bibMarcMapper.extractFields(bibMarcRecord, bibMarc);
765             workBibDocumentList.add(bibMarc);
766         }
767         return workBibDocumentList;
768     }
769 
770 }