001    package org.kuali.ole.describe.controller;
002    
003    import org.apache.log4j.Logger;
004    import org.apache.solr.client.solrj.SolrServerException;
005    import org.kuali.ole.PropertyUtil;
006    import org.kuali.ole.converter.MarcXMLConverter;
007    import org.kuali.ole.describe.bo.ExternalDataSourceConfig;
008    import org.kuali.ole.describe.bo.ImportBibUserPreferences;
009    import org.kuali.ole.describe.bo.WorkBibDocumentSearchResult;
010    import org.kuali.ole.describe.form.ImportBibForm;
011    import org.kuali.ole.describe.service.ImportBibService;
012    import org.kuali.ole.docstore.discovery.model.SearchCondition;
013    import org.kuali.ole.docstore.discovery.model.SearchParams;
014    import org.kuali.ole.docstore.discovery.service.QueryService;
015    import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
016    import org.kuali.ole.docstore.model.bo.WorkBibDocument;
017    import org.kuali.ole.docstore.model.converter.WorkBibDocConverter;
018    import org.kuali.ole.docstore.model.xmlpojo.ingest.Request;
019    import org.kuali.ole.docstore.model.xmlpojo.ingest.Response;
020    import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument;
021    import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.ControlField;
022    import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.WorkBibMarcRecord;
023    import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.WorkBibMarcRecords;
024    import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
025    import org.kuali.ole.docstore.model.xstream.work.bib.marc.MRKToMARCXMLConverter;
026    import org.kuali.ole.docstore.model.xstream.work.bib.marc.WorkBibMarcRecordProcessor;
027    import org.kuali.ole.editor.service.DocstoreHelperService;
028    import org.kuali.ole.externalds.DataSourceConfig;
029    import org.kuali.ole.externalds.ExternalDataSource;
030    import org.kuali.ole.externalds.ExternalDataSourceFactory;
031    import org.kuali.rice.krad.service.BusinessObjectService;
032    import org.kuali.rice.krad.service.KRADServiceLocator;
033    import org.kuali.rice.krad.uif.UifParameters;
034    import org.kuali.rice.krad.web.controller.UifControllerBase;
035    import org.kuali.rice.krad.web.form.UifFormBase;
036    import org.springframework.stereotype.Controller;
037    import org.springframework.validation.BindingResult;
038    import org.springframework.web.bind.annotation.ModelAttribute;
039    import org.springframework.web.bind.annotation.RequestMapping;
040    import org.springframework.web.multipart.MultipartFile;
041    import org.springframework.web.servlet.ModelAndView;
042    
043    import javax.servlet.ServletException;
044    import javax.servlet.http.HttpServletRequest;
045    import javax.servlet.http.HttpServletResponse;
046    import java.io.IOException;
047    import java.util.*;
048    
049    /**
050     * Created with IntelliJ IDEA.
051     * User: pj7789
052     * Date: 26/11/12
053     * Time: 11:46 AM
054     * To change this template use File | Settings | File Templates.
055     */
056    
057    @Controller
058    @RequestMapping(value = "/importBibController")
059    public class ImportBibController
060            extends UifControllerBase {
061    
062        private static final Logger  LOG               = Logger.getLogger(ImportBibController.class);
063    
064        /**
065         * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
066         */
067    
068    
069        /**
070         * This method creates a instance of ListBoxForm
071         *
072         * @param request
073         * @return ListBoxForm
074         */
075        @Override
076        protected ImportBibForm createInitialForm(HttpServletRequest request) {
077            return new ImportBibForm();
078        }
079    
080        /**
081         * This method takes the initial request when click on DublinEditor Screen.
082         *
083         * @param form
084         * @param result
085         * @param request
086         * @param response
087         * @return ModelAndView
088         */
089        @Override
090        @RequestMapping(params = "methodToCall=start")
091        public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
092                                  HttpServletRequest request, HttpServletResponse response) {
093            ImportBibForm importBibForm = (ImportBibForm) form;
094            return super.start(importBibForm, result, request, response);
095        }
096    
097        /**
098         * Used for Test-case
099         *
100         * @param result
101         * @param request
102         * @param response
103         * @param importBibForm
104         * @return ModelAndView
105         */
106        protected ModelAndView callSuper(BindingResult result, HttpServletRequest request, HttpServletResponse response,
107                                         ImportBibForm importBibForm) {
108            return super.navigate(importBibForm, result, request, response);
109        }
110    
111        @RequestMapping(params = "methodToCall=overLay")
112        public ModelAndView overLay(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
113                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
114            String uuid = request.getParameter("docId");
115            ImportBibForm importBibForm = (ImportBibForm) form;
116            importBibForm.setUuid(uuid);
117            DocstoreHelperService helperService = new DocstoreHelperService();
118            String bibXml = helperService.getDocstoreData(uuid);
119            if (bibXml != null && bibXml.length() > 0) {
120                WorkBibMarcRecordProcessor workBibMarcRecordProcessor = new WorkBibMarcRecordProcessor();
121                WorkBibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(bibXml);
122                if (marcRecords != null && marcRecords.getRecords() != null && marcRecords.getRecords().size() > 0) {
123                    importBibForm.setExistingWorkBibMarcRecord(marcRecords.getRecords().get(0));
124    
125                }
126            }
127            return getUIFModelAndView(importBibForm, "SearchBibViewPage");
128        }
129    
130    
131        @RequestMapping(params = "methodToCall=load")
132        public ModelAndView load(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
133                                 HttpServletRequest request, HttpServletResponse response) throws Exception {
134            LOG.info("Inside Search Method");
135            ImportBibForm importBibForm = (ImportBibForm) form;
136            MultipartFile multipartFile = importBibForm.getImportBibSearch().getLocationFile();
137            importBibForm.getImportBibSearch().setReturnCheck(false);
138    
139            String marcXmlContent = getMarcXml(multipartFile);
140            request.getSession().setAttribute("showDetailForLocalSearchRecord",marcXmlContent);
141            if (marcXmlContent != null && marcXmlContent.length() > 0) {
142                //convert xml to pojo
143                WorkBibMarcRecordProcessor workBibMarcRecordProcessor = new WorkBibMarcRecordProcessor();
144                WorkBibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(marcXmlContent);
145                if (marcRecords != null) {
146                    importBibForm.setWorkBibMarcRecordList(marcRecords.getRecords());
147                }
148                importBibForm.getImportBibSearch().setSelectedFileName(multipartFile.getOriginalFilename());
149                importBibForm.getImportBibSearch().setRecordsInFile(marcRecords.getRecords().size());
150                // convert pojo to workBibDoc
151                WorkBibDocConverter workBibDocConverter = new WorkBibDocConverter();
152                List<WorkBibDocument> workBibDocumentList = workBibDocConverter.convert(marcRecords);
153                List<WorkBibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocumentList);
154                // Sorting the import bib result list and mapping it to corresponding marc record
155                SortedMap<WorkBibDocumentSearchResult , WorkBibMarcRecord> marcDocRecMapSorted = new TreeMap<WorkBibDocumentSearchResult, WorkBibMarcRecord>(new ImportBibService());
156                for(int i=0; i<importBibResultsList.size() ; i++){
157                    marcDocRecMapSorted.put(importBibResultsList.get(i) ,importBibForm.getWorkBibMarcRecordList().get(i)) ;
158                }
159                importBibForm.setMarcDocRecMap(marcDocRecMapSorted);
160                List<WorkBibDocumentSearchResult> searchList = new ArrayList<WorkBibDocumentSearchResult>();
161                searchList.addAll(importBibForm.getMarcDocRecMap().keySet());
162                // adding the sorted key values to search results list to display in seacrch table
163                importBibForm.getImportBibSearch().setLocalBibDocumentSearchResults(searchList);
164            }
165            return getUIFModelAndView(importBibForm);
166        }
167    
168    
169        @RequestMapping(params = "methodToCall=search")
170        public ModelAndView search(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
171                                   HttpServletRequest request, HttpServletResponse response) throws Exception {
172            LOG.info("Inside Search Method");
173            ImportBibForm importBibForm = (ImportBibForm) form;
174            SearchParams searchParams = importBibForm.getSearchParams();
175            List<SearchCondition> searchFieldsList = searchParams.getSearchFieldsList();
176            for (SearchCondition searchCondition : searchParams.getSearchFieldsList()) {
177                LOG.debug("getSearchText..." + searchCondition.getSearchText());
178                LOG.debug("getSearchScope..." + searchCondition.getSearchScope());
179                LOG.debug("getDocField..." + searchCondition.getDocField());
180                LOG.debug("getOperator..." + searchCondition.getOperator());
181            }
182            String source = importBibForm.getImportBibSearch().getSource();
183            if (source != null && source.length() > 0) {
184                DataSourceConfig dataSourceConfig = new DataSourceConfig();
185                BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
186                Map parentCriteria = new HashMap();
187                parentCriteria.put("id", source);
188                ExternalDataSourceConfig externalDataSourceConfig = new ExternalDataSourceConfig();
189                externalDataSourceConfig = businessObjectService
190                        .findByPrimaryKey(ExternalDataSourceConfig.class, parentCriteria);
191                dataSourceConfig.setDomainName(externalDataSourceConfig.getDomainName());
192                dataSourceConfig.setPortNum(externalDataSourceConfig.getPortNum());
193                ExternalDataSource externalDataSource = ExternalDataSourceFactory.getInstance().getExternalDataSource(dataSourceConfig);
194                List<String> results = null;
195                // NOTE: Uncomment this line to enable Searching external Z39.50 data sources.
196                //List<String> results = externalDataSource.searchForBibs(searchParams,dataSourceConfig);
197                request.getSession().setAttribute("showDetailForExternalSearchRecord", results);
198                WorkBibMarcRecords marcRecords = prepareWorkBibMarcRecords(results);
199                //   WorkBibMarcRecords marcRecords =  externalDataSource.searchForBibs(searchParams,dataSourceConfig);
200                if (marcRecords != null) {
201                    importBibForm.setWorkBibMarcRecordList(marcRecords.getRecords());
202                }
203                WorkBibDocConverter workBibDocConverter = new WorkBibDocConverter();
204                List<WorkBibDocument> workBibDocumentList = workBibDocConverter.convert(marcRecords);
205                List<WorkBibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocumentList);
206                SortedMap<WorkBibDocumentSearchResult, WorkBibMarcRecord> marcDocRecMapSorted = new TreeMap<WorkBibDocumentSearchResult, WorkBibMarcRecord>(new ImportBibService());
207                for (int i = 0; i < importBibResultsList.size(); i++) {
208                    marcDocRecMapSorted.put(importBibResultsList.get(i), importBibForm.getWorkBibMarcRecordList().get(i));
209                }
210    
211                importBibForm.setMarcDocRecMap(marcDocRecMapSorted);
212                List<WorkBibDocumentSearchResult> searchList = new ArrayList<WorkBibDocumentSearchResult>();
213                searchList.addAll(importBibForm.getMarcDocRecMap().keySet());
214                // adding the sorted key values to search results list to display in seacrch table
215                importBibForm.getImportBibSearch().setExternalBibDocumentSearchResults(searchList);
216                importBibForm.getImportBibSearch().setReturnCheck(true);
217            } else {
218                LOG.debug("ImportBibController :search : No source selected...");
219            }
220    
221            return getUIFModelAndView(importBibForm);
222        }
223        public WorkBibMarcRecords prepareWorkBibMarcRecords(List<String> results) {
224            //OCLCResponseHandler oclcResponseHandler = new OCLCResponseHandler();
225            MRKToMARCXMLConverter mrkToMARCXMLConverter  = new MRKToMARCXMLConverter();
226            StringBuffer sb = new StringBuffer(
227                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><collection xmlns=\"http://www.loc.gov/MARC21/slim\">");
228            for (String marcString : results) {
229                String marcXML = mrkToMARCXMLConverter.convert(marcString);
230                sb.append(marcXML.substring(marcXML.indexOf("<record>"), marcXML.indexOf("</collection>")));
231            }
232            sb.append("</collection>");
233            String marcXmlContent = sb.toString();
234            WorkBibMarcRecordProcessor workBibMarcRecordProcessor = new WorkBibMarcRecordProcessor();
235            WorkBibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(marcXmlContent);
236            return marcRecords;
237        }
238        /**
239         * @param form
240         * @param result
241         * @param request
242         * @param response
243         * @return
244         */
245        @RequestMapping(params = "methodToCall=clearSearch")
246        public ModelAndView clearSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
247                                        HttpServletRequest request, HttpServletResponse response) {
248            LOG.info("Inside clearSearch Method");
249            ImportBibForm importBibForm = (ImportBibForm) form;
250            importBibForm.getImportBibSearch().setReturnCheck(true);
251            importBibForm.getImportBibSearch().setExternalBibDocumentSearchResults(null);
252            importBibForm.getImportBibSearch().setSource("");
253            List<SearchCondition> searchConditions = new ArrayList<SearchCondition>();
254            searchConditions.add(new SearchCondition());
255            searchConditions.add(new SearchCondition());
256            importBibForm.getSearchParams().setSearchFieldsList(searchConditions);
257            return getUIFModelAndView(importBibForm);
258        }
259    
260        /**
261         * @param form
262         * @param result
263         * @param request
264         * @param response
265         * @return
266         */
267        @RequestMapping(params = "methodToCall=clearFile")
268        public ModelAndView clearFile(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
269                                      HttpServletRequest request, HttpServletResponse response) {
270            LOG.info("Inside clearSearch Method");
271    
272            ImportBibForm importBibForm = (ImportBibForm) form;
273            importBibForm.getImportBibSearch().setReturnCheck(false);
274            importBibForm.getImportBibSearch().setLocalBibDocumentSearchResults(null);
275            importBibForm.getImportBibSearch().setSelectedFileName("");
276            importBibForm.getImportBibSearch().setRecordsInFile(0);
277            importBibForm.getImportBibSearch().setRecordsImported(0);
278            return getUIFModelAndView(importBibForm);
279        }
280    
281        @RequestMapping(params = "methodToCall=actionLink")
282        public ModelAndView actionLink(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
283                                       HttpServletRequest request, HttpServletResponse response) {
284            ImportBibForm importBibForm = (ImportBibForm) form;
285            int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
286            List<WorkBibMarcRecord> marcRecList = importBibForm.getWorkBibMarcRecordList();
287            WorkBibMarcRecord marcRec = marcRecList.get(index);
288            LOG.info("Marc Rec is..." + marcRec);
289            return getUIFModelAndView(importBibForm);
290        }
291    
292        @RequestMapping(params = "methodToCall=localNext")
293        public ModelAndView next(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
294                                 HttpServletRequest request, HttpServletResponse response) {
295            ImportBibForm importBibForm = (ImportBibForm) form;
296            if (importBibForm != null && importBibForm.getImportBibSearch() != null
297                    && importBibForm.getImportBibSearch().getLocalBibDocumentSearchResults() != null) {
298                List<WorkBibDocumentSearchResult> workBibDocumentSearchResultList = importBibForm.getImportBibSearch()
299                        .getLocalBibDocumentSearchResults();
300                boolean isSelected = true;
301                int i = 0;
302                for (WorkBibDocumentSearchResult workBibDocumentResult : workBibDocumentSearchResultList) {
303                    i++;
304                    if (workBibDocumentResult.isSelectedMarc() && isSelected) {
305                        isSelected = false;
306                        importBibForm.getImportBibSearch().setSelectedMarc(
307                                importBibForm.getImportBibSearch().getLocalBibDocumentSearchResults().get(i - 1));
308                        importBibForm.setNewWorkBibMarcRecord(importBibForm.getMarcDocRecMap().get(workBibDocumentResult));
309                        importBibForm.getImportBibSearch().setSelectedRecordIndex(i - 1);
310                    }
311                }
312                if (isSelected) {
313                    importBibForm.setMessage("Please select a bib record to continue the process");
314                    return getUIFModelAndView(importBibForm, "SearchBibViewPage");
315                }
316            }
317            importBibForm.setMessage(null);
318            return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
319        }
320    
321        @RequestMapping(params = "methodToCall=externalNext")
322        public ModelAndView externalNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
323                                         HttpServletRequest request, HttpServletResponse response) {
324            ImportBibForm importBibForm = (ImportBibForm) form;
325            if (importBibForm != null && importBibForm.getImportBibSearch() != null
326                    && importBibForm.getImportBibSearch().getExternalBibDocumentSearchResults() != null) {
327                List<WorkBibDocumentSearchResult> workBibDocumentSearchResultList = importBibForm.getImportBibSearch()
328                        .getExternalBibDocumentSearchResults();
329                boolean isSelected = true;
330                int i = 0;
331                for (WorkBibDocumentSearchResult workBibDocumentResult : workBibDocumentSearchResultList) {
332                    i++;
333                    if (workBibDocumentResult.isSelectedExternalMarc() && isSelected) {
334                        isSelected = false;
335                        importBibForm.getImportBibSearch().setSelectedMarc(
336                                importBibForm.getImportBibSearch().getExternalBibDocumentSearchResults().get(i - 1));
337                        importBibForm.setNewWorkBibMarcRecord(importBibForm.getMarcDocRecMap().get(workBibDocumentResult));
338                        importBibForm.getImportBibSearch().setSelectedRecordIndex(i - 1);
339                    }
340                }
341                if (isSelected) {
342                    importBibForm.setMessage("Please select a bib record to continue the process");
343                    return getUIFModelAndView(importBibForm, "SearchBibViewPage");
344                }
345            }
346            importBibForm.setMessage(null);
347            return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
348        }
349        @RequestMapping(params = "methodToCall=loadUserPref")
350        public ModelAndView loadUserPref(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
351                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
352            ImportBibForm importBibForm = (ImportBibForm) form;
353            ImportBibUserPreferences importBibUserPreferences = importBibForm.getImportBibUserPreferences();
354            if (importBibUserPreferences.getPrefId1().length() > 0) {
355                importBibUserPreferences.setPrefId(Integer.valueOf(importBibUserPreferences.getPrefId1()));
356                if (importBibUserPreferences.getPrefId() != null && importBibUserPreferences.getPrefId() > 0) {
357                    BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
358                    Map parentCriteria = new HashMap();
359                    parentCriteria.put("prefId", importBibUserPreferences.getPrefId());
360                    importBibUserPreferences = businessObjectService
361                            .findByPrimaryKey(ImportBibUserPreferences.class, parentCriteria);
362                    importBibForm.setImportBibUserPreferences(importBibUserPreferences);
363                    parentCriteria.put("prefId", 1);
364                    ImportBibUserPreferences importBibAdminPreferences = businessObjectService
365                            .findByPrimaryKey(ImportBibUserPreferences.class, parentCriteria);
366                    importBibForm.getImportBibUserPreferences()
367                            .setAdminProtectedTags(importBibAdminPreferences.getProtectedTags());
368                    importBibForm.getImportBibUserPreferences().setAdminRemovalTags(importBibAdminPreferences.getRemovalTags());
369                }
370                importBibUserPreferences.setPrefId1(String.valueOf(importBibUserPreferences.getPrefId()));
371            }
372    
373            if (importBibForm.getExistingWorkBibMarcRecord() != null) {
374                //converting marc record to WorkBibDocument
375                WorkBibMarcRecords marcRecords = new WorkBibMarcRecords();
376                List<WorkBibMarcRecord> workBibMarcRecordList = new ArrayList<WorkBibMarcRecord>();
377                workBibMarcRecordList.add(importBibForm.getExistingWorkBibMarcRecord());
378                marcRecords.setRecords(workBibMarcRecordList);
379                WorkBibDocConverter workBibDocConverter = new WorkBibDocConverter();
380                List<WorkBibDocument> workBibDocumentList = workBibDocConverter.convert(marcRecords);
381                //setting uuid (control field 001) to WorkBibMarc Document
382                for (ControlField cf : importBibForm.getExistingWorkBibMarcRecord().getControlFields()) {
383                    if (cf.getTag().equalsIgnoreCase("001")) {
384                        workBibDocumentList.get(0).setId(cf.getValue());
385                        break;
386                    }
387                }
388                // getting workbibdocument with Instance data.
389                DocstoreHelperService helperService = new DocstoreHelperService();
390                List<WorkBibDocument> workBibDocuments = helperService.getInfoForBibTree(workBibDocumentList);
391                List<WorkBibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocuments);
392                // setting workbibDocument to OverLayMarcRecord
393                if (importBibForm.getImportBibConfirmReplace() != null && importBibResultsList != null
394                        && importBibResultsList.size() > 0) {
395                    importBibForm.getImportBibConfirmReplace().setOverLayMarcRecord(importBibResultsList.get(0));
396                }
397            }
398            if (importBibForm.getExistingWorkBibMarcRecord() != null) {
399                importBibUserPreferences.setImportType("overLay");
400            } else if (importBibUserPreferences != null && "overLay".equalsIgnoreCase(importBibUserPreferences.getImportType())) {
401                importBibUserPreferences.setImportType("newImport");
402            }
403    
404            return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
405        }
406    
407    
408        @RequestMapping(params = "methodToCall=userPrefNext")
409        public ModelAndView userPrefNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
410                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
411            ImportBibForm importBibForm = (ImportBibForm) form;
412            ImportBibUserPreferences importBibUserPreferences = importBibForm.getImportBibUserPreferences();
413            ImportBibService importBibService = new ImportBibService();
414            if (importBibService.callNumValidation(importBibUserPreferences)) {
415                importBibForm.setMessage("Please enter a valid data field value in call number. Ex:050");
416                return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
417            }
418            if (importBibService.proNRemTagValidation(importBibUserPreferences)) {
419                importBibForm
420                        .setMessage("Please enter valid data field values in Protected / Removal Tags. Ex: 035,040,651");
421                return getUIFModelAndView(importBibForm, "UserPreferenceViewPage");
422            }
423            importBibForm.setMessage(null);
424            importBibService.applyUserPref(importBibForm);
425            request.getSession().setAttribute("importBibForm", importBibForm);
426            Request req = importBibService
427                    .buildRequest(importBibForm.getNewWorkBibMarcRecord(), importBibForm.getNewInstanceCollection(), importBibUserPreferences.getImportStatus());
428            request.getSession().setAttribute("requestObject", req);
429            if (!importBibUserPreferences.getImportType().equalsIgnoreCase("newImport")) {
430                return getUIFModelAndView(importBibForm, "ConfirmReplace");
431            }
432            try {
433                String url = PropertyUtil.getPropertyUtil().getProperty("ole.rice2.url.base");
434                response.sendRedirect(url + "/portal.do?channelTitle=Import Bib&channelUrl=" + url +
435                        "/kr-krad/editorcontroller?viewId=EditorView&methodToCall=load&docCategory=work&docType=bibliographic&docFormat=marc&loadFromSession=true&editable=true");
436            }
437            catch (Exception e) {
438                LOG.error("Exception while forwarding to editor." + e);
439            }
440            return getUIFModelAndView(importBibForm, "ConfirmImport");
441        }
442    
443    
444        @RequestMapping(params = "methodToCall=loadImportBibSearch")
445        public ModelAndView loadImportBibSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
446                                                HttpServletRequest request, HttpServletResponse response)
447                throws IOException, ServletException {
448            LOG.info("Inside confirmReplaceNext Method");
449            ImportBibForm importBibForm = (ImportBibForm) form;
450            if (importBibForm != null && importBibForm.getImportBibSearch() != null) {
451                if (importBibForm.getMarcDocRecMap() != null && importBibForm.getImportBibSearch() != null &&
452                        importBibForm.getImportBibSearch().getSelectedMarc() != null &&
453                        importBibForm.getMarcDocRecMap().get(importBibForm.getImportBibSearch().getSelectedMarc()) != null) {
454    
455                    importBibForm.getMarcDocRecMap().remove(importBibForm.getImportBibSearch().getSelectedMarc());
456                    List<WorkBibDocumentSearchResult> localRecList = new ArrayList<WorkBibDocumentSearchResult>();
457                    List<WorkBibMarcRecord> marcRecList = new ArrayList<WorkBibMarcRecord>();
458                    for (Map.Entry<WorkBibDocumentSearchResult, WorkBibMarcRecord> record : importBibForm.getMarcDocRecMap().entrySet()) {
459                        localRecList.add(record.getKey());
460                        marcRecList.add(record.getValue());
461                    }
462                    importBibForm.getImportBibSearch().setLocalBibDocumentSearchResults(localRecList);
463                    importBibForm.setWorkBibMarcRecordList(marcRecList);
464                }
465                importBibForm.getMarcDocRecMap().remove(importBibForm.getImportBibSearch().getSelectedMarc());
466                importBibForm.getImportBibSearch()
467                        .setRecordsImported(importBibForm.getImportBibSearch().getRecordsImported() + 1);
468                importBibForm.getImportBibSearch()
469                        .setRecordsInFile(importBibForm.getImportBibSearch().getRecordsInFile() - 1);
470            }
471    
472            return getUIFModelAndView(importBibForm, "SearchBibViewPage");
473        }
474    
475        @RequestMapping(params = "methodToCall=viewRecordNext")
476        public ModelAndView viewRecordNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
477                                           HttpServletRequest request, HttpServletResponse response)
478                throws IOException, SolrServerException {
479            LOG.info("Inside Search Method");
480            ImportBibForm importBibForm = (ImportBibForm) form;
481            String resp = null;
482            if (request != null && request.getSession() != null) {
483                resp = (String) request.getSession().getAttribute("responseString");
484                if (request.getSession().getAttribute("importBibForm") != null) {
485                    ImportBibForm importBibForminSession = (ImportBibForm) request.getSession()
486                                                                                  .getAttribute("importBibForm");
487                    importBibForm.setImportBibSearch(importBibForminSession.getImportBibSearch());
488                    importBibForm.setWorkBibMarcRecordList(importBibForminSession.getWorkBibMarcRecordList());
489                    importBibForm.setBibUuidsList(importBibForminSession.getBibUuidsList());
490                    importBibForm.setMarcDocRecMap(importBibForminSession.getMarcDocRecMap());
491                    request.getSession().removeAttribute("importBibForm");
492                }
493                request.getSession().removeAttribute("requestObject");
494                request.getSession().removeAttribute("responseString");
495            }
496    
497            List<WorkBibDocument> bibDocumentList = new ArrayList<WorkBibDocument>();
498    
499            if (resp != null) {
500                ResponseHandler respConverter = new ResponseHandler();
501                resp = resp.trim();
502                Response responseObj = respConverter.toObject(resp);
503                QueryService queryService = QueryServiceImpl.getInstance();
504                for (ResponseDocument respDoc : responseObj.getDocuments()) {
505                    WorkBibDocument workBibDocument = new WorkBibDocument();
506                    workBibDocument.setId(respDoc.getUuid());
507                    workBibDocument = queryService.buildBibDocumentInfo(workBibDocument);
508                    bibDocumentList.add(workBibDocument);
509                    importBibForm.setUuid(respDoc.getUuid());
510                }
511            }
512    
513            List<WorkBibDocumentSearchResult> uuidList = importBibForm.getBibUuidsList();
514            WorkBibDocumentSearchResult workBibDocumentSearchResult = new WorkBibDocumentSearchResult();
515    
516            for (WorkBibDocument workBibDocument : bibDocumentList) {
517                workBibDocumentSearchResult = new WorkBibDocumentSearchResult();
518                if (workBibDocument.getTitle() != null) {
519                    workBibDocumentSearchResult.setDisplayField(workBibDocument.getTitle());
520                    workBibDocumentSearchResult.setUuid(workBibDocument.getId());
521                }
522                uuidList.add(workBibDocumentSearchResult);
523            }
524    
525            importBibForm.setBibUuidsList(uuidList);
526    
527    
528            return getUIFModelAndView(importBibForm, "ConfirmImport");
529        }
530    
531    
532        @RequestMapping(params = "methodToCall=confirmReplaceNext")
533        public ModelAndView confirmReplaceNext(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
534                                               HttpServletRequest request, HttpServletResponse response)
535                throws IOException, ServletException {
536            LOG.info("Inside loadImportBibSearch Method");
537            ImportBibForm importBibForm = (ImportBibForm) form;
538    
539            try {
540                String url = PropertyUtil.getPropertyUtil().getProperty("ole.rice2.url.base");
541                response.sendRedirect(url + "/portal.do?channelTitle=Import Bib&channelUrl=" + url
542                        + "/kr-krad/editorcontroller?viewId=EditorView&methodToCall=load&docCategory=work&docType=bibliographic&docFormat=marc&loadFromSession=true&editable=true&docId="
543                        + importBibForm.getUuid());
544            }
545            catch (Exception e) {
546                LOG.error("Exception while forwarding to editor." + e);
547    
548            }
549    
550            //        return getUIFModelAndView(importBibForm, "ConfirmImport");
551            return getUIFModelAndView(importBibForm, "ConfirmImport");
552        }
553    
554        private String getMarcXml(MultipartFile file) throws IOException {
555            String marcXMLContent = null;
556            String modifiedXMLContent = null;
557            MultipartFile multipartFile = file;
558            String locationFileName = multipartFile.getOriginalFilename();
559            if (locationFileName.endsWith(".mrc")) {
560                String fileContent = new String(multipartFile.getBytes());
561    
562                MarcXMLConverter marcXMLConverter = new MarcXMLConverter();
563                marcXMLContent = marcXMLConverter.convert(fileContent);
564                modifiedXMLContent = marcXMLContent.replace(
565                        "collection xmlns=\"http://www.loc.gov/MARC21/slim\" xmlns=\"http://www.loc.gov/MARC21/slim",
566                        "collection xmlns=\"http://www.loc.gov/MARC21/slim");
567            }
568            return modifiedXMLContent;
569    
570        }
571    
572        private List<WorkBibDocumentSearchResult> mapMarcFieldValues(List<WorkBibDocument> workBibDocumentList) {
573            List<WorkBibDocumentSearchResult> importBibResultsList = new ArrayList<WorkBibDocumentSearchResult>();
574            WorkBibDocumentSearchResult workBibDocument = new WorkBibDocumentSearchResult();
575            for (WorkBibDocument bibDoc : workBibDocumentList) {
576                workBibDocument.setId(bibDoc.getId());
577                workBibDocument.setAuthor(bibDoc.getAuthor());
578                workBibDocument.setTitle(bibDoc.getTitle());
579                workBibDocument.setPublicationDate(bibDoc.getPublicationDate());
580                workBibDocument.setEdition(bibDoc.getEdition());
581                workBibDocument.setWorkInstanceDocumentList(bibDoc.getWorkInstanceDocumentList());
582                importBibResultsList.add(workBibDocument);
583                workBibDocument = new WorkBibDocumentSearchResult();
584            }
585            return importBibResultsList;
586        }
587    
588        @RequestMapping(params = "methodToCall=showDetailForLocalSearchRecord")
589        public ModelAndView showDetailForLocalSearchRecord(@ModelAttribute("KualiForm") UifFormBase form,
590                                                           BindingResult result, HttpServletRequest request,
591                                                           HttpServletResponse response) throws Exception {
592            MRKToMARCXMLConverter mrkToMARCXMLConverter = new MRKToMARCXMLConverter();
593            String bibId = request.getParameter("bibId");
594            LOG.info("showDetailForLocalSearchRecord bibId " + bibId);
595            ImportBibForm importBibForm = (ImportBibForm) form;
596            String marcXmlContent = (String) request.getSession().getAttribute("showDetailForLocalSearchRecord");
597            SortedMap<WorkBibDocumentSearchResult, WorkBibMarcRecord> marcDocRecMapSorted = sort(marcXmlContent);
598            List<WorkBibDocumentSearchResult> searchList = new ArrayList<WorkBibDocumentSearchResult>();
599            searchList.addAll(marcDocRecMapSorted.keySet());
600            if (marcXmlContent != null && marcXmlContent.length() > 0) {
601                WorkBibMarcRecordProcessor workBibMarcRecordProcessor = new WorkBibMarcRecordProcessor();
602                WorkBibMarcRecord workBibMarcRecord = marcDocRecMapSorted.get(searchList.get(Integer.parseInt(bibId)));
603                List<WorkBibMarcRecord> workBibMarcRecordList = new ArrayList<WorkBibMarcRecord>();
604                workBibMarcRecordList.add(workBibMarcRecord);
605                WorkBibMarcRecords marcRecordsNew = new WorkBibMarcRecords();
606                marcRecordsNew.setRecords(workBibMarcRecordList);
607                String detailXML = workBibMarcRecordProcessor.toXml(marcRecordsNew);
608                LOG.info("detailXML " + detailXML);
609                String marc = mrkToMARCXMLConverter.ConvertMarcXMLToMRK(detailXML);
610                importBibForm.setMessage("<pre>" + marc + "</pre>");
611                LOG.info("marc " + marc);
612            }
613            return getUIFModelAndView(form);
614        }
615    
616        @RequestMapping(params = "methodToCall=showDetailForExternalSearchRecord")
617        public ModelAndView showDetailForExternalSearchRecord(@ModelAttribute("KualiForm") UifFormBase form,
618                                                              BindingResult result, HttpServletRequest request,
619                                                              HttpServletResponse response) {
620            String bibId = request.getParameter("bibId");
621            ImportBibForm importBibForm = (ImportBibForm) form;
622            List<String> results = (List<String>) request.getSession().getAttribute("showDetailForExternalSearchRecord");
623            String resultvalue = results.get(Integer.parseInt(bibId));
624            importBibForm.setMessage("<pre>" + resultvalue + "</pre>");
625            return getUIFModelAndView(form);
626        }
627    
628        public SortedMap<WorkBibDocumentSearchResult, WorkBibMarcRecord> sort(String marcXmlContent) {
629            if (marcXmlContent != null && marcXmlContent.length() > 0) {
630                //convert xml to pojo
631                WorkBibMarcRecordProcessor workBibMarcRecordProcessor = new WorkBibMarcRecordProcessor();
632                WorkBibMarcRecords marcRecords = workBibMarcRecordProcessor.fromXML(marcXmlContent);
633                List<WorkBibMarcRecord> workBibMarcRecordList = marcRecords.getRecords();
634                // convert pojo to workBibDoc
635                WorkBibDocConverter workBibDocConverter = new WorkBibDocConverter();
636                List<WorkBibDocument> workBibDocumentList = workBibDocConverter.convert(marcRecords);
637                List<WorkBibDocumentSearchResult> importBibResultsList = mapMarcFieldValues(workBibDocumentList);
638                // Sorting the import bib result list and mapping it to corresponding marc record
639                SortedMap<WorkBibDocumentSearchResult, WorkBibMarcRecord> marcDocRecMapSorted
640                        = new TreeMap<WorkBibDocumentSearchResult, WorkBibMarcRecord>(new ImportBibService());
641                for (int i = 0; i < importBibResultsList.size(); i++) {
642                    marcDocRecMapSorted.put(importBibResultsList.get(i), workBibMarcRecordList.get(i));
643                }
644                return marcDocRecMapSorted;
645            } else {
646                SortedMap<WorkBibDocumentSearchResult, WorkBibMarcRecord> marcDocRecMapSortedZero
647                        = new TreeMap<WorkBibDocumentSearchResult, WorkBibMarcRecord>(new ImportBibService());
648                return marcDocRecMapSortedZero;
649            }
650        }
651    
652    }