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