View Javadoc
1   package org.kuali.ole.docstore.document.jcr;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.apache.solr.common.SolrDocument;
5   import org.kuali.ole.docstore.OleDocStoreException;
6   import org.kuali.ole.docstore.common.document.content.instance.*;
7   import org.kuali.ole.docstore.common.document.content.instance.xstream.InstanceOlemlRecordProcessor;
8   import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
9   import org.kuali.ole.docstore.common.document.content.instance.xstream.SourceHoldingOlemlRecordProcessor;
10  import org.kuali.ole.docstore.document.DocumentManager;
11  import org.kuali.ole.docstore.model.enums.DocCategory;
12  import org.kuali.ole.docstore.model.enums.DocFormat;
13  import org.kuali.ole.docstore.model.enums.DocType;
14  import org.kuali.ole.docstore.model.xmlpojo.ingest.*;
15  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
16  import org.kuali.ole.docstore.process.ProcessParameters;
17  import org.kuali.ole.docstore.repository.WorkBibNodeManager;
18  import org.kuali.ole.docstore.repository.WorkInstanceNodeManager;
19  import org.kuali.ole.docstore.service.BeanLocator;
20  import org.kuali.ole.docstore.service.ServiceLocator;
21  import org.kuali.ole.docstore.util.ItemExistsException;
22  import org.kuali.ole.pojo.OleException;
23  import org.kuali.ole.utility.callnumber.CallNumberFactory;
24  import org.kuali.ole.utility.callnumber.CallNumberType;
25  import org.slf4j.Logger;
26  import org.slf4j.LoggerFactory;
27  
28  import javax.jcr.Node;
29  import javax.jcr.NodeIterator;
30  import javax.jcr.RepositoryException;
31  import javax.jcr.Session;
32  import java.io.FileNotFoundException;
33  import java.util.*;
34  
35  import static org.kuali.ole.docstore.process.ProcessParameters.FILE;
36  
37  /**
38   * Implements the DocumentManager interface for [Work-Instance-*] documents.
39   *
40   * @version %I%, %G%
41   * @author: tirumalesh.b
42   * Date: 31/8/12 Time: 7:04 PM
43   */
44  
45  public class JcrWorkInstanceDocumentManager
46          extends JcrAbstractDocumentManager {
47  
48      private static JcrWorkInstanceDocumentManager ourInstanceJcr = null;
49      private InstanceOlemlRecordProcessor olemlProcessor = new InstanceOlemlRecordProcessor();
50      private static final Logger LOG = LoggerFactory
51              .getLogger(JcrWorkInstanceDocumentManager.class);
52  
53      public static JcrWorkInstanceDocumentManager getInstance() {
54          if (null == ourInstanceJcr) {
55              ourInstanceJcr = new JcrWorkInstanceDocumentManager();
56          }
57          return ourInstanceJcr;
58      }
59  
60      protected JcrWorkInstanceDocumentManager() {
61          super();
62          this.nodeManager = WorkInstanceNodeManager.getInstance();
63      }
64  
65      @Override
66      public void modifyDocumentContent(RequestDocument document, String nodeIdentifier, String parentNodeIdentifier) {
67  
68  
69          if (document.getContent().getContentObject() instanceof OleHoldings) { // holdings
70              ((OleHoldings) document.getContent().getContentObject()).setHoldingsIdentifier(nodeIdentifier);
71              document.getContent()
72                      .setContent(olemlProcessor.toXML((OleHoldings) document.getContent().getContentObject()));
73          } else if (document.getContent().getContentObject() instanceof SourceHoldings) { // source holdings.
74              ((SourceHoldings) document.getContent().getContentObject()).setHoldingsIdentifier(nodeIdentifier);
75              document.getContent()
76                      .setContent(olemlProcessor.toXML((SourceHoldings) document.getContent().getContentObject()));
77          } else if (document.getContent().getContentObject() instanceof Item) { // item
78              ((Item) document.getContent().getContentObject()).setItemIdentifier(nodeIdentifier);
79              document.getContent().setContent(olemlProcessor.toXML((Item) document.getContent().getContentObject()));
80          } else if (document.getContent().getContentObject() instanceof Instance) { // instance
81              Instance inst = ((Instance) document.getContent().getContentObject());
82              inst.setInstanceIdentifier(parentNodeIdentifier);
83              InstanceCollection instanceCollection = new InstanceCollection();
84              ArrayList<Instance> oleinsts = new ArrayList<Instance>();
85              oleinsts.add(inst);
86              instanceCollection.setInstance((oleinsts));
87              document.getContent().setContent(olemlProcessor.toXML(instanceCollection));
88          }
89      }
90  
91      @Override
92      public Node storeDocument(RequestDocument requestDocument, Object object, ResponseDocument responseDocument) throws OleDocStoreException {
93          Session session = (Session) object;
94          Node fileNode = null;
95          String validateMsg = null;
96          try {
97              AdditionalAttributes additionalAttributes = requestDocument.getAdditionalAttributes();
98              modifyAdditionalAttributes(requestDocument, null);
99  
100             // get the parent node
101             Node parentNode = nodeManager.getParentNode(requestDocument, session);
102             String fileName = requestDocument.getFormat() + FILE;
103 
104             // create the file node
105             fileNode = nodeManager.createFileNode(requestDocument, fileName, parentNode, session);
106 
107             if (isVersioningEnabled()) {
108                 nodeManager.enableVersioning(fileNode);
109             }
110             if (requestDocument.getContent().getContentObject() != null) {
111                 InstanceCollection instColl = (InstanceCollection) requestDocument.getContent().getContentObject();
112                 for (Instance inst : instColl.getInstance()) {
113                     List<String> resIdList = new ArrayList<String>();
114                     resIdList.addAll(inst.getResourceIdentifier());
115                     for (String resId : inst.getResourceIdentifier()) {
116                         if (resId != null && resId.length() > 0) {
117                             try {
118                                 Node bibNode = nodeManager.getNodeByUUID(session, resId);
119                                 WorkBibNodeManager bibNodeManager = WorkBibNodeManager.getInstance();
120                                 bibNodeManager.linkNodes(bibNode, fileNode, session);
121                             } catch (Exception e) {
122                                 resIdList.remove(resId);
123                             }
124                         }
125                     }
126                     inst.setResourceIdentifier(resIdList);
127                 }
128             }
129             buildResponseDocument(requestDocument, session, responseDocument);
130             if (validateMsg != null) {
131                 LOG.debug("in if validation message not null-->" + validateMsg);
132                 responseDocument.setStatusMessage(validateMsg);
133             } else {
134                 //LOG.info("in else if validation message null");
135                 responseDocument.setStatusMessage("Document ingested successfully.");
136             }
137         } catch (Exception e) {
138             throw new OleDocStoreException(e);
139         }
140         return fileNode;
141     }
142 
143     @Override
144     protected void modifyContent(RequestDocument reqDoc, Session session, Node nodeByUUID) throws RepositoryException, FileNotFoundException, OleDocStoreException {
145         setIdentifierValueInContent(reqDoc);
146         RequestDocument linkReqInfo = new RequestDocument();
147         if (reqDoc.getLinkedRequestDocuments() != null && reqDoc.getLinkedRequestDocuments().size() > 0) {
148             for (Iterator<RequestDocument> linkIterator = reqDoc.getLinkedRequestDocuments().iterator(); linkIterator
149                     .hasNext(); ) {
150                 linkReqInfo = linkIterator.next();
151                 if (linkReqInfo != null && linkReqInfo.getId() != null && linkReqInfo.getType().equalsIgnoreCase(
152                         DocType.INSTANCE.getCode())) {
153                     if (nodeByUUID.hasProperty("instanceIdentifier")) {
154                         String instanceIds = nodeByUUID.getProperty("instanceIdentifier").getString() + "," + linkReqInfo.getId();
155                         nodeByUUID.setProperty("instanceIdentifier", instanceIds);
156                     } else {
157                         nodeByUUID.setProperty("instanceIdentifier", linkReqInfo.getId());
158                     }
159                 }
160             }
161         }
162     }
163 
164     @Override
165     protected void addNewRecordsToDocStore(RequestDocument requestDocument, Session session)
166             throws OleDocStoreException {
167         if (requestDocument.getContent().getContent() == null && requestDocument.getId() != null) {
168             for (RequestDocument linkedItemDocument : requestDocument.getLinkedRequestDocuments()) {
169                 if (DocType.ITEM.getDescription().equalsIgnoreCase(linkedItemDocument.getType())
170                         && linkedItemDocument.getContent().getContent() != null) {
171                     nodeManager.ingestItemRecForInstance(linkedItemDocument, requestDocument.getId(), session);
172                 }
173             }
174         }
175     }
176 
177 /*    @Override
178     protected String updateIndex(RequestDocument requestDocument) throws OleDocStoreException {
179         String result = null;
180         if (DocType.SOURCEHOLDINGS.getCode().equalsIgnoreCase(requestDocument.getType())) {
181             return "success";
182         }
183         else {
184             result = updateRecord(requestDocument);
185         }
186         return result;
187     }*/
188 
189     @Override
190     public ResponseDocument bind(RequestDocument requestDocument, Object object, String operation) throws OleDocStoreException, RepositoryException, OleException, FileNotFoundException {
191         Session session = (Session) object;
192         List<RequestDocument> requestDocumentList = new ArrayList<RequestDocument>();
193         String bindFail = "binding failed";
194         try {
195 
196             // Store data in docstore.
197             updatePropertiesOfInstanceNode(requestDocument, session, operation);
198             updatePropertiesOfBibNodes(requestDocument, session, operation);
199             getContent(requestDocument, session);
200 /*
201             requestDocumentList.add(requestDocument);
202             Request request = new Request();
203             request.setRequestDocuments(requestDocumentList);
204 */
205             updateContentXmlOfInstance(requestDocument, session);
206 /*
207             Node nodeByUUID = session.getNodeByIdentifier(requestDocument.getUuid());
208             Property instanceNode = nodeByUUID.getProperty("bibIdentifier");
209 */
210 
211         } catch (Exception e) {
212             LOG.info(
213                     "Document was updated in indexer but not in docStore, trying to rollback the changes from indexer",
214                     e);
215 
216             LOG.info(bindFail, e);
217             throw new OleDocStoreException(bindFail, e);
218         }
219         return buildResponseForBind(requestDocument);
220     }
221 
222 
223     @Override
224     public ResponseDocument unbind(RequestDocument requestDocument, Object object, String operation) throws OleDocStoreException, RepositoryException, OleException, FileNotFoundException {
225         Session session = (Session) object;
226         List<RequestDocument> requestDocumentList = new ArrayList<RequestDocument>();
227         String bindFail = "unbinding failed";
228         try {
229 
230             // Store data in docstore.
231             updatePropertiesOfInstanceNode(requestDocument, session, operation);
232             updatePropertiesOfBibNodes(requestDocument, session, operation);
233             getContent(requestDocument, session);
234 /*
235             requestDocumentList.add(requestDocument);
236             Request request = new Request();
237             request.setRequestDocuments(requestDocumentList);
238 */
239             updateContentXmlOfInstance(requestDocument, session);
240 /*
241             Node nodeByUUID = session.getNodeByIdentifier(requestDocument.getUuid());
242             Property instanceNode = nodeByUUID.getProperty("bibIdentifier");
243 */
244 
245         } catch (Exception e) {
246             LOG.info(
247                     "Document was updated in indexer but not in docStore, trying to rollback the changes from indexer",
248                     e);
249 
250             LOG.info(bindFail, e);
251             throw new OleDocStoreException(bindFail, e);
252         }
253         return buildResponseForBind(requestDocument);
254     }
255 
256     @Override
257     public List<ResponseDocument> deleteVerify(List<RequestDocument> requestDocument, Object object) {
258         return null;  //To change body of implemented methods use File | Settings | File Templates.
259     }
260 
261     @Override
262     public ResponseDocument deleteVerify(RequestDocument requestDocument, Object object) throws Exception {
263         // List<String> bibIdentifierList = new ArrayList<String>();
264         Session session = (Session) object;
265         List<String> instanceIdentifierList = new ArrayList<String>();
266         ResponseDocument responseDocument = new ResponseDocument();
267         Node instanceNode = session.getNodeByIdentifier(requestDocument.getUuid());
268         String bibIdentifier = instanceNode.getProperty("bibIdentifier").getString();
269         String[] bibIds = bibIdentifier.split(",");
270         if (bibIds.length > 1) {
271             responseDocument.setCategory(requestDocument.getCategory());
272             responseDocument.setType(requestDocument.getType());
273             responseDocument.setFormat(requestDocument.getFormat());
274             responseDocument.setUuid(requestDocument.getUuid());
275             responseDocument.setStatus("failure'");
276             responseDocument.setStatusMessage("Instance is bound with more than one bib. So deletion cannot be done");
277             return responseDocument;
278         }
279         boolean exists = checkInstancesOrItemsExistsInOLE(requestDocument.getUuid(), session);
280         if (exists) {
281             responseDocument.setId(requestDocument.getId());
282             responseDocument.setCategory(requestDocument.getCategory());
283             responseDocument.setType(requestDocument.getType());
284             responseDocument.setFormat(requestDocument.getFormat());
285             responseDocument.setUuid(requestDocument.getUuid());
286             responseDocument.setStatus("failure'");
287             responseDocument.setStatusMessage("Instances or Items in use. So deletion cannot be done");
288             return responseDocument;
289         }
290 /*        String instanceIdentifier = "";
291         String bibIdentifierValue=bibIds[0]; // getting the first value from the bibIds array expecting that it has only one bib identifier otherwise it is bound with.
292         Node bibUUID = session.getNodeByIdentifier(bibIdentifierValue);
293             instanceIdentifier = bibUUID.getProperty("instanceIdentifier").getString();
294             String[] instanceIds = instanceIdentifier.split(",");
295             for (String instanceId : instanceIds) {
296                 instanceIdentifierList.add(instanceId);
297             }*/
298       /* if(instanceIdentifierList.size()==1){
299                 responseDocument.setUuid(bibIdentifierValue);
300                 responseDocument.setCategory(DocCategory.WORK.getCode());
301                 responseDocument.setType(DocType.BIB.getDescription());
302                 responseDocument.setFormat(DocFormat.MARC.getCode());
303                 responseDocument.setStatus("success");
304                 responseDocument.setStatusMessage("success");
305                // responseDocument = RdbmsWorkBibDocumentManager.getInstance().deleteVerify(requestDocument, session);
306             }
307         else{*/
308         responseDocument.setUuid(requestDocument.getUuid());
309         responseDocument.setId(requestDocument.getId());
310         responseDocument.setCategory(requestDocument.getCategory());
311         responseDocument.setType(requestDocument.getType());
312         responseDocument.setFormat(requestDocument.getFormat());
313         responseDocument.setStatus("success");
314         responseDocument.setStatusMessage("success");
315         // }
316         return responseDocument;
317     }
318 
319     @Override
320     public ResponseDocument delete(RequestDocument requestDocument, Object object) throws Exception {
321         Session session = (Session) object;
322         DocumentManager documentManager = null;
323         ResponseDocument responseDocument = new ResponseDocument();
324         ResponseDocument responseDocumentFromDeleteVerify = deleteVerify(requestDocument, session);
325 
326         String status = responseDocumentFromDeleteVerify.getStatus();
327         if (status.equalsIgnoreCase("success")) {
328             if (responseDocumentFromDeleteVerify.getCategory().equalsIgnoreCase("work")
329                     && responseDocumentFromDeleteVerify.getFormat().equalsIgnoreCase("marc") && responseDocumentFromDeleteVerify.getType()
330                     .equalsIgnoreCase(
331                             "bibliographic")) {
332                 RequestDocument requestDocumentForBib = prepareRequestDocument(responseDocumentFromDeleteVerify);
333                 documentManager = BeanLocator.getDocstoreFactory().getDocumentManager(requestDocumentForBib.getCategory(), requestDocumentForBib.getType(), requestDocumentForBib.getFormat());
334                 responseDocument = documentManager.delete(requestDocumentForBib, session);
335             } else if (responseDocumentFromDeleteVerify.getCategory().equalsIgnoreCase("work")
336                     && responseDocumentFromDeleteVerify.getFormat().equalsIgnoreCase("oleml") && responseDocumentFromDeleteVerify.getType()
337                     .equalsIgnoreCase(
338                             "instance")) {
339                 //                   documentManager = BeanLocator.getDocumentManagerFactory().getDocumentManager(requestDocument);
340                 //                   responseDocument= documentManager.delete(requestDocument, session);
341                 List<String> instanceIdentifierList = new ArrayList<String>();
342                 instanceIdentifierList.add(requestDocument.getUuid());
343                 deLinkInstanceFromBib(requestDocument.getUuid(), session);
344                 deleteFromRepository(instanceIdentifierList, session);
345             }
346         }
347 
348         return responseDocument;
349     }
350 
351     private void deLinkInstanceFromBib(String instanceIdentifier, Session session) throws Exception {
352         List<String> instanceIdentifierList = new ArrayList<String>();
353         Node instanceNode = session.getNodeByIdentifier(instanceIdentifier);
354         String bibIdentifier = instanceNode.getProperty("bibIdentifier").getString();
355         Node bibNode = session.getNodeByIdentifier(bibIdentifier);
356         String instanceIdentifiers = bibNode.getProperty("instanceIdentifier").getString();
357         String[] instanceIds = instanceIdentifiers.split(",");
358         StringBuffer instaceIdentifiersStringBuffer = new StringBuffer();
359         if (instanceIds.length > 1) {
360             for (String instanceId : instanceIds) {
361                 if (!instanceId.equalsIgnoreCase(instanceIdentifier)) {
362                     instaceIdentifiersStringBuffer.append(instanceId);
363                     instaceIdentifiersStringBuffer.append(",");
364                 }
365             }
366         }
367         String modifierInstanceIdentifiers = instaceIdentifiersStringBuffer.toString();
368         // String modified= modifierInstanceIdentifiers.substring(0, modifierInstanceIdentifiers.length() - 1);
369         //  bibNode.setProperty("instanceIdentifier",modified);
370         //str.substring(0,str.length()-1)
371         //modifierInstanceIdentifiers.
372 
373     }
374 
375     /**
376      * This method builds the response document after the bound-with process.
377      *
378      * @param requestDocument
379      * @return
380      */
381 
382     private ResponseDocument buildResponseForBind(RequestDocument requestDocument) {
383         ResponseDocument responseDocument = new ResponseDocument();
384         responseDocument.setId(requestDocument.getId());
385         responseDocument.setCategory(requestDocument.getCategory());
386         responseDocument.setType(requestDocument.getType());
387         responseDocument.setFormat(requestDocument.getFormat());
388         responseDocument.setUuid(requestDocument.getUuid());
389         List<RequestDocument> linkedRequestDocuments = requestDocument.getLinkedRequestDocuments();
390         List<ResponseDocument> linkedResponseDocumentsList = new ArrayList<ResponseDocument>();
391         for (RequestDocument linkedRequestDocument : linkedRequestDocuments) {
392 
393             ResponseDocument linkedResponseDocument = new ResponseDocument();
394             linkedResponseDocument.setCategory(linkedRequestDocument.getCategory());
395             linkedResponseDocument.setType(linkedRequestDocument.getType());
396             linkedResponseDocument.setFormat(linkedRequestDocument.getFormat());
397             linkedResponseDocument.setId(linkedRequestDocument.getId());
398             linkedRequestDocument.setUser(linkedRequestDocument.getUuid());
399             linkedResponseDocumentsList.add(linkedResponseDocument);
400 
401         }
402         responseDocument.setLinkedDocuments(linkedResponseDocumentsList);
403 
404 
405         return responseDocument;
406     }
407 
408     /**
409      * @param requestDocument
410      * @param session
411      * @param operation
412      * @throws RepositoryException
413      * @throws OleDocStoreException
414      * @throws OleException
415      */
416     private void updatePropertiesOfInstanceNode(RequestDocument requestDocument, Session session, String operation) throws RepositoryException, OleDocStoreException, OleException {
417         if (operation.equalsIgnoreCase("bind")) {
418             LOG.debug("requestDocument.getUuid()-->" + requestDocument.getUuid());
419             Node nodeByUUID = session.getNodeByIdentifier(requestDocument.getUuid());
420             StringBuilder bibIdentifierList = new StringBuilder();
421             LOG.info("bib id-->" + nodeByUUID.getProperty("bibIdentifier").getString());
422             String bibIdentifier = nodeByUUID.getProperty("bibIdentifier").getString();
423             bibIdentifierList.append(bibIdentifier);
424             List<RequestDocument> linkedRequestDocuments = requestDocument.getLinkedRequestDocuments();
425             for (RequestDocument linkedRequestDocument : linkedRequestDocuments) {
426 
427                 bibIdentifierList.append(",");
428                 bibIdentifierList.append(linkedRequestDocument.getUuid());
429             }
430             LOG.info("bibIdentifierList-->" + bibIdentifierList.toString());
431             nodeByUUID.setProperty("bibIdentifier", bibIdentifierList.toString());
432 
433             //session.save();
434         } else if (operation.equalsIgnoreCase("unbind")) {
435             Node nodeByUUID = session.getNodeByIdentifier(requestDocument.getUuid());
436             List<String> bibIdentifierList = new ArrayList<String>();
437             String bibIdentifier = nodeByUUID.getProperty("bibIdentifier").getString();
438             String[] bibIdentifierSplitter = bibIdentifier.split(",");
439             for (String bibId : bibIdentifierSplitter) {
440                 bibIdentifierList.add(bibId);
441 
442             }
443             List<RequestDocument> linkedRequestDocuments = requestDocument.getLinkedRequestDocuments();
444             for (RequestDocument linkedRequestDocument : linkedRequestDocuments) {
445                 if (bibIdentifierList.contains(linkedRequestDocument.getUuid())) {
446                     bibIdentifierList.remove(linkedRequestDocument.getUuid());
447                 }
448 
449             }
450             LOG.info("bibIdentifierList after removing the bibids-->" + bibIdentifierList.toString());
451             nodeByUUID.setProperty("bibIdentifier", bibIdentifierList.toString());
452 
453 
454         }
455 
456     }
457 
458     /**
459      * @param requestDocument
460      * @param session
461      * @throws OleDocStoreException
462      */
463     private void getContent(RequestDocument requestDocument, Session session) throws OleDocStoreException {
464         DocumentManager documentManager = BeanLocator.getDocstoreFactory().getDocumentManager(requestDocument.getCategory(), requestDocument.getType(), requestDocument.getFormat());
465         ResponseDocument responseDocument = documentManager.checkout(requestDocument, session);
466         requestDocument.setContent(responseDocument.getContent());
467         List<RequestDocument> linkedRequestDocuments = requestDocument.getLinkedRequestDocuments();
468 
469         for (RequestDocument linkedRequestDocument : linkedRequestDocuments) {
470             DocumentManager documentManagerForLink = BeanLocator.getDocstoreFactory().getDocumentManager(linkedRequestDocument.getCategory(), linkedRequestDocument.getType(), linkedRequestDocument.getFormat());
471             linkedRequestDocument.setContent(documentManagerForLink.checkout(linkedRequestDocument, session).getContent());
472 
473         }
474     }
475 
476     /**
477      * @param requestDocument
478      * @param object
479      * @param operation
480      * @throws RepositoryException
481      * @throws OleException
482      */
483     private void updatePropertiesOfBibNodes(RequestDocument requestDocument, Object object, String operation) throws RepositoryException, OleException {
484         Session session = (Session) object;
485         List<RequestDocument> linkedReqDocs = requestDocument.getLinkedRequestDocuments();
486         for (RequestDocument linkedReqDoc : linkedReqDocs) {
487             if (operation.equalsIgnoreCase("bind")) {
488 
489                 Node nodeByUUID = null;
490                 StringBuilder instanceIdentifierList = new StringBuilder();
491                 nodeByUUID = session.getNodeByIdentifier(linkedReqDoc.getUuid());
492                 String instanceIdentifier = nodeByUUID.getProperty("instanceIdentifier").getString();
493                 LOG.debug("instanceIdentifier id-->" + instanceIdentifier);
494                 instanceIdentifierList.append(instanceIdentifier);
495                 instanceIdentifierList.append(",");
496                 instanceIdentifierList.append(requestDocument.getUuid());
497                 LOG.info("instanceIdentifierList-->" + instanceIdentifierList.toString());
498                 nodeByUUID.setProperty("instanceIdentifier", instanceIdentifierList.toString());
499             } else if (operation.equalsIgnoreCase("unbind")) {
500                 Node nodeByUUID = null;
501                 List<String> instanceIdentifierList = new ArrayList<String>();
502                 nodeByUUID = session.getNodeByIdentifier(linkedReqDoc.getUuid());
503                 String instanceIdentifier = nodeByUUID.getProperty("instanceIdentifier").getString();
504                 LOG.debug("instanceIdentifier id-->" + instanceIdentifier);
505                 String[] instanceIdentifierSplitter = instanceIdentifier.split(",");
506                 for (String instanceId : instanceIdentifierSplitter) {
507                     instanceIdentifierList.add(instanceId);
508                 }
509                 if (instanceIdentifierList.contains(requestDocument.getUuid())) {
510                     instanceIdentifierList.remove(requestDocument.getUuid());
511                 }
512 
513                 LOG.info("instanceIdentifierList after remove-->" + instanceIdentifierList.toString());
514                 nodeByUUID.setProperty("instanceIdentifier", instanceIdentifierList.toString());
515 
516             }
517         }
518     }
519 
520     /**
521      * @param requestDocument
522      * @param session
523      * @throws RepositoryException
524      * @throws OleException
525      * @throws FileNotFoundException
526      * @throws OleDocStoreException
527      */
528     private void updateContentXmlOfInstance(RequestDocument requestDocument, Session session) throws RepositoryException, OleException, FileNotFoundException, OleDocStoreException {
529         Node nodeByUUID = session.getNodeByIdentifier(requestDocument.getUuid());
530         String content = checkOutContent(nodeByUUID, DocType.INSTANCE.getCode(), "chuntley");
531         nodeByUUID.setProperty("jcr:data", content);
532         List<RequestDocument> linkedRequestDocuments = requestDocument.getLinkedRequestDocuments();
533         for (RequestDocument linkedRequestDocument : linkedRequestDocuments) {
534             Node linkNodeByUUID = session.getNodeByIdentifier(linkedRequestDocument.getUuid());
535             LOG.info("link getIdentifier-->" + linkNodeByUUID.getIdentifier());
536             String linkContent = checkOutContent(linkNodeByUUID, DocType.BIB.getDescription(), "chuntley");
537             linkNodeByUUID.getNode("jcr:content").setProperty("jcr:data", linkContent);
538         }
539     }
540 
541     @Override
542     protected String checkOutContent(Node nodeByUUID, String format, String user)
543             throws RepositoryException, OleDocStoreException, FileNotFoundException {
544         String content = null;
545         if (nodeByUUID.getName().equalsIgnoreCase(ProcessParameters.NODE_INSTANCE)) {
546             content = nodeManager.getInstanceData(nodeByUUID);
547         } else {
548             content = nodeManager.getData(nodeByUUID);
549         }
550         return content;
551     }
552 
553 
554     /**
555      * Method to get Parsed Holdings & Item Documents.
556      *
557      * @param instanceDoc  - Instance document in format OleML
558      * @param linkedBibIds TODO
559      * @return
560      */
561     public List<RequestDocument> getParsedHoldingsNItemDocuments(RequestDocument instanceDoc,
562                                                                  List<String> linkedBibIds) throws OleDocStoreException {
563         List<RequestDocument> parsedItemNHoldingsDocuments = new ArrayList<RequestDocument>();
564         if (instanceDoc != null && DocCategory.WORK.isEqualTo(instanceDoc.getCategory()) && DocType.INSTANCE.isEqualTo(
565                 instanceDoc.getType()) && DocFormat.OLEML.isEqualTo(instanceDoc.getFormat())) {
566             String docContent = instanceDoc.getContent().getContent();
567             InstanceCollection instanceCollection = olemlProcessor.fromXML(docContent);
568             instanceDoc.getContent().setContentObject(instanceCollection);
569             // XML conversion
570             if (instanceCollection.getInstance() != null && instanceCollection.getInstance().size() > 0) {
571                 Instance instance = instanceCollection.getInstance().get(0);
572                 resolveLinkingWithBib(instance);
573 
574                 if (instance.getResourceIdentifier().size() == 1) {
575                     if (instance.getResourceIdentifier().get(0) == null || ""
576                             .equals(instance.getResourceIdentifier().get(0))) {
577                         instance.getResourceIdentifier().remove(0);
578                     }
579                 }
580                 if (linkedBibIds != null && linkedBibIds.size() > 0) {
581                     for (String likedBibId : linkedBibIds) {
582                         instance.getResourceIdentifier().add(likedBibId);
583                     }
584                 }
585                 parsedItemNHoldingsDocuments.add(generateInstanceDocument(instance));
586 
587                 OleHoldings oleHolding = instance.getOleHoldings();
588                 processCallNumber(oleHolding);
589                 RequestDocument rdHol = (RequestDocument) instanceDoc.clone();
590                 Content content = new Content();
591                 content.setContent(olemlProcessor.toXML(oleHolding));
592                 content.setContentObject(oleHolding);
593                 rdHol.setContent(content);
594                 if (oleHolding != null && oleHolding.getExtension() != null) {
595                     rdHol.setAdditionalAttributes(getFirstAdditionalAttributes(oleHolding.getExtension()));
596                 }
597                 parsedItemNHoldingsDocuments.add(rdHol);
598 
599                 SourceHoldings sourceHoldings = instance.getSourceHoldings();
600                 RequestDocument rdSrcHol = (RequestDocument) instanceDoc.clone();
601                 Content sourceHolContent = new Content();
602                 sourceHolContent.setContent(olemlProcessor.toXML(sourceHoldings));
603                 sourceHolContent.setContentObject(sourceHoldings);
604                 rdSrcHol.setContent(sourceHolContent);
605                 if (sourceHoldings != null && sourceHoldings.getExtension() != null) {
606                     rdSrcHol.setAdditionalAttributes(getFirstAdditionalAttributes(sourceHoldings.getExtension()));
607                 }
608                 parsedItemNHoldingsDocuments.add(rdSrcHol);
609 
610                 if (instance.getItems() == null) {
611                     instance.setItems(new Items());
612                 }
613                 if (instance.getItems().getItem() == null) {
614                     instance.getItems().getItem().add(new Item());
615                 }
616                 if (instance.getItems().getItem() != null && instance.getItems().getItem().size() == 0) {
617                     instance.getItems().getItem().add(new Item());
618                 }
619                 for (Item oleItem : instance.getItems().getItem()) {
620                     RequestDocument rdItm = (RequestDocument) instanceDoc.clone();
621                     if (oleItem.getCallNumber() != null) {
622                         computeCallNumberType(oleItem.getCallNumber());
623                     }
624                     updateShelvingOrder(oleItem, oleHolding);
625                     Content itemContent = new Content();
626                     itemContent.setContent(olemlProcessor.toXML(oleItem));
627                     itemContent.setContentObject(oleItem);
628                     rdItm.setContent(itemContent);
629                     if (oleItem != null && oleItem.getExtension() != null) {
630                         rdItm.setAdditionalAttributes(getFirstAdditionalAttributes(oleItem.getExtension()));
631                     }
632                     parsedItemNHoldingsDocuments.add(rdItm);
633                 }
634             }
635         }
636         return parsedItemNHoldingsDocuments;
637     }
638 
639     protected void processCallNumber(OleHoldings oleHolding) throws OleDocStoreException {
640         if (oleHolding != null && oleHolding.getCallNumber() != null) {
641             //validateCallNumber(oleHolding.getCallNumber());
642             CallNumber cNum = oleHolding.getCallNumber();
643             computeCallNumberType(cNum);
644             if (cNum.getNumber() != null && cNum.getNumber().trim().length() > 0) {
645                 //Build sortable key if a valid call number exists
646                 boolean isValid = validateCallNumber(cNum.getNumber(), cNum.getShelvingScheme().getCodeValue());
647                 String value = "";
648                 if (isValid) {
649                     value = buildSortableCallNumber(cNum.getNumber(), cNum.getShelvingScheme().getCodeValue());
650                 } else {
651                     value = cNum.getNumber();
652                 }
653                 if (cNum.getShelvingOrder() == null) {
654                     cNum.setShelvingOrder(new ShelvingOrder());
655                 }
656                 cNum.getShelvingOrder().setFullValue(value);
657             }
658         }
659     }
660 
661     public void validateCallNumber(CallNumber cNum) throws OleDocStoreException {
662         validateCNumNCNumType(cNum);
663         validateShelvingOrderNCNum(cNum);
664     }
665 
666     private void validateShelvingOrderNCNum(CallNumber cNum) throws OleDocStoreException {
667         if (cNum.getShelvingOrder() != null && cNum.getShelvingOrder().getFullValue() != null &&
668                 cNum.getShelvingOrder().getFullValue().trim().length() > 0) {
669             if (!(cNum.getNumber() != null && cNum.getNumber().length() > 0)) {
670                 throw new OleDocStoreException("Shelving order value is available, so please enter call number information");
671             }
672         }
673     }
674 
675 
676     /**
677      * Verifies that callNumberType is valid when callNumber is present.
678      * Else throws exception.
679      */
680     private void validateCNumNCNumType(CallNumber cNum) throws OleDocStoreException {
681         String callNumber = "";
682         String callNumberType = "";
683         // Get callNumber and callNumberType
684         if (cNum != null) {
685             callNumber = cNum.getNumber();
686             if (cNum.getShelvingScheme() != null) {
687                 callNumberType = cNum.getShelvingScheme().getCodeValue();
688             }
689         }
690         // Check if CallNumber is present
691         if (StringUtils.isNotEmpty(callNumber)) {
692             // Check if callNumberType is empty or #
693             if ((callNumberType == null) || (callNumberType.length() == 0) || (callNumberType.equals("#"))) {
694                 throw new OleDocStoreException("Please enter valid call number type value in call number information ");
695             }
696         }
697     }
698 
699     public void validateCallNumber(CallNumber itemCNum, OleHoldings holdings) throws OleDocStoreException {
700         // item call number and type verification
701         if ((itemCNum.getNumber() != null && itemCNum.getNumber().length() > 0)) {
702             validateCNumNCNumType(itemCNum);
703             validateShelvingOrderNCNum(itemCNum);
704         }
705         // if item call number is null consider holdings call number
706         else if (holdings != null) {
707             if (holdings.getCallNumber() != null) {
708                 CallNumber holCNum = holdings.getCallNumber();
709                 validateCNumNCNumType(holCNum);
710                 // consider item shelving order and holdings call number information.
711                 if (itemCNum.getShelvingOrder() != null && itemCNum.getShelvingOrder().getFullValue() != null &&
712                         itemCNum.getShelvingOrder().getFullValue().trim().length() > 0) {
713                     if (!(holCNum.getNumber() != null && holCNum.getNumber().length() > 0)) {
714                         throw new OleDocStoreException("Shelving order value is available, Please enter call number information");
715                     }
716                 }
717             }
718             // item shelving order is not null and holdings call number is null
719             else if (itemCNum.getShelvingOrder() != null && itemCNum.getShelvingOrder().getFullValue() != null &&
720                     itemCNum.getShelvingOrder().getFullValue().trim().length() > 0) {
721                 throw new OleDocStoreException("Shelving order value is available, Please enter call number information");
722             }
723 
724         }
725     }
726 
727     public void updateShelvingOrder(Item item, OleHoldings oleHolding) throws OleDocStoreException {
728         String callNumber = null;
729         String shelvingScheme = null;
730         if (item != null) {
731             if (item.getCallNumber() == null) {
732                 item.setCallNumber(new CallNumber());
733             }
734             // validating item if call number is available, shelving scheme should be available
735             // validateCallNumber(item.getCallNumber(), null);
736             //if call number is null or empty
737             if (!(item.getCallNumber().getNumber() != null && item.getCallNumber().getNumber().trim().length() > 0)) {
738                 // if holding call number and shelving scheme is not empty
739                 if (oleHolding != null && oleHolding.getCallNumber() != null && oleHolding.getCallNumber().getNumber() != null &&
740                         oleHolding.getCallNumber().getShelvingScheme() != null && oleHolding.getCallNumber().getShelvingScheme().getCodeValue() != null) {
741                     callNumber = oleHolding.getCallNumber().getNumber();
742                     shelvingScheme = oleHolding.getCallNumber().getShelvingScheme().getCodeValue();
743                 }
744             } else {
745                 // call number is not empty
746                 //TODO strip off item info from call number
747                 callNumber = item.getCallNumber().getNumber();
748                 //                item.getCallNumber().setNumber(appendItemInfoToCalNumber(item, callNumber));
749                 if (item.getCallNumber().getShelvingScheme() != null) {
750                     shelvingScheme = item.getCallNumber().getShelvingScheme().getCodeValue();
751                 }
752             }
753             String shelvingOrd = "";
754             if (callNumber != null && callNumber.trim().length() > 0 && shelvingScheme != null && shelvingScheme.trim().length() > 0) {
755                 callNumber = appendItemInfoToCalNumber(item, callNumber);
756                 //Build sortable key if a valid call number exists
757                 boolean isValid = validateCallNumber(callNumber, shelvingScheme);
758                 if (isValid) {
759                     shelvingOrd = buildSortableCallNumber(callNumber, shelvingScheme);
760                 } else {
761                     shelvingOrd = callNumber;
762                 }
763                 if (item.getCallNumber().getShelvingOrder() == null) {
764                     item.getCallNumber().setShelvingOrder(new ShelvingOrder());
765                 }
766                 item.getCallNumber().getShelvingOrder().setFullValue(shelvingOrd);
767             }
768         }
769     }
770 
771     private String appendItemInfoToCalNumber(Item item, String callNumber) {
772         if (item.getEnumeration() != null && item.getEnumeration().trim().length() > 0) {
773             callNumber = callNumber + " " + item.getEnumeration().trim();
774         }
775         if (item.getChronology() != null && item.getChronology().trim().length() > 0) {
776             callNumber = callNumber + " " + item.getChronology().trim();
777 
778         }
779         if (item.getCopyNumber() != null && item.getCopyNumber().trim().length() > 0) {
780             callNumber = callNumber + " " + item.getCopyNumber().trim();
781         }
782         return callNumber;
783     }
784 
785     protected boolean validateCallNumber(String callNumber, String codeValue) throws OleDocStoreException {
786         boolean isValid = false;
787         if (StringUtils.isNotEmpty(callNumber) && StringUtils.isNotEmpty(codeValue)) {
788             org.kuali.ole.utility.callnumber.CallNumber callNumberObj = CallNumberFactory.getInstance().getCallNumber(codeValue);
789             if (callNumberObj != null) {
790                 isValid = callNumberObj.isValid(callNumber);
791             }
792         }
793         return isValid;
794     }
795 
796     protected String buildSortableCallNumber(String callNumber, String codeValue) throws OleDocStoreException {
797         String shelvingOrder = "";
798         if (StringUtils.isNotEmpty(callNumber) && StringUtils.isNotEmpty(codeValue)) {
799             org.kuali.ole.utility.callnumber.CallNumber callNumberObj = CallNumberFactory.getInstance().getCallNumber(codeValue);
800             if (callNumberObj != null) {
801                 shelvingOrder = callNumberObj.getSortableKey(callNumber);
802                 //shelvingOrder = shelvingOrder.replaceAll(" ", "_");
803             }
804         }
805         return shelvingOrder;
806     }
807 
808     private RequestDocument generateInstanceDocument(Instance instance) {
809         InstanceCollection instanceCollection = new InstanceCollection();
810         List<Instance> instances = new ArrayList<Instance>();
811         instanceCollection.setInstance(instances);
812         Instance inst = new Instance();
813         instances.add(inst);
814         inst.setInstanceIdentifier(instance.getInstanceIdentifier());
815         inst.setResourceIdentifier(instance.getResourceIdentifier());
816         inst.setFormerResourceIdentifier(instance.getFormerResourceIdentifier());
817         inst.setExtension(instance.getExtension());
818         String cont = olemlProcessor.toXML(instanceCollection);
819         RequestDocument requestDocument = new RequestDocument();
820         requestDocument.setCategory(DocCategory.WORK.getCode());
821         requestDocument.setType(DocType.INSTANCE.getCode());
822         requestDocument.setFormat(DocFormat.OLEML.getCode());
823         requestDocument.setContent(new Content());
824         requestDocument.getContent().setContent(cont);
825         requestDocument.getContent().setContentObject(inst);
826         return requestDocument;
827     }
828 
829     private void resolveLinkingWithBib(Instance instance) {
830         if (ProcessParameters.BULK_INGEST_IS_LINKING_ENABLED) {
831             //            instance.getResourceIdentifier().clear();
832             for (FormerIdentifier frids : instance.getFormerResourceIdentifier()) {
833                 Identifier identifier = frids.getIdentifier();
834                 try {
835                     if (identifier.getIdentifierValue() != null
836                             && identifier.getIdentifierValue().trim().length() != 0) {
837                         List<SolrDocument> solrDocs = ServiceLocator.getIndexerService()
838                                 .getSolrDocument("SystemControlNumber",
839                                         "\"" + identifier
840                                                 .getIdentifierValue()
841                                                 + "\"");
842                         if (solrDocs != null && solrDocs.size() > 0) {
843                             for (SolrDocument solrDoc : solrDocs) {
844                                 if (checkApplicability(identifier.getIdentifierValue(),
845                                         solrDoc.getFieldValue("SystemControlNumber"))) {
846                                     instance.getResourceIdentifier().add(solrDoc.getFieldValue("id").toString());
847                                 }
848                             }
849                         }
850                     }
851                 } catch (Exception e) {
852 
853                 }
854             }
855         }
856     }
857 
858     private boolean checkApplicability(Object value, Object fieldValue) {
859         if (fieldValue instanceof Collection) {
860             for (Object object : (Collection) fieldValue) {
861                 if (object.equals(value)) {
862                     return true;
863                 }
864             }
865             return false;
866         } else {
867             return value.equals(fieldValue);
868         }
869     }
870 
871     /**
872      * Method to get Additional Attributes
873      *
874      * @param extension
875      * @return
876      */
877     private AdditionalAttributes getFirstAdditionalAttributes(Extension extension) {
878         if (extension != null && extension.getContent() != null) {
879             for (Object obj : extension.getContent()) {
880                 if (obj instanceof AdditionalAttributes) {
881                     return (AdditionalAttributes) obj;
882                 }
883             }
884         }
885         return null;
886     }
887 
888     private void setIdentifierValueInContent(RequestDocument reqDoc) {
889         if (reqDoc.getType().equalsIgnoreCase(DocType.ITEM.getDescription())) {
890             ItemOlemlRecordProcessor recordProcessor = new ItemOlemlRecordProcessor();
891             Item item = recordProcessor.fromXML(reqDoc.getContent().getContent());
892             item.setItemIdentifier(reqDoc.getId());
893             reqDoc.getContent().setContent(recordProcessor.toXML(item));
894         }
895         if (reqDoc.getType().equalsIgnoreCase(DocType.HOLDINGS.getDescription())) {
896             HoldingOlemlRecordProcessor recordProcessor = new HoldingOlemlRecordProcessor();
897             OleHoldings holdings = recordProcessor.fromXML(reqDoc.getContent().getContent());
898             holdings.setHoldingsIdentifier(reqDoc.getId());
899             reqDoc.getContent().setContent(recordProcessor.toXML(holdings));
900         }
901         if (reqDoc.getType().equalsIgnoreCase(DocType.SOURCEHOLDINGS.getDescription())) {
902             SourceHoldingOlemlRecordProcessor recordProcessor = new SourceHoldingOlemlRecordProcessor();
903             SourceHoldings sourceHoldings = recordProcessor.fromXML(reqDoc.getContent().getContent());
904             sourceHoldings.setHoldingsIdentifier(reqDoc.getId());
905             reqDoc.getContent().setContent(recordProcessor.toXML(sourceHoldings));
906         }
907     }
908 
909     public ResponseDocument buildResponseDocument(RequestDocument requestDocument) {
910         ResponseDocument responseDocument = new ResponseDocument();
911         responseDocument.setId(requestDocument.getId());
912         responseDocument.setCategory(requestDocument.getCategory());
913         responseDocument.setType(requestDocument.getType());
914         responseDocument.setFormat(requestDocument.getFormat());
915         responseDocument.setUuid(requestDocument.getUuid());
916         if ((requestDocument.getLinkedRequestDocuments() != null) && (requestDocument.getLinkedRequestDocuments().size()
917                 > 0) || requestDocument.getType()
918                 .equals(DocType.INSTANCE
919                         .getCode())) {
920             buildInstanceComponentResponseDocuments(requestDocument, responseDocument);
921         }
922         buildLinkedResponseDocuments(requestDocument, responseDocument);    // in the case of adding an item
923         return responseDocument;
924     }
925 
926     public ResponseDocument buildResponseDocument(RequestDocument requestDocument, Session session) {
927         ResponseDocument responseDocument = new ResponseDocument();
928         responseDocument.setId(requestDocument.getId());
929         responseDocument.setCategory(requestDocument.getCategory());
930         responseDocument.setType(requestDocument.getType());
931         responseDocument.setFormat(requestDocument.getFormat());
932         responseDocument.setUuid(requestDocument.getUuid());
933         String category = requestDocument.getCategory();
934         String type = requestDocument.getType();
935         Node node = null;
936         try {
937             node = session.getNodeByIdentifier(requestDocument.getUuid());
938         } catch (RepositoryException e) {
939             LOG.info("Failed to get node:" + e.getMessage(), e);
940         }
941 
942         if (node != null) {
943             try {
944                 AdditionalAttributes additionalAttributes = requestDocument.getAdditionalAttributes();
945                 if (additionalAttributes != null && category.equals(DocCategory.WORK.getDescription()) && type
946                         .equals(DocType.BIB.getDescription())) {
947                     Collection<String> attributeNames = additionalAttributes.getAttributeNames();
948                     if (attributeNames != null && attributeNames.size() > 0) {
949                         for (Iterator<String> iterator = attributeNames.iterator(); iterator.hasNext(); ) {
950                             String attributeName = iterator.next();
951                             if (node.hasProperty(attributeName)) {
952                                 additionalAttributes
953                                         .setAttribute(attributeName, node.getProperty(attributeName).getString());
954                             }
955                         }
956                     }
957                     responseDocument.setAdditionalAttributes(additionalAttributes);
958                 }
959             } catch (RepositoryException e) {
960                 LOG.info("Failed to get node property:" + e.getMessage(), e);
961             }
962         }
963 
964         buildLinkedResponseDocuments(requestDocument, responseDocument);
965         return responseDocument;
966     }
967 
968     private void buildInstanceComponentResponseDocuments(RequestDocument requestDocument,
969                                                          ResponseDocument responseDocument) {
970         if (requestDocument.getContent().getContent() == null) {    // in the case of adding an item
971             return;
972         }
973         InstanceCollection instanceCollection = (InstanceCollection) requestDocument.getContent().getContentObject();
974         ResponseDocument linkedInstanceDocument = null;
975         ResponseDocument linkedInstanceItemDocument = null;
976         ResponseDocument linkedInstanceSrHoldingDoc = null;
977         requestDocument.getContent().setContent("");
978         List<ResponseDocument> linkInstanceDocs = new ArrayList<ResponseDocument>();
979         for (Instance oleInstance : instanceCollection.getInstance()) {
980             // holding from instance
981             linkedInstanceDocument = new ResponseDocument();
982             setResponseParameters(linkedInstanceDocument, requestDocument);
983             linkedInstanceDocument.setUuid(oleInstance.getOleHoldings().getHoldingsIdentifier());
984             linkedInstanceDocument.setType("holdings");
985             linkInstanceDocs.add(linkedInstanceDocument);
986 
987             //SourceHolding from Instance
988             linkedInstanceSrHoldingDoc = new ResponseDocument();
989             setResponseParameters(linkedInstanceSrHoldingDoc, requestDocument);
990             if (oleInstance.getSourceHoldings() != null
991                     && oleInstance.getSourceHoldings().getHoldingsIdentifier() != null) {
992                 linkedInstanceSrHoldingDoc.setUuid(oleInstance.getSourceHoldings().getHoldingsIdentifier());
993                 linkedInstanceSrHoldingDoc.setType("sourceHoldings");
994                 linkInstanceDocs.add(linkedInstanceSrHoldingDoc);
995             }
996 
997             // item from instance
998             for (Iterator<Item> itemIterator = oleInstance.getItems().getItem().iterator(); itemIterator.hasNext(); ) {
999                 Item oleItem = itemIterator.next();
1000                 linkedInstanceItemDocument = new ResponseDocument();
1001                 setResponseParameters(linkedInstanceItemDocument, requestDocument);
1002                 linkedInstanceItemDocument.setUuid(oleItem.getItemIdentifier());
1003                 linkedInstanceItemDocument.setType("item");
1004                 linkInstanceDocs.add(linkedInstanceItemDocument);
1005             }
1006         }
1007         responseDocument.setLinkedDocuments(linkInstanceDocs);
1008     }
1009 
1010     /**
1011      * Used in the case of adding an item.
1012      *
1013      * @param requestDocument
1014      * @param responseDocument
1015      */
1016     protected void buildLinkedResponseDocuments(RequestDocument requestDocument, ResponseDocument responseDocument) {
1017         if ((null == requestDocument.getLinkedRequestDocuments()) || (requestDocument.getLinkedRequestDocuments().size()
1018                 == 0)) {
1019             buildInstanceComponentResponseDocuments(requestDocument, responseDocument);
1020             return;
1021         }
1022         for (RequestDocument linkedItemDocument : requestDocument.getLinkedRequestDocuments()) {
1023             if (DocType.ITEM.getDescription().equalsIgnoreCase(linkedItemDocument.getType())
1024                     && linkedItemDocument.getContent().getContent() != null) {
1025                 ResponseDocument linkedItemResponseDocument = new ResponseDocument();
1026                 setResponseParameters(linkedItemResponseDocument, requestDocument);
1027                 linkedItemResponseDocument.setUuid(linkedItemDocument.getUuid());
1028                 linkedItemResponseDocument.setType("item");
1029                 linkedItemResponseDocument.setContent(new Content(""));
1030                 responseDocument.getLinkedDocuments().add(linkedItemResponseDocument);
1031             }
1032         }
1033     }
1034 
1035     public void transferItems(List<RequestDocument> requestDocuments, Session session) throws Exception {
1036         LOG.debug("in JcrWorkInstanceDocumentManager transferItems");
1037         List<String> itemIdentifierList = new ArrayList<String>();
1038         String destInstanceIdentifier = requestDocuments.get(requestDocuments.size() - 1).getUuid();
1039         String destPath = "";
1040         for (int i = 0; i < requestDocuments.size() - 1; i++) {
1041             itemIdentifierList.add(requestDocuments.get(i).getUuid());
1042         }
1043         LOG.debug("JcrWorkInstanceDocumentManager transferItems itemIdentifierList " + itemIdentifierList);
1044         // Below line is commented to disable item exists check in ole as per jira 4130.
1045         //boolean isExists=checkInstancesOrItemsExistsInOLE(itemIdentifierList);
1046         boolean isExists = false;
1047         LOG.debug("isExists " + isExists);
1048         if (isExists) {
1049             LOG.debug("in isExists");
1050             throw new ItemExistsException("One of the Items to be Transfered is Loaned or In use in OLE");
1051         }
1052         LOG.debug("after isExists");
1053         Node instanceNode = session.getNodeByIdentifier(destInstanceIdentifier);
1054         NodeIterator instanceNodeIterator = instanceNode.getNodes();
1055 
1056         while (instanceNodeIterator.hasNext()) {
1057             Node node = instanceNodeIterator.nextNode();
1058             if (node.getName().equalsIgnoreCase("holdingsNode")) {
1059                 destPath = node.getPath() + "/itemFile";
1060                 break;
1061             }
1062         }
1063         for (String itemIdentifier : itemIdentifierList) {
1064             String sourcePath = session.getNodeByIdentifier(itemIdentifier).getPath();
1065             session.move(sourcePath, destPath);
1066         }
1067 
1068     }
1069 
1070     public void transferInstances(List<RequestDocument> requestDocuments, Session session) throws Exception {
1071         List<String> instanceIdentifiersList = new ArrayList<String>();
1072         for (int i = 0; i < requestDocuments.size() - 1; i++) {
1073             instanceIdentifiersList.add(requestDocuments.get(i).getUuid());
1074         }
1075         WorkInstanceNodeManager workInstanceNodeManager = WorkInstanceNodeManager.getInstance();
1076         InstanceCollection instanceCollection = null;
1077         String desBibIdentifier = requestDocuments.get(requestDocuments.size() - 1).getUuid();
1078         for (String instanceIdentifier : instanceIdentifiersList) {
1079             Node instanceNode = nodeManager.getNodeByUUID(session, instanceIdentifier);
1080             String instanceXMLContent = workInstanceNodeManager.getXMLOnlyForInstanceType(instanceNode);
1081             instanceCollection = olemlProcessor.fromXML(instanceXMLContent);
1082             List<Instance> instanceList = instanceCollection.getInstance();
1083             List<String> instanceIdentifiers = new ArrayList<String>();
1084             instanceIdentifiers.add(desBibIdentifier);
1085             instanceList.get(0).setResourceIdentifier(instanceIdentifiers);
1086             String backToXML = olemlProcessor.toXML(instanceCollection);
1087             byte[] bytes = convertContentToBytes(backToXML);
1088             NodeIterator nodeIterator = instanceNode.getNodes();
1089             Node node = null;
1090 
1091             while (nodeIterator.hasNext()) {
1092                 node = nodeIterator.nextNode();
1093                 if (node.getName().equalsIgnoreCase("instanceFile")) {
1094                     updateContentToNode(new RequestDocument(), session, bytes, node);
1095                 }
1096             }
1097         }
1098     }
1099 
1100     private byte[] convertContentToBytes(String xmlContent) throws OleDocStoreException {
1101         String charset = "UTF-8";
1102         byte[] documentBytes = null;
1103         try {
1104             if (xmlContent != null) {
1105                 documentBytes = xmlContent.getBytes(charset);
1106             }
1107         } catch (Exception e) {
1108             //  logger.info("Failed to convert input string to byte[] with charset " + charset, e);
1109             throw new OleDocStoreException(e.getMessage());
1110         }
1111         return documentBytes;
1112     }
1113 
1114     @Override
1115     public void validateInput(RequestDocument requestDocument, Object object, List<String> fieldValues) throws OleDocStoreException {
1116         Session session = (Session) object;
1117         String content = requestDocument.getContent().getContent();
1118         if (content == null) {
1119             if (requestDocument.getLinkedRequestDocuments().size() > 0) {
1120                 List<RequestDocument> linkedRequestDocuments = requestDocument.getLinkedRequestDocuments();
1121                 for (RequestDocument linkedRequestDocument : linkedRequestDocuments) {
1122                     if (linkedRequestDocument.getType().equalsIgnoreCase(DocType.ITEM.getCode())) {
1123                         JcrWorkItemDocumentManager.getInstance().validateNewItem(linkedRequestDocument, session, fieldValues, requestDocument.getId());
1124                     }
1125                 }
1126             }
1127         } else {
1128             InstanceOlemlRecordProcessor instProcessor = new InstanceOlemlRecordProcessor();
1129             InstanceCollection instanceCollection = instProcessor.fromXML(content);
1130             List<Instance> instanceList = instanceCollection.getInstance();
1131             for (Instance instance : instanceList) {
1132                 if (instance.getOleHoldings() != null) {
1133                     OleHoldings oleHoldings = instance.getOleHoldings();
1134                     JcrJcrWorkHoldingsDocumentManager.getInstance().validateHoldings(oleHoldings);
1135                 }
1136                 if (instance.getItems() != null) {
1137                     Items items = instance.getItems();
1138                     List<Item> itemList = items.getItem();
1139                     if (itemList.size() > 0) {
1140                         for (Item item : itemList) {
1141                             JcrWorkItemDocumentManager.getInstance().itemBarcodeValidation(item, fieldValues, null);
1142                             if (item.getCallNumber() != null) {
1143                                 CallNumber callNumber = item.getCallNumber();
1144                                 if (instance.getOleHoldings() != null) {
1145                                     OleHoldings oleHoldings = instance.getOleHoldings();
1146                                     validateCallNumber(callNumber, oleHoldings);
1147                                 } else {
1148                                     validateCallNumber(callNumber, null);
1149                                 }
1150                             }
1151                         }
1152                     }
1153                 }
1154             }
1155         }
1156     }
1157 
1158     /**
1159      * Compute 'call number type name' if a valid 'call number type code' is available
1160      *
1161      * @param callNumber
1162      */
1163     public void computeCallNumberType(CallNumber callNumber) {
1164         Set<String> validCallNumberTypeSet = CallNumberType.validCallNumberTypeCodeSet;
1165         if (callNumber != null) {
1166             if (callNumber.getShelvingScheme() != null) {
1167                 String callNumberTypeCode = callNumber.getShelvingScheme().getCodeValue();
1168                 String callNumberTypeName = "";
1169                 //If call number type code is valid
1170                 if ((StringUtils.isNotEmpty(callNumberTypeCode)) && (validCallNumberTypeSet
1171                         .contains(callNumberTypeCode))) {
1172                     callNumberTypeName = CallNumberType.valueOf(callNumberTypeCode).getDescription();
1173                     callNumber.getShelvingScheme().setFullValue(callNumberTypeName);
1174                 }
1175             }
1176         }
1177     }
1178 }