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