View Javadoc

1   /*
2    * Copyright 2011 The Kuali Foundation.
3    * 
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    * http://www.opensource.org/licenses/ecl2.php
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.repository;
17  
18  import org.apache.commons.io.FileUtils;
19  import org.kuali.ole.RepositoryManager;
20  import org.kuali.ole.docstore.DocStoreConstants;
21  import org.kuali.ole.docstore.model.enums.DocType;
22  import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument;
23  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.OleHolding;
24  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.OleItem;
25  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkHoldingOlemlRecordProcessor;
26  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
27  import org.kuali.ole.docstore.service.DocumentIndexer;
28  import org.kuali.ole.docstore.service.ServiceLocator;
29  import org.kuali.ole.logger.DocStoreLogger;
30  import org.kuali.ole.pojo.OleException;
31  import org.slf4j.Logger;
32  import org.slf4j.LoggerFactory;
33  
34  import javax.jcr.Binary;
35  import javax.jcr.Node;
36  import javax.jcr.RepositoryException;
37  import javax.jcr.Session;
38  import javax.jcr.version.VersionHistory;
39  import javax.jcr.version.VersionIterator;
40  import javax.jcr.version.VersionManager;
41  import java.io.ByteArrayInputStream;
42  import java.io.File;
43  import java.util.ArrayList;
44  import java.util.Calendar;
45  import java.util.Iterator;
46  import java.util.List;
47  
48  import static org.kuali.ole.docstore.process.ProcessParameters.FILE_ITEM;
49  
50  public class CheckinManager {
51      private static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
52      DocStoreLogger docStoreLogger = new DocStoreLogger(this.getClass().getName());
53      private static final Logger LOG  = LoggerFactory.getLogger(CheckinManager.class);
54  
55      public String updateContent(RequestDocument requestDocument) throws OleException {
56          List<String> ingestDocs = new ArrayList<String>();
57          List<String> uuids = new ArrayList<String>();
58          StringBuilder sb = new StringBuilder();
59          String uuid = null;
60          String content = null;
61          String latestVersion = null;
62          String checkInFail = "Check in failed. ";
63          content = requestDocument.getContent().getContent();
64          if (requestDocument.getUuid() == null || requestDocument.getUuid().trim().length() == 0) {
65              requestDocument.setUuid(requestDocument.getId());
66          }
67          uuid = requestDocument.getUuid();
68          ingestDocs.add(sb.toString());
69          uuids.add(uuid);
70          if (DocType.INSTANCE.getCode().equalsIgnoreCase(requestDocument.getType()) && content == null
71              && requestDocument.getId() != null) {
72              for (RequestDocument linkedItemDocument : requestDocument.getLinkedRequestDocuments()) {
73                  if (DocType.ITEM.getCode().equalsIgnoreCase(linkedItemDocument.getType())
74                      && linkedItemDocument.getContent().getContent() != null) {
75                      ingestNIndexItemRecForInstance(requestDocument);
76                  }
77              }
78          }
79          String result = ServiceLocator.getIndexerService().indexDocument(requestDocument);
80          if (!result.startsWith("success")) {
81              throw new OleException(checkInFail + result);
82          }
83          Session session = null;
84          try {
85              latestVersion = updateRecordInDocStore(requestDocument);
86          }
87          catch (Exception e) {
88              docStoreLogger.log("Document was updated in indexer but not in docStore, trying to rollback the changes from indexer", e);
89  
90              RequestDocument prevRequestDoc = null;
91              session = RepositoryManager.getRepositoryManager().getSession("CheckinManager", "checkIn");
92              Node nodeByUUID = getNodeByUUID(session, requestDocument.getId());
93              try {
94                  DocumentIndexer documentIndexer = new DocumentIndexer();
95                  prevRequestDoc = new RequestDocument();
96                  prevRequestDoc = requestDocument;
97                  String prevContent = nodeByUUID.getNode("jcr:content").getProperty("jcr:data").getValue().getString();
98                  prevRequestDoc.getContent().setContent(prevContent);
99                  documentIndexer.indexDocument(prevRequestDoc);
100             }
101             catch (Exception ex) {
102                 String failMsg = checkInFail + "Unable to Roll back the changes in indexer.  Record UUID "
103                                  + requestDocument.getId() + "got updated in indexer, but not in docstore ";
104                 docStoreLogger.log(failMsg, ex);
105                 throw new OleException(failMsg, ex);
106 
107             }
108             docStoreLogger.log(checkInFail, e);
109             throw new OleException(checkInFail, e);
110         }
111         finally {
112             RepositoryManager.getRepositoryManager().logout(session);
113         }
114 
115 
116         return latestVersion;
117     }
118 
119     private void ingestNIndexItemRecForInstance(RequestDocument reqDoc) throws OleException {
120         Session session =null;
121         try {
122             session = RepositoryManager.getRepositoryManager().getSession("CheckinManager","ingestNIndexItemRecForInstance");
123             Node nodeByUUID = getNodeByUUID(session, reqDoc.getId());
124             Node holdingsNode = nodeByUUID.getNode("holdings");
125             NodeHandler nodeHandler = new NodeHandler();
126 
127             for(RequestDocument linkedItemDocument : reqDoc.getLinkedRequestDocuments()){
128              WorkItemOlemlRecordProcessor recordProcessor = new WorkItemOlemlRecordProcessor();
129              OleItem item = recordProcessor.fromXML(linkedItemDocument.getContent().getContent());
130              linkedItemDocument.getContent().setContentObject(item);
131             String uuid = (nodeHandler.initFileNode(linkedItemDocument, FILE_ITEM, holdingsNode,
132                                                     session)).getIdentifier();
133             linkedItemDocument.setId(uuid);
134             }
135             session.save();
136         }
137         catch (Exception e) {
138            docStoreLogger.log(e.getMessage());
139            throw new OleException(e.getMessage(), e);
140         }
141         finally {
142             RepositoryManager.getRepositoryManager().logout(session);
143         }
144     }
145 
146 
147     private String updateRecordInDocStore(RequestDocument reqDoc) throws OleException, RepositoryException {
148         Session session = RepositoryManager.getRepositoryManager().getSession("CheckinManager", "updateRecordInDocStore");
149         String charset = "UTF-8";
150         byte[] documentBytes = null;
151         String currentVersion = null;
152 
153         try {
154             if (reqDoc.getDocumentName() != null && reqDoc.getDocumentName().trim().length() != 0) {
155                 documentBytes = FileUtils.readFileToByteArray(new File(reqDoc.getDocumentName()));
156             } else if (reqDoc.getContent().getContent() != null) {
157                 setIdentifierValueInContent(reqDoc);
158                 documentBytes = reqDoc.getContent().getContent().getBytes(charset);
159             }
160         } catch (Exception e) {
161             getDocStoreLogger().log("Failed to convert input string to byte[] with charset " + charset, e);
162             throw new OleException(e.getMessage());
163         }
164         RequestDocument linkReqInfo = new RequestDocument();
165         if (reqDoc.getLinkedRequestDocuments() != null && reqDoc.getLinkedRequestDocuments().size() > 0) {
166             for (Iterator<RequestDocument> linkIterator = reqDoc.getLinkedRequestDocuments().iterator(); linkIterator.hasNext();) {
167                 linkReqInfo = linkIterator.next();
168             }
169         }
170         Node nodeByUUID = session.getNodeByIdentifier(reqDoc.getUuid());
171         try {
172             Binary binary = null;
173             if (documentBytes != null) {
174                 binary = session.getValueFactory().createBinary(new ByteArrayInputStream(documentBytes));
175                 nodeByUUID.getNode("jcr:content").setProperty("jcr:data", binary);
176             }
177             if (linkReqInfo != null && linkReqInfo.getId() != null && linkReqInfo.getType().equalsIgnoreCase(DocType.INSTANCE.getCode())) {
178                 nodeByUUID.setProperty("instanceIdentifier", linkReqInfo.getId());
179             }
180             Calendar lastModified = Calendar.getInstance();
181             lastModified.setTimeInMillis(lastModified.getTimeInMillis());
182             if (!reqDoc.getType().equalsIgnoreCase(DocType.INSTANCE.getCode())) {
183                 nodeByUUID.getNode("jcr:content").setProperty("jcr:lastModified", lastModified);
184             }
185             session.save();
186             if (DocStoreConstants.isVersioningEnabled || DocType.LICENSE.isEqualTo(reqDoc.getType())) {
187                 VersionManager versionManager = getVersionManager(session);
188                 versionManager.checkpoint(nodeByUUID.getPath());
189                 VersionHistory versionHistory = versionManager.getVersionHistory(nodeByUUID.getPath());
190                 VersionIterator allVersions = versionHistory.getAllVersions();
191                 while (allVersions.hasNext()) {
192                     currentVersion = allVersions.nextVersion().getName();
193                 }
194                 getDocStoreLogger().log("Version updated for UUID:" + reqDoc.getUuid() + "  ====  version:" + currentVersion);
195             }
196         } catch (Exception e) {
197             docStoreLogger.log(e.getMessage());
198             throw new OleException(e.getMessage(), e);
199         } finally {
200             RepositoryManager.getRepositoryManager().logout(session);
201         }
202         return currentVersion;
203     }
204 
205     private void setIdentifierValueInContent(RequestDocument reqDoc) {
206         if (reqDoc.getType().equalsIgnoreCase(DocType.ITEM.getCode())) {
207             WorkItemOlemlRecordProcessor recordProcessor = new WorkItemOlemlRecordProcessor();
208             OleItem item = recordProcessor.fromXML(reqDoc.getContent().getContent());
209             item.setItemIdentifier(reqDoc.getId());
210             reqDoc.getContent().setContent(recordProcessor.toXML(item));
211         }
212         if (reqDoc.getType().equalsIgnoreCase(DocType.HOLDINGS.getDescription())) {
213             WorkHoldingOlemlRecordProcessor recordProcessor = new WorkHoldingOlemlRecordProcessor();
214             OleHolding holdings = recordProcessor.fromXML(reqDoc.getContent().getContent());
215             holdings.setHoldingsIdentifier(reqDoc.getId());
216             reqDoc.getContent().setContent(recordProcessor.toXML(holdings));
217         }
218     }
219 
220     private Node getNodeByUUID(Session newSession, String uuid)
221             throws OleException {
222         return new NodeHandler().getNodeByUUID(newSession, uuid);
223     }
224 
225     public DocStoreLogger getDocStoreLogger() {
226         return docStoreLogger;
227     }
228 
229     public VersionManager getVersionManager(Session session)
230             throws OleException, RepositoryException {
231         return session.getWorkspace().getVersionManager();
232     }
233 }