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.apache.commons.io.IOUtils;
20  import org.kuali.ole.RepositoryManager;
21  import org.kuali.ole.docstore.model.enums.DocFormat;
22  import org.kuali.ole.docstore.model.xmlpojo.ingest.*;
23  import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
24  import org.kuali.ole.docstore.process.ProcessParameters;
25  import org.kuali.ole.logger.DocStoreLogger;
26  import org.kuali.ole.logger.MetricsLogger;
27  import org.kuali.ole.pojo.OleException;
28  import org.kuali.ole.utility.CompressUtils;
29  import org.slf4j.Logger;
30  import org.slf4j.LoggerFactory;
31  
32  import javax.jcr.*;
33  import java.io.*;
34  import java.util.ArrayList;
35  import java.util.List;
36  
37  /**
38   * Created by IntelliJ IDEA.
39   * User: pvsubrah
40   * Date: 9/14/11
41   * Time: 10:09 AM
42   * To change this template use File | Settings | File Templates.
43   */
44  public class CheckoutManager {
45      MetricsLogger metricsLogger = new MetricsLogger(this.getClass().getName());
46      DocStoreLogger docStoreLogger = new DocStoreLogger(this.getClass().getName());
47      private static final Logger LOG = LoggerFactory.getLogger(CheckoutManager.class);
48  
49  
50      public String checkOut(String uuid, String userName, String action)
51              throws OleException, RepositoryException, FileNotFoundException {
52          return checkOut(null, uuid, userName, action);
53      }
54  
55      public String checkOut(Session session, String uuid, String userName, String action)
56              throws OleException, RepositoryException, FileNotFoundException {
57          Session newSession;
58          String content = "";
59  
60          if (null == session) {
61              newSession = RepositoryManager.getRepositoryManager().getSession(userName, action);
62          } else {
63              newSession = session;
64          }
65          getMetricsLogger().startRecording();
66          Node nodeByUUID = getNodeByUUID(newSession, uuid);
67          if (nodeByUUID != null) {
68              if (nodeByUUID.getName().equalsIgnoreCase(ProcessParameters.NODE_INSTANCE)) {
69                  content = getXMLFORInstanceNode(nodeByUUID);
70              } else {
71                  content = getData(nodeByUUID);
72              }
73          }
74  
75          if (null == session) {
76              RepositoryManager.getRepositoryManager().logout(newSession);
77          }
78          getMetricsLogger().endRecording();
79          getMetricsLogger().printTimes("Time taken for checking out: ");
80          return content;
81      }
82  
83      public String getXMLFORInstanceNode(Node instanceNode)
84              throws RepositoryException, OleException, FileNotFoundException {
85          String instance = "";
86          String holdings = "";
87          String sourceHolding = "";
88          List<String> items = new ArrayList<String>();
89          StringBuffer stringBuffer = new StringBuffer();
90          NodeIterator nodeIterator = instanceNode.getNodes();
91          Node node = null;
92          while (nodeIterator.hasNext()) {
93              node = nodeIterator.nextNode();
94              if (node.getName().equalsIgnoreCase("instanceFile")) {
95                  instance = getData(node);
96              } else if (node.getName().equalsIgnoreCase(ProcessParameters.NODE_HOLDINGS)) {
97                  NodeIterator nodes = node.getNodes();
98                  while (nodes.hasNext()) {
99                      Node node1 = nodes.nextNode();
100                     if (node1.getName().equalsIgnoreCase("holdingsFile")) {
101                         holdings = getData(node1);
102                     } else if (node1.getName().equalsIgnoreCase("sourceHoldingsFile")) {
103                         if (getData(node1) != null && getData(node1).length() > 0) {
104                             sourceHolding = getData(node1);
105                         }
106                     } else if (node1.getName().equalsIgnoreCase("itemFile")) {
107                         items.add(getData(node1));
108                     }
109                 }
110 
111             }
112         }
113         stringBuffer
114                 .append(instance.substring(instance.indexOf("<instanceCollection>"), instance.indexOf("</instance>")));
115         if (!holdings.equalsIgnoreCase("<null/>")) {
116             stringBuffer.append(holdings);
117         }
118         if (!sourceHolding.equalsIgnoreCase("<null/>")) {
119             stringBuffer.append(sourceHolding);
120         }
121         stringBuffer.append("<items>");
122         for (String str : items) {
123             if (!str.equalsIgnoreCase("<null/>")) {
124                 stringBuffer.append(str);
125             }
126         }
127         stringBuffer.append("</items>");
128         stringBuffer.append("</instance>");
129         stringBuffer.append("</instanceCollection>");
130         return stringBuffer.toString();
131     }
132 
133     public String getData(Node nodeByUUID) throws OleException, RepositoryException, FileNotFoundException {
134         StringBuffer stringBuffer = new StringBuffer();
135         if (null != nodeByUUID) {
136             Node jcrContent = nodeByUUID.getNode("jcr:content");
137             Binary binary = jcrContent.getProperty("jcr:data").getBinary();
138             InputStream content = binary.getStream();
139 
140             Writer writer;
141             try {
142                 writer = new StringWriter();
143                 char[] buffer = new char[1024];
144                 try {
145                     Reader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
146                     int n;
147                     while ((n = reader.read(buffer)) != -1) {
148                         writer.write(buffer, 0, n);
149                     }
150                 } finally {
151                     stringBuffer.append(writer.toString());
152                     content.close();
153                 }
154 
155             } catch (IOException e) {
156                 getDocStoreLogger().log("failure during checkOut of ", e);
157             }
158 
159         }
160 
161         return stringBuffer.toString();
162     }
163 
164     public File checkOutMultiPart(Request request) throws Exception {
165         String uuid;
166         Session session = null;
167         Response response = new Response();
168         response.setUser(request.getUser());
169         response.setOperation(request.getOperation());
170         File outputZip = null;
171         File folder = null;
172         try {
173             session = RepositoryManager.getRepositoryManager().getSession(request.getUser(), request.getOperation());
174             folder = File.createTempFile("tmp", "fdi");
175             folder.delete();
176             folder.mkdirs();
177             for (RequestDocument doc : request.getRequestDocuments()) {
178                 uuid = doc.getUuid();
179                 ResponseDocument responseDoc = new ResponseDocument();
180                 responseDoc.setUuid(uuid);
181                 response.getDocuments().add(responseDoc);
182                 Node node = session.getNodeByIdentifier(uuid);
183                 Property fileName = null;
184                 try {
185                     fileName = node.getProperty("fileName");
186                 } catch (PathNotFoundException re) {
187                 }
188                 if (fileName != null) {
189                     File file = new File(folder.getAbsolutePath() + File.separator + fileName.getString());
190                     file.createNewFile();
191                     FileOutputStream fos = new FileOutputStream(file);
192                     getNodeData(node, fos);
193                     responseDoc.setDocumentName(fileName.getString());
194                     Content content = new Content();
195                     content.setContent(getData(node));
196                     responseDoc.setContent(content);
197                 } else {
198                     Content content = new Content();
199                     content.setContent(getData(node));
200                     responseDoc.setContent(content);
201                 }
202                 responseDoc.setId(doc.getId());
203                 responseDoc.setCategory(doc.getCategory());
204                 responseDoc.setFormat(doc.getFormat());
205                 responseDoc.setType(doc.getType());
206             }
207             response.setStatus("Success");
208             response.setStatusMessage("CheckOut Successful.");
209 
210         } catch (Exception e) {
211             response.setStatus("Failure");
212             String failOverMessage = e.getMessage();
213             if (e instanceof ItemNotFoundException) {
214                 failOverMessage = "Document Not Found for uuid : " + failOverMessage;
215             }
216             response.setStatusMessage("CheckOut Failed, Cause: " + failOverMessage);
217             docStoreLogger.log("CheckOut Failed, Cause: " + failOverMessage, e);
218         } finally {
219             if (session != null) {
220                 RepositoryManager.getRepositoryManager().logout(session);
221             }
222             ResponseHandler responseHandler = new ResponseHandler();
223             String responseXml = responseHandler.toXML(response);
224             FileOutputStream fOSResp = new FileOutputStream(
225                     new File(folder.getAbsolutePath() + File.separator + "response.xml"));
226             IOUtils.write(responseXml, fOSResp);
227             try {
228                 fOSResp.close();
229             } catch (Exception exd) {
230                 LOG.error(exd.getMessage() , exd);
231             }
232             outputZip = new CompressUtils().createZippedBagFile(folder);
233             FileUtils.deleteDirectory(folder);
234         }
235         return outputZip;
236     }
237 
238     public void getNodeData(Node nodeByUUID, OutputStream output) throws Exception {
239         if (null != nodeByUUID) {
240             Node jcrContent = nodeByUUID.getNode("jcr:content");
241             Binary binary = jcrContent.getProperty("jcr:data").getBinary();
242             InputStream content = binary.getStream();
243             try {
244                 IOUtils.copy(content, output);
245                 content.close();
246                 output.close();
247             } catch (Exception e) {
248                 LOG.error(e.getMessage() , e);
249             }
250         }
251     }
252 
253     private Node getNodeByUUID(Session newSession, String uuid) throws OleException {
254         return new NodeHandler().getNodeByUUID(newSession, uuid);
255     }
256 
257     public MetricsLogger getMetricsLogger() {
258         return metricsLogger;
259     }
260 
261     public DocStoreLogger getDocStoreLogger() {
262         return docStoreLogger;
263     }
264 
265     public String checkOutBinary(String uuid, String userId, String action, String docFormat)
266             throws OleException, RepositoryException, IOException {
267         return checkOutBinary(null, uuid, userId, action, docFormat);
268     }
269 
270     private String checkOutBinary(Session session, String uuid, String userId, String action, String docFormat)
271             throws OleException, RepositoryException, IOException {
272         FileOutputStream fos = null;
273         Node nodeByUUID = null;
274         Session newSession;
275         File output = File.createTempFile("checkout.", ".output");
276         FileUtils.deleteQuietly(output);
277         output.mkdirs();
278         if (null == session) {
279             newSession = RepositoryManager.getRepositoryManager().getSession(userId, action);
280 
281         } else {
282             newSession = session;
283         }
284         getMetricsLogger().startRecording();
285         nodeByUUID = getNodeByUUID(newSession, uuid);
286         String fileNameAndExtension = null;
287         String outputFilePath = null;
288         if (nodeByUUID != null) {
289             if (docFormat.equalsIgnoreCase(DocFormat.PDF.getCode())) {
290                 fileNameAndExtension = nodeByUUID.getIdentifier() + ".pdf";
291             }
292             if (docFormat.equalsIgnoreCase(DocFormat.DOC.getCode())) {
293                 fileNameAndExtension = nodeByUUID.getIdentifier() + ".doc";
294             }
295             outputFilePath = output.getAbsolutePath() + File.separator + fileNameAndExtension;
296             byte[] binaryContent = getBinaryData(nodeByUUID);
297             fos = new FileOutputStream(outputFilePath);
298             fos.write(binaryContent);
299             fos.close();
300         }
301         if (null == session) {
302             RepositoryManager.getRepositoryManager().logout(newSession);
303         }
304         getMetricsLogger().endRecording();
305         getMetricsLogger().printTimes("Time taken for checking out: ");
306         LOG.info("path-->" + output.getAbsolutePath());
307         return outputFilePath;
308     }
309 
310     private byte[] getBinaryData(Node nodeByUUID) throws RepositoryException, IOException {
311         byte[] bytes = null;
312         if (null != nodeByUUID) {
313             Node jcrContent = nodeByUUID.getNode("jcr:content");
314             Binary binary = jcrContent.getProperty("jcr:data").getBinary();
315             InputStream inputStream = binary.getStream();
316             bytes = getBytesFromInputStream(inputStream);
317         }
318         return bytes;
319     }
320 
321     public byte[] getBytesFromInputStream(InputStream is) throws IOException {
322         long length = is.available();
323         if (length > Integer.MAX_VALUE) {
324             // File is too large
325         }
326         byte[] bytes = new byte[(int) length];
327         // Read in the bytes
328         int offset = 0;
329         int numRead = 0;
330         while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
331             offset += numRead;
332         }
333         // Ensure all the bytes have been read in
334         if (offset < bytes.length) {
335             throw new IOException("Could not completely read file ");
336         }
337         // Close the input stream and return bytes
338         is.close();
339         return bytes;
340     }
341 }