View Javadoc

1   package org.kuali.ole.docstore.document;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.kuali.ole.docstore.OleDocStoreException;
5   import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
6   import org.kuali.ole.docstore.model.enums.DocCategory;
7   import org.kuali.ole.docstore.model.enums.DocFormat;
8   import org.kuali.ole.docstore.model.enums.DocType;
9   import org.kuali.ole.docstore.model.xmlpojo.ingest.Content;
10  import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument;
11  import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument;
12  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.CallNumber;
13  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.Item;
14  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.OleHoldings;
15  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.ShelvingScheme;
16  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkHoldingOlemlRecordProcessor;
17  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
18  import org.kuali.ole.docstore.process.ProcessParameters;
19  import org.kuali.ole.docstore.service.BeanLocator;
20  import org.slf4j.Logger;
21  import org.slf4j.LoggerFactory;
22  
23  import javax.jcr.Node;
24  import javax.jcr.RepositoryException;
25  import javax.jcr.Session;
26  import java.io.FileNotFoundException;
27  import java.util.ArrayList;
28  import java.util.Iterator;
29  import java.util.List;
30  
31  import static org.kuali.ole.docstore.process.ProcessParameters.FILE_HOLDINGS;
32  
33  /**
34   * Created with IntelliJ IDEA.
35   * User: SG7940
36   * Date: 1/23/13
37   * Time: 5:09 PM
38   * To change this template use File | Settings | File Templates.
39   */
40  public class WorkItemDocumentManager extends  WorkInstanceDocumentManager {
41  
42      private static WorkItemDocumentManager      ourInstance    = null;
43      private static Logger LOG         = LoggerFactory.getLogger(WorkItemDocumentManager.class);
44  
45      public static WorkItemDocumentManager getInstance() {
46          if (null == ourInstance) {
47              ourInstance = new WorkItemDocumentManager();
48          }
49          return ourInstance;
50      }
51  
52  
53      @Override
54      public List<ResponseDocument> deleteVerify(List<RequestDocument> requestDocument, Session session) {
55          return null;
56      }
57  
58      @Override
59      public ResponseDocument deleteVerify(RequestDocument requestDocument, Session session) throws Exception {
60          LOG.debug("workItemDocumentManager deleteVerify method");
61          List<String> instanceIdentifierList = new ArrayList<String>();
62          ResponseDocument responseDocument = new ResponseDocument();
63          List<String> itemIdentifierList=new ArrayList<String>();
64          itemIdentifierList.add(requestDocument.getUuid());
65          boolean exists=checkInstancesOrItemsExistsInOLE(itemIdentifierList);
66          if(exists){
67              responseDocument.setId(requestDocument.getId());
68              responseDocument.setCategory(requestDocument.getCategory());
69              responseDocument.setType(requestDocument.getType());
70              responseDocument.setFormat(requestDocument.getFormat());
71              responseDocument.setUuid(requestDocument.getUuid());
72              responseDocument.setStatus("failure'");
73              responseDocument.setStatusMessage("Instances or Items in use. So deletion cannot be done");
74              return responseDocument;
75          }
76         Node itemNode = session.getNodeByIdentifier(requestDocument.getUuid());
77  
78          long itemSize=itemNode.getParent().getNodes().getSize()-2;
79          LOG.debug("WorkItemDocumentManager : itemSize "+itemSize);
80          String instanceIdentifier=itemNode.getParent().getParent().getIdentifier();
81          LOG.debug("WorkItemDocumentManager : instanceIdentifier "+instanceIdentifier);
82           if(itemSize==1){
83              requestDocument.setUuid(instanceIdentifier);
84              requestDocument.setCategory(DocCategory.WORK.getCode());
85              requestDocument.setType(DocType.INSTANCE.getCode());
86              requestDocument.setFormat(DocFormat.OLEML.getCode());
87              responseDocument = WorkInstanceDocumentManager.getInstance().deleteVerify(requestDocument, session);
88          }
89          else{
90                  responseDocument.setUuid(requestDocument.getUuid());
91                  responseDocument.setId(requestDocument.getId());
92                  responseDocument.setCategory(requestDocument.getCategory());
93                  responseDocument.setType(requestDocument.getType());
94                  responseDocument.setFormat(requestDocument.getFormat());
95                  responseDocument.setStatus("success");
96                  responseDocument.setStatusMessage("success");
97          }
98          return responseDocument;
99      }
100           @Override
101     public ResponseDocument delete(RequestDocument requestDocument, Session session) throws Exception {
102               LOG.debug("in WorkItemDocumentManager :delete");
103               DocumentManager documentManager = null;
104            ResponseDocument responseDocument=new ResponseDocument();
105            ResponseDocument responseDocumentFromDeleteVerify=deleteVerify(requestDocument,session);
106               LOG.debug("in WorkItemDocumentManager :delete after verify getUuid "+responseDocumentFromDeleteVerify.getUuid());
107            String status=responseDocumentFromDeleteVerify.getStatus();
108               LOG.debug("in WorkItemDocumentManager :delete status "+status);
109 
110                if(status.equalsIgnoreCase("success")){
111                 if(responseDocumentFromDeleteVerify.getCategory().equalsIgnoreCase("work") && responseDocumentFromDeleteVerify.getFormat().equalsIgnoreCase("oleml") && responseDocumentFromDeleteVerify.getType().equalsIgnoreCase("instance")){
112                     LOG.debug("in WorkItemDocumentManager :delete if of instance");
113                RequestDocument requestDocumentForInstance =     prepareRequestDocument(responseDocumentFromDeleteVerify);
114                    documentManager = BeanLocator.getDocumentManagerFactory().getDocumentManager(requestDocumentForInstance);
115                   responseDocument=  documentManager.delete(requestDocumentForInstance,session);
116                 }
117                else if(responseDocumentFromDeleteVerify.getCategory().equalsIgnoreCase("work") && responseDocumentFromDeleteVerify.getFormat().equalsIgnoreCase("marc") && responseDocumentFromDeleteVerify.getType().equalsIgnoreCase("bibliographic")){
118                     LOG.debug("in WorkItemDocumentManager :delete if of marc");
119                     RequestDocument requestDocumentForBib =     prepareRequestDocument(responseDocumentFromDeleteVerify);
120                    documentManager = BeanLocator.getDocumentManagerFactory().getDocumentManager(requestDocumentForBib);
121                   responseDocument=  documentManager.delete(requestDocumentForBib,session);
122                 }
123                 else if(responseDocumentFromDeleteVerify.getCategory().equalsIgnoreCase("work") && responseDocumentFromDeleteVerify.getFormat().equalsIgnoreCase("oleml") && responseDocumentFromDeleteVerify.getType().equalsIgnoreCase("item")){
124                     LOG.debug("in WorkItemDocumentManager :delete if of item");
125                       List<String> itemIdentifierList=new ArrayList<String>();
126                     itemIdentifierList.add(requestDocument.getUuid());
127                     deleteFromRepository(itemIdentifierList,session);
128 
129                 }
130                }
131               return responseDocument;
132           }
133 
134     @Override
135     protected void modifyContent(RequestDocument reqDoc, Session session, Node nodeByUUID)
136                     throws RepositoryException, FileNotFoundException, OleDocStoreException {
137         if (reqDoc.getOperation().equalsIgnoreCase("checkIn")) {
138             WorkItemOlemlRecordProcessor itemProcessor = new WorkItemOlemlRecordProcessor();
139 
140             if (reqDoc.getContent() != null && reqDoc.getContent().getContent() != null) {
141                 // get new item content to check in
142                 Item newItem = itemProcessor.fromXML(reqDoc.getContent().getContent());
143                 // verify new item call number and shelving scheme to build sortable call num
144                 Boolean status = true;
145                 if (newItem.getCallNumber() == null) {
146                     newItem.setCallNumber(new CallNumber());
147                 }
148                 CallNumber cNum = newItem.getCallNumber();
149                 if (!(cNum.getShelvingOrder() != null && cNum.getShelvingOrder().getFullValue() != null &&
150                         cNum.getShelvingOrder().getFullValue().trim().length() > 0)) {
151                     if (!(cNum.getNumber() != null && cNum.getNumber().trim().length() > 0)) {
152                         OleHoldings hold = getHoldings(nodeByUUID);
153                         updateShelvingOrder(newItem, hold);
154                         status = false;
155                     } else {
156                         updateShelvingOrder(newItem, null);
157                         status = false;
158                     }
159                 }
160                 if (status) {
161                     //get already existing item content from jcr.
162                     String existingItemXml = nodeManager.getData(nodeByUUID);
163                     // if new item contains shelving scheme and call number
164                     if (existingItemXml != null) {
165                         Item existItem = itemProcessor.fromXML(existingItemXml);
166                         if (existItem.getCallNumber() == null) {
167                             existItem.setCallNumber(new CallNumber());
168                         }
169                         CallNumber existCNum = existItem.getCallNumber();
170                         setItemValuesFromNullToEmpty(existItem);
171                         setItemValuesFromNullToEmpty(newItem);
172                         cNum = newItem.getCallNumber();
173                         computeCallNumberType(cNum);
174                         if (!(existCNum.getNumber().equalsIgnoreCase((cNum.getNumber()))) |
175                                 !(existCNum.getShelvingScheme().getCodeValue().equalsIgnoreCase(cNum.getShelvingScheme().getCodeValue())) |
176                                 !((existItem.getEnumeration()).equalsIgnoreCase(newItem.getEnumeration())) |
177                                 !((existItem.getChronology()).equalsIgnoreCase(newItem.getChronology())) |
178                                 !((existItem.getCopyNumber()).equalsIgnoreCase(newItem.getCopyNumber()))) {
179                             if (!(cNum.getNumber() != null && cNum.getNumber().trim().length() > 0)) {
180                                 OleHoldings hold = getHoldings(nodeByUUID);
181                                 updateShelvingOrder(newItem, hold);
182                             } else {
183                                 updateShelvingOrder(newItem, null);
184                             }
185 
186                         }
187                     }
188                 }
189                 reqDoc.getContent().setContent(itemProcessor.toXML(newItem));
190             }
191         }
192     }
193 
194     private OleHoldings getHoldings(Node nodeByUUID) throws RepositoryException, FileNotFoundException, OleDocStoreException {
195         // if new item call num and shelving scheme are empty get them from holdings.
196         Node holdingsNode = nodeByUUID.getParent();
197         Node holdingsFileNode = holdingsNode.getNode(FILE_HOLDINGS);
198         String holdXml = nodeManager.getData(holdingsFileNode);
199         WorkHoldingOlemlRecordProcessor holdProc = new WorkHoldingOlemlRecordProcessor();
200         OleHoldings hold = holdProc.fromXML(holdXml);
201         return hold;
202     }
203 
204     protected void updateItemCallNumberFromHoldings(Node nodeByUUID, OleHoldings newHold, RequestDocument reqDoc)
205             throws RepositoryException, FileNotFoundException, OleDocStoreException {
206         Node holdingsNode = nodeByUUID.getParent();
207 //        Node itemNode = holdingsNode.getNodes(ProcessParameters.FILE_ITEM);
208         for (Iterator<Node> itemIterator = holdingsNode.getNodes(ProcessParameters.FILE_ITEM); itemIterator.hasNext(); ) {
209             Node itemNode = itemIterator.next();
210             String itemXml = nodeManager.getData(itemNode);
211             String uuid = itemNode.getProperty("jcr:uuid").getString();
212             WorkItemOlemlRecordProcessor itemProcessor = new WorkItemOlemlRecordProcessor();
213             Item item = itemProcessor.fromXML(itemXml);
214             if (item != null ) {
215                 if(item.getCallNumber() == null){
216                    item.setCallNumber(new CallNumber());
217                 }
218                 item.getCallNumber().setNumber("");
219                 if (item.getCallNumber().getShelvingScheme() != null)
220                     item.getCallNumber().getShelvingScheme().setCodeValue("");
221                 updateShelvingOrder(item, newHold);
222                 String newItemXml = itemProcessor.toXML(item);
223                 buildRequestDocumentForItem(newItemXml, reqDoc, uuid);
224             }
225         }
226     }
227 
228     protected void updateContentToNode(RequestDocument reqDoc, Session session, byte[] documentBytes, Node nodeByUUID)
229             throws RepositoryException, OleDocStoreException {
230         documentBytes = convertContentToBytes(reqDoc);
231         super.updateContentToNode(reqDoc, session, documentBytes, nodeByUUID);
232     }
233 
234     private void buildRequestDocumentForItem(String newItemXml, RequestDocument reqDoc, String uuid) {
235         RequestDocument requestDocument = new RequestDocument();
236         requestDocument.setOperation("checkIn");
237         requestDocument.setCategory(DocCategory.WORK.getCode());
238         requestDocument.setType(DocType.ITEM.getCode());
239         requestDocument.setFormat(DocFormat.OLEML.getCode());
240         requestDocument.setUuid(uuid);
241         requestDocument.setId(uuid);
242         Content content = new Content();
243         content.setContent(newItemXml);
244         requestDocument.setContent(content);
245         List<RequestDocument> reqDocList = reqDoc.getLinkedRequestDocuments();
246         if (reqDocList == null) {
247             reqDoc.setLinkedRequestDocuments(new ArrayList<RequestDocument>());
248         }
249         reqDocList.add(requestDocument);
250     }
251 
252     private void setItemValuesFromNullToEmpty(Item item) {
253         CallNumber existCNum = item.getCallNumber();
254         if(existCNum == null ){
255             item.setCallNumber(new CallNumber());
256         }
257         if(existCNum.getNumber() == null){
258            existCNum.setNumber("");
259         }
260         ShelvingScheme existSS = existCNum.getShelvingScheme();
261         if (existSS == null) {
262             existCNum.setShelvingScheme(new ShelvingScheme());
263             existSS = existCNum.getShelvingScheme();
264         }
265         if (existSS != null && !(existSS.getCodeValue() != null && existSS.getCodeValue().trim().length() > 0)) {
266             existSS.setCodeValue("");
267         }
268         if (item.getEnumeration() == null) {
269             item.setEnumeration("");
270         }
271         if (item.getChronology() == null) {
272             item.setChronology("");
273         }
274         if (item.getCopyNumber() == null) {
275             item.setCopyNumber("");
276         }
277     }
278 
279     @Override
280     public void validateInput(RequestDocument requestDocument, Session session, List<String> valuesList) throws OleDocStoreException {
281         validateItem(requestDocument, session, valuesList);
282      }
283 
284 
285     public void validateNewItem(RequestDocument linkedRequestDocument, Session session, List<String> fieldValues, String instanceUuid)throws OleDocStoreException{
286         try{
287             String itemContent = linkedRequestDocument.getContent().getContent();
288             WorkItemOlemlRecordProcessor workItemOlemlRecordProcessor = new WorkItemOlemlRecordProcessor();
289             Item item = workItemOlemlRecordProcessor.fromXML(itemContent);
290             itemBarcodeValidation(item, fieldValues, null);
291             if (item.getCallNumber() != null) {
292                Node instanceNode =  nodeManager.getNodeByUUID(session,instanceUuid);
293                 if (instanceNode != null && instanceNode.hasNode(ProcessParameters.NODE_HOLDINGS)) {
294                     Node holdingsParentNode = instanceNode.getNode(ProcessParameters.NODE_HOLDINGS);
295                     if (holdingsParentNode.hasNode(ProcessParameters.FILE_HOLDINGS)) {
296                         Node holdingsNode = holdingsParentNode.getNode(ProcessParameters.FILE_HOLDINGS);
297                         if (holdingsNode != null) {
298                             getHoldingsContentNValidateItem(holdingsNode, item);
299                         }
300                     }
301                 }
302             }
303         }
304         catch (Exception e){
305             throw new OleDocStoreException(e.getMessage(),e);
306         }
307     }
308 
309 
310     public void validateItem(RequestDocument linkedRequestDocument, Session session, List<String> fieldValues) throws OleDocStoreException {
311         try{
312             String itemContent = linkedRequestDocument.getContent().getContent();
313             WorkItemOlemlRecordProcessor workItemOlemlRecordProcessor = new WorkItemOlemlRecordProcessor();
314             Item item = workItemOlemlRecordProcessor.fromXML(itemContent);
315             //TODO:Ignored this validation as it affecting check in operation for an existing barcode
316             itemBarcodeValidation(item, fieldValues, linkedRequestDocument.getId());
317             if (item.getCallNumber() != null) {
318                 Node node = nodeManager.getNodeByUUID(session, linkedRequestDocument.getUuid());
319                 Node parentNode = null;
320                 parentNode = node.getParent();
321                 if (parentNode != null) {
322                     if (parentNode.hasNode(ProcessParameters.FILE_HOLDINGS)) {
323                         Node holdingsNode = parentNode.getNode(ProcessParameters.FILE_HOLDINGS);
324                         getHoldingsContentNValidateItem(holdingsNode, item);
325                     }
326                 }
327             }
328         }
329         catch (Exception e){
330             throw new OleDocStoreException(e.getMessage(),e);
331         }
332     }
333 
334     public void itemBarcodeValidation(Item item, List<String> fieldValues, String id) throws OleDocStoreException {
335         if (item.getAccessInformation() != null && StringUtils.isNotEmpty(item.getAccessInformation().getBarcode())) {
336             try {
337                if (fieldValues.contains(item.getAccessInformation().getBarcode()) ||
338                         QueryServiceImpl.getInstance().isFieldValueExists(DocType.ITEM.getCode(), "ItemBarcode_display", item.getAccessInformation().getBarcode(), id)) {
339                     throw new OleDocStoreException("Barcode " + item.getAccessInformation().getBarcode() + " already exists ");
340                 }
341                 fieldValues.add(item.getAccessInformation().getBarcode());
342             } catch (Exception e) {
343                 throw new OleDocStoreException(e.getMessage(), e);
344             }
345         }
346 
347     }
348 
349     private void getHoldingsContentNValidateItem(Node holdingsNode, Item item) throws Exception{
350         String content = checkOutContent(holdingsNode, DocFormat.OLEML.getCode(), "ole-khuntley");
351         WorkHoldingOlemlRecordProcessor workHoldingOlemlRecordProcessor = new WorkHoldingOlemlRecordProcessor();
352         OleHoldings oleHoldings = workHoldingOlemlRecordProcessor.fromXML(content);
353         CallNumber callNumber = item.getCallNumber();
354         validateCallNumber(callNumber, oleHoldings);
355     }
356 
357 
358 }