1 package org.kuali.ole.docstore.discovery.rest;
2
3 import gov.loc.repository.bagit.utilities.FormatHelper;
4 import org.apache.commons.fileupload.FileItem;
5 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
6 import org.apache.commons.fileupload.servlet.ServletFileUpload;
7 import org.apache.commons.io.FileUtils;
8 import org.apache.commons.lang.StringUtils;
9 import org.kuali.ole.DocumentUniqueIDPrefix;
10 import org.kuali.ole.RepositoryBrowser;
11 import org.kuali.ole.RepositoryManager;
12 import org.kuali.ole.docstore.OleDocStoreException;
13 import org.kuali.ole.docstore.discovery.service.ServiceLocator;
14 import org.kuali.ole.docstore.model.xmlpojo.ingest.Request;
15 import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument;
16 import org.kuali.ole.docstore.model.xmlpojo.ingest.Response;
17 import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument;
18 import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler;
19 import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
20 import org.kuali.ole.docstore.service.BeanLocator;
21 import org.kuali.ole.docstore.service.DocumentService;
22 import org.kuali.ole.docstore.service.DocumentServiceImpl;
23 import org.kuali.ole.docstore.service.IngestNIndexHandlerService;
24 import org.kuali.ole.pojo.OleException;
25 import org.kuali.ole.repository.DeleteManager;
26 import org.kuali.ole.repository.DocumentStoreManager;
27 import org.kuali.ole.repository.NodeHandler;
28 import org.kuali.ole.service.OleUuidCheckWebService;
29 import org.kuali.ole.service.OleWebServiceProvider;
30 import org.kuali.ole.service.impl.OleWebServiceProviderImpl;
31 import org.kuali.ole.utility.CompressUtils;
32 import org.kuali.rice.core.api.config.property.ConfigContext;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.web.bind.annotation.PathVariable;
36
37 import javax.jcr.Node;
38 import javax.jcr.RepositoryException;
39 import javax.jcr.Session;
40 import javax.servlet.ServletOutputStream;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43 import javax.ws.rs.*;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import java.io.*;
47 import java.util.ArrayList;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Map;
51
52
53
54
55
56
57
58
59
60 @Path("/documents")
61 public class DocumentResources {
62 private static final Logger LOG = LoggerFactory
63 .getLogger(DocumentResources.class);
64 private IngestNIndexHandlerService ingestNIndexHandlerService = BeanLocator
65 .getIngestNIndexHandlerService();
66 private DocumentStoreManager documentStoreManager = BeanLocator.getDocumentStoreManager();
67 private CompressUtils compressUtils = new CompressUtils();
68 private DocumentService documentService;
69
70
71
72
73
74
75
76
77 @POST
78 @Consumes({MediaType.MULTIPART_FORM_DATA})
79 @Produces({MediaType.TEXT_XML})
80 public String create(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
81 String xmlResponse = null;
82 File targetDir = null;
83 String fileData = null;
84 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
85 String updatesEnabled = "true";
86 boolean isUpdateEnabled = true;
87 if ("false".equalsIgnoreCase(updatesEnabled)) {
88 isUpdateEnabled = false;
89 } else {
90 isUpdateEnabled = true;
91 }
92 if (isMultipart) {
93 LOG.info("Processing in Multipart : START");
94 FileItem item = getFileItemFromRequest(request);
95 String contentType = item.getContentType();
96 LOG.info("content type-->" + contentType);
97 if (contentType.equalsIgnoreCase(MediaType.APPLICATION_OCTET_STREAM)) {
98 File outputFile = new File(FileUtils.getTempDirectory(), item.getName());
99 item.write(outputFile);
100 targetDir = compressUtils.extractZippedBagFile(outputFile.getAbsolutePath(), null);
101 ArrayList<File> files = compressUtils.getAllFilesList(targetDir);
102 try {
103 RequestHandler rh = new RequestHandler();
104 Request dsRequest = null;
105 for (File file : files) {
106 if (file.getName().equalsIgnoreCase("request.xml")) {
107 String rqStr = FileUtils.readFileToString(file);
108 dsRequest = rh.toObject(rqStr);
109 for (RequestDocument rd : dsRequest.getRequestDocuments()) {
110 if (rd.getDocumentName() != null) {
111 for (File fl : files) {
112 if (fl.getName().equals(rd.getDocumentName())) {
113 rd.setDocumentName(fl.getAbsolutePath());
114 break;
115 }
116 }
117 }
118 }
119 if ("ingest".equalsIgnoreCase(dsRequest.getOperation())) {
120 if (isUpdateEnabled) {
121
122
123 Response docStoreResponse = BeanLocator.getDocumentServiceImpl().process(dsRequest);
124 LOG.info("xmlResponse :" + new ResponseHandler().toXML(docStoreResponse));
125 sendResponseBag(response, docStoreResponse);
126 } else {
127 sendUnavailableResponseString(response);
128 }
129 } else if ("checkIn".equalsIgnoreCase(dsRequest.getOperation())) {
130 if (isUpdateEnabled) {
131 Response dsResponse = new Response();
132 checkIn(dsRequest, dsResponse);
133 sendResponseBag(response, dsResponse);
134 } else {
135 sendUnavailableResponseString(response);
136 }
137
138 } else {
139 response.sendError(HttpServletResponse.SC_BAD_REQUEST,
140 "Invalid Request Operation: " + dsRequest.getOperation());
141 }
142 break;
143 }
144 }
145 files.add(files.get(files.size() - 1).getParentFile());
146 compressUtils.deleteFiles(files);
147 } catch (Exception e) {
148 LOG.error("Invalid Request : " + e.getMessage(), e);
149 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Request : " + e.getMessage());
150 }
151 LOG.info("Processing in Multipart : END");
152
153
154 } else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML)) {
155 File file = new File(FileUtils.getTempDirectory(), item.getName());
156 item.write(file);
157 fileData = FileUtils.readFileToString(file, "UTF-8");
158 file.delete();
159
160
161 Request dsRequest = null;
162 try{
163 dsRequest = new RequestHandler().toObject(fileData);
164 Response dsResponse = BeanLocator.getDocumentServiceImpl().process(dsRequest);
165 xmlResponse = new ResponseHandler().toXML(dsResponse);
166 LOG.info("xmlResponse-->" + xmlResponse);
167 } catch (Exception e){
168 LOG.error("Invalid Request : " + e.getMessage(), e);
169 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Request : " +e.getMessage());
170 }
171 }
172
173 }
174
175 return xmlResponse;
176
177 }
178
179
180
181
182
183
184
185
186
187 private String getFileContent(@Context HttpServletRequest request, @Context HttpServletResponse response)
188 throws IOException
189
190 {
191 int maxFileSize = 100 * 1024;
192 int maxMemSize = 4 * 1024;
193 File file = null;
194 DiskFileItemFactory factory = new DiskFileItemFactory();
195
196 factory.setSizeThreshold(maxMemSize);
197
198 File output = File.createTempFile("ingest.", ".output");
199 FileUtils.deleteQuietly(output);
200 factory.setRepository(output);
201
202
203 ServletFileUpload upload = new ServletFileUpload(factory);
204
205
206 upload.setSizeMax(maxFileSize);
207 String fileData = null;
208 try {
209
210 List fileItems = upload.parseRequest(request);
211
212
213 Iterator i = fileItems.iterator();
214
215 while (i.hasNext()) {
216 FileItem fi = (FileItem) i.next();
217 if (!fi.isFormField()) {
218
219
220 String fieldName = fi.getFieldName();
221 String fileName = fi.getName();
222 String contentType = fi.getContentType();
223 LOG.debug("item Name = " + fi.getName() + " ; content type = " + fi.getContentType());
224 boolean isInMemory = fi.isInMemory();
225 long sizeInBytes = fi.getSize();
226
227
228 fi.write(output);
229 LOG.debug("Uploaded Filename: " + fileName);
230 LOG.debug("Uploaded output path: " + output.getAbsolutePath());
231 }
232 }
233 fileData = FileUtils.readFileToString(output, "UTF-8");
234 output.delete();
235
236 } catch (Exception ex) {
237 LOG.error("error while ingesting :" + ex);
238 }
239
240 return fileData;
241 }
242
243
244
245
246
247 private FileItem getFileItemFromRequest(@Context HttpServletRequest req) throws Exception, Exception {
248 int maxFileSize = 100 * 1024;
249 int maxMemSize = 4 * 1024;
250 File file = null;
251 DiskFileItemFactory factory = new DiskFileItemFactory();
252
253 factory.setSizeThreshold(maxMemSize);
254
255
256 ServletFileUpload upload = new ServletFileUpload(factory);
257
258
259 upload.setSizeMax(maxFileSize);
260 String fileData = null;
261
262
263 List fileItems = upload.parseRequest(req);
264
265
266 Iterator i = fileItems.iterator();
267
268 FileItem fi = null;
269 while (i.hasNext()) {
270 fi = (FileItem) i.next();
271 if (!fi.isFormField()) {
272
273
274 String fieldName = fi.getFieldName();
275 String fileName = fi.getName();
276 String contentType = fi.getContentType();
277 LOG.debug(
278 "In getFileContent() item Name = " + fi.getName() + " ; content type = " + fi.getContentType());
279
280 }
281 }
282 return fi;
283 }
284
285
286
287
288
289
290 @GET
291 @Path("{id}")
292 @Produces({MediaType.TEXT_XML, MediaType.TEXT_PLAIN})
293 public String findById(@PathParam("id") String id) throws Exception {
294 LOG.info("id--> " + id);
295 String xmlResponse = null;
296 Response response = null;
297 try {
298 response = checkOut(id);
299 LOG.debug("checkOut response-->" + xmlResponse);
300 } catch (Exception e) {
301 LOG.error("Exception while checkout" + e);
302 }
303 return new ResponseHandler().toXML(response);
304 }
305
306
307
308
309
310 @GET
311 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_OCTET_STREAM})
312 public String getCheckOutResponse(@Context HttpServletRequest httpServletRequest,
313 @QueryParam("category") String category, @QueryParam("type") String type,
314 @QueryParam("format") String format,
315 @QueryParam("staringUUID") String staringUUID,
316 @QueryParam("endingUUID") String numUUIDs) throws Exception {
317 String requestXML = null;
318 String responseXML = null;
319 requestXML = httpServletRequest.getParameter("checkOutRequest");
320 LOG.debug("requestXML-->" + requestXML);
321 if (!StringUtils.isBlank(requestXML)) {
322 LOG.debug("requestXML-->" + requestXML);
323 Request dsRequest = new RequestHandler().toObject(requestXML);
324 File output = documentStoreManager.checkOutMultiPart(dsRequest);
325 File extractDir = compressUtils.extractZippedBagFile(output.getAbsolutePath(), null);
326 LOG.debug("extractDir-->" + extractDir.getAbsolutePath());
327 String responsePath = extractDir + File.separator + "response.xml";
328 File responseFile = new File(responsePath);
329 if (extractDir.isDirectory() && responseFile.isFile()) {
330 responseXML = FileUtils.readFileToString(responseFile);
331 LOG.debug("response-->" + responseXML);
332 }
333
334 } else {
335 int startIndex = Integer.parseInt(staringUUID);
336 LOG.debug("numUUIDs -->" + numUUIDs);
337 int endIndex = Integer.parseInt(numUUIDs);
338 RepositoryBrowser repositoryBrowser = new RepositoryBrowser();
339 List<String> uuidList = repositoryBrowser.getUUIDs(category, type, format, startIndex, endIndex);
340 Response response = buildResponse(uuidList, category, type, format);
341 responseXML = new ResponseHandler().toXML(response);
342 LOG.debug("response XML-->" + responseXML);
343
344 }
345 return responseXML;
346 }
347
348
349
350
351
352
353
354
355
356
357 public Response buildResponse(List<String> uuidList, String category, String type, String format) {
358 Response response = new Response();
359 response.setOperation("getUUIDs");
360 ArrayList<ResponseDocument> responseDocumentList = new ArrayList<ResponseDocument>();
361 for (int i = 0; i < uuidList.size(); i++) {
362 ResponseDocument responseDocument = new ResponseDocument();
363 responseDocument.setId(String.valueOf(i + 1));
364 responseDocument.setCategory(category);
365 responseDocument.setType(type);
366 responseDocument.setFormat(format);
367 responseDocument.setUuid(uuidList.get(i));
368 responseDocumentList.add(responseDocument);
369 }
370 response.setDocuments(responseDocumentList);
371 return response;
372 }
373
374 @PUT
375 @Consumes({MediaType.APPLICATION_XML})
376 @Produces({MediaType.TEXT_XML})
377 public String update(@PathVariable("stringContent") String stringContent) {
378 LOG.debug("check in content-->" + stringContent);
379 RequestHandler requestHandler = new RequestHandler();
380 Request request = requestHandler.toObject(stringContent);
381 String checkInResponse = checkIn(request, null);
382 LOG.debug("checkInResponse-->" + checkInResponse);
383 return checkInResponse;
384 }
385
386 @PUT
387 @Path("{bind}")
388 @Consumes({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
389 @Produces({MediaType.TEXT_XML})
390 public String bind(@PathParam("bind") String operation, @QueryParam("stringContent") String stringContent) throws OleDocStoreException, RepositoryException, OleException, FileNotFoundException {
391 LOG.info("request-->" + stringContent);
392 Response response = new Response();
393 RequestHandler requestHandler = new RequestHandler();
394 Request request = requestHandler.toObject(stringContent);
395 documentService = DocumentServiceImpl.getInstance();
396 if ((request.getOperation().equalsIgnoreCase("bind")) || (request.getOperation().equalsIgnoreCase("unbind"))) {
397 LOG.info("operation-->" + operation);
398 response = documentService.process(request);
399 LOG.info("response-->" + new ResponseHandler().toXML(response));
400 }
401
402 return new ResponseHandler().toXML(response);
403 }
404
405
406 @DELETE
407 @Path("{id}")
408 @Produces({MediaType.TEXT_XML})
409 public String remove(@PathParam("id") String ids, @QueryParam("identifierType") String identifierType,
410 @QueryParam("operation") String operation, @QueryParam("docCategory") String docCategory, @QueryParam("docType") String docType, @QueryParam("docFormat") String docFormat) throws IOException, RepositoryException, OleException, OleDocStoreException {
411 LOG.debug("ids-->" + ids);
412 LOG.debug("identifier-->" + identifierType);
413 LOG.debug("operation-->" + operation);
414 Request request = null;
415 request = buildRequest(ids, identifierType, operation, docCategory, docType, docFormat);
416
417 documentService = DocumentServiceImpl.getInstance();
418 Response response = documentService.process(request);
419
420 LOG.debug("response-->" + new ResponseHandler().toXML(response));
421 return new ResponseHandler().toXML(response);
422 }
423
424
425 @DELETE
426 @Produces({MediaType.TEXT_XML})
427 public String removeDocuments(@PathVariable("deleteRequest") String deleteRequest) throws IOException {
428 LOG.debug("request xml for delete-->" + deleteRequest);
429 RequestHandler requestHandler = new RequestHandler();
430 Request request = requestHandler.toObject(deleteRequest);
431 Response response = processDeleteRequest(request);
432 String deleteResponse = new ResponseHandler().toXML(response);
433 LOG.debug("delete response -->" + deleteResponse);
434
435 return deleteResponse;
436 }
437
438 private Request buildRequest(String ids, String identifierType, String operation, String category, String type, String format) {
439 String[] Id = ids.split(",");
440 List<String> idList = new ArrayList<String>();
441 List<String> uuidList = new ArrayList<String>();
442 Request request = new Request();
443 for (int i = 0; i < Id.length; i++) {
444 idList.add(Id[i]);
445 LOG.debug("adding -->" + idList);
446 }
447 if ((!StringUtils.isBlank(identifierType)) && identifierType.equalsIgnoreCase("SCN") || identifierType
448 .equalsIgnoreCase("ISBN")) {
449 uuidList = ServiceLocator.getQueryService().getUUIDList(idList, identifierType);
450 } else {
451 uuidList = idList;
452 }
453 request = buildRequest(uuidList, operation, category, type, format);
454 return request;
455
456
457 }
458
459 private Request buildRequest(List<String> uuidList, String operation, String category, String type, String format) {
460 Request request = new Request();
461 List<RequestDocument> requestDocumentList = new ArrayList<RequestDocument>();
462 request.setUser("ole-khuntley");
463 request.setOperation(operation);
464 for (int i = 0; i < uuidList.size(); i++) {
465 if (DocumentUniqueIDPrefix.hasPrefix(uuidList.get(i))) {
466 Map<String, String> categoryTypeFormat = DocumentUniqueIDPrefix.getCategoryTypeFormat(uuidList.get(i));
467 category = categoryTypeFormat.get("category");
468 type = categoryTypeFormat.get("type");
469 format = categoryTypeFormat.get("format");
470 }
471
472 RequestDocument requestDocument = new RequestDocument();
473 requestDocument.setCategory(category);
474 requestDocument.setType(type);
475 requestDocument.setFormat(format);
476 requestDocument.setUuid(uuidList.get(i));
477 requestDocumentList.add(requestDocument);
478 }
479 request.setRequestDocuments(requestDocumentList);
480 return request;
481 }
482
483 protected Response processDeleteRequest(Request dsRequest) throws IOException {
484 DeleteManager deleteManager = new DeleteManager();
485 List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
486 requestDocuments = dsRequest.getRequestDocuments();
487 Response response = null;
488 String uuidsNotInOle = null;
489 String serviceURL = null;
490 StringBuilder uuidsSB = null;
491 try {
492 if ((requestDocuments == null) || (requestDocuments.size() == 0)) {
493 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failed",
494 "Deletion failed: No documents specified for deletion.");
495 } else {
496
497 uuidsSB = new StringBuilder();
498 for (RequestDocument requestDocument : requestDocuments) {
499 uuidsSB.append(requestDocument.getUuid()).append(",");
500 }
501 serviceURL = ConfigContext.getCurrentContextConfig().getProperty("uuidCheckServiceURL");
502 LOG.info(" uuidCheckServiceURL --------> " + serviceURL);
503 boolean verifiedWithOLE = true;
504 try {
505
506 OleWebServiceProvider oleWebServiceProvider = new OleWebServiceProviderImpl();
507
508 OleUuidCheckWebService oleUuidCheckWebService = (OleUuidCheckWebService) oleWebServiceProvider
509 .getService("org.kuali.ole.service.OleUuidCheckWebService", "oleUuidCheckWebService",
510 serviceURL);
511
512 uuidsNotInOle = oleUuidCheckWebService
513 .checkUuidExsistence(uuidsSB.substring(0, uuidsSB.length() - 1));
514 } catch (Exception e) {
515 verifiedWithOLE = false;
516 LOG.error("Check uuid call to OLE failed:", e);
517 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure",
518 "Deletion failed: Exception while connecting to OLE service to verify the existence of documents."
519 + e.getMessage());
520 }
521 if (verifiedWithOLE) {
522 LOG.info("response uuids from OLE " + uuidsNotInOle);
523
524 if ((uuidsNotInOle != null) && (uuidsNotInOle.length() > 0)) {
525 String[] uuids = StringUtils.split(uuidsNotInOle, ",");
526 requestDocuments = new ArrayList<RequestDocument>();
527 for (String id : uuids) {
528 RequestDocument requestDocument = new RequestDocument();
529 requestDocument.setUuid(id);
530 requestDocuments.add(requestDocument);
531 }
532 dsRequest.setRequestDocuments(requestDocuments);
533 try {
534 response = deleteManager.deleteDocs(dsRequest);
535 } catch (Exception e) {
536 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure",
537 "Deletion failed: Exception while deleting from docstore. "
538 + e.getMessage());
539 }
540 } else {
541 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure",
542 "Deletion failed: Documents exist in OLE database and cannot be deleted.");
543 }
544 }
545 }
546 } catch (Exception e) {
547 LOG.error("delete operation failed:", e);
548 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure", "Failed : " + e.getMessage());
549 }
550 return response;
551 }
552
553 public String checkIn(Request dsRequest, Response dsResponse) {
554 if (dsResponse == null) {
555 dsResponse = new Response();
556 }
557 String checkInResponse = null;
558 List<String> latestVersion = new ArrayList<String>();
559 try {
560 dsResponse = BeanLocator.getDocumentServiceImpl().process(dsRequest);
561 checkInResponse = (new ResponseHandler().toXML(dsResponse));
562 } catch (Exception ex) {
563
564 String failOverMessage = ex.getMessage();
565 failOverMessage = failOverMessage.replace("javax.jcr.ItemNotFoundException", "Document Not Found for uuid");
566 checkInResponse = printResponse(dsResponse, dsRequest.getOperation(), "Failure", "Checkin failed",
567 failOverMessage);
568 }
569 return checkInResponse;
570 }
571
572 private String printResponse(Response response, String operation, String status, String message,
573 String statusMessage) {
574 String resp = null;
575 if (response == null) {
576 response = new Response();
577 }
578 response.setOperation(operation);
579 response.setStatus(status);
580 response.setMessage(message);
581 response.setStatusMessage(statusMessage);
582 resp = new ResponseHandler().toXML(response);
583 return resp;
584 }
585
586 protected Response checkOut(String uuid) throws Exception {
587
588 String checkoutResponse = null;
589 Request req = null;
590 Response dsResponse = null;
591 try {
592 if (DocumentUniqueIDPrefix.hasPrefix(uuid)) {
593 Map<String, String> categoryTypeFormat = DocumentUniqueIDPrefix.getCategoryTypeFormat(uuid);
594 String category = categoryTypeFormat.get("category");
595 String type = categoryTypeFormat.get("type");
596 String format = categoryTypeFormat.get("format");
597 req = new Request();
598 RequestDocument requestDocument = buildRequestDocument(category, type, format, uuid);
599 List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
600 requestDocuments.add(requestDocument);
601 req.setOperation("checkOut");
602 req.setUser("checkOutUser");
603 req.setRequestDocuments(requestDocuments);
604 }
605 if (req == null) {
606
607 req = getRequest(uuid, null, null);
608 }
609 dsResponse = BeanLocator.getDocumentServiceImpl().process(req);
610 if (dsResponse != null) {
611 for (ResponseDocument responseDocument : dsResponse.getDocuments()) {
612 if (responseDocument != null && responseDocument.getContent() != null) {
613 checkoutResponse = responseDocument.getContent().getContent();
614 }
615 checkoutResponse = checkoutResponse + "\n";
616 }
617 }
618
619 LOG.info("xmlResponse-->" + checkoutResponse);
620 } catch (Exception ex) {
621 LOG.error("Error while performing checkout process", ex);
622 }
623
624 return dsResponse;
625
626 }
627
628
629 private RequestDocument buildRequestDocument(String cat, String type, String format, String uuid) {
630 RequestDocument reqDoc = new RequestDocument();
631 reqDoc.setCategory(cat);
632 reqDoc.setType(type);
633 reqDoc.setFormat(format);
634 reqDoc.setUuid(uuid);
635 return reqDoc;
636
637 }
638
639 private Request getRequest(String uuid, String userId, String action) throws OleDocStoreException, OleException {
640
641 Node nodeByUUID = null;
642 Session session = null;
643 Request req = new Request();
644 if (action == null || "".equalsIgnoreCase(action)) {
645 action = "checkOut";
646 }
647 if (userId == null || "".equalsIgnoreCase(userId)) {
648 userId = "RestWebUser";
649 }
650 session = RepositoryManager.getRepositoryManager().getSession(userId, action);
651 String cat = null;
652 String type = null;
653 String format = null;
654 try {
655 NodeHandler nodeHandler = new NodeHandler();
656 nodeByUUID = nodeHandler.getNodeByUUID(session, uuid);
657 String nodePath = nodeByUUID.getPath();
658 String[] splitLine = nodePath.split("/");
659
660 if (splitLine != null && splitLine.length >= 4) {
661 cat = splitLine[1];
662 type = splitLine[2];
663 format = splitLine[3];
664 } else {
665 throw new OleDocStoreException(" This is not a valid UUID ");
666 }
667 req.setOperation(action);
668 req.setUser(userId);
669 List<RequestDocument> reqDocList = new ArrayList<RequestDocument>();
670 RequestDocument reqDoc = buildRequest(cat, type, format, uuid);
671 reqDocList.add(reqDoc);
672 req.setRequestDocuments(reqDocList);
673 } catch (Exception e) {
674 LOG.info(e.getMessage(), e);
675 throw new OleDocStoreException(e);
676 } finally {
677 session.logout();
678 }
679 return req;
680 }
681
682 private RequestDocument buildRequest(String cat, String type, String format, String uuid) {
683 RequestDocument reqDoc = new RequestDocument();
684 reqDoc.setCategory(cat);
685 reqDoc.setType(type);
686 reqDoc.setFormat(format);
687 reqDoc.setUuid(uuid);
688 return reqDoc;
689
690 }
691
692 private ArrayList<File> extractBagFilesFromRequest(@Context HttpServletRequest req,
693 @Context HttpServletResponse res) throws Exception {
694 File targetDir = null;
695 try {
696 File file = null;
697 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
698 fileItemFactory.setSizeThreshold(1 * 1024 * 1024);
699 Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
700 while (items.hasNext()) {
701 FileItem item = (FileItem) items.next();
702 LOG.info("item Name = " + item.getName() + " ; content type = " + item.getContentType());
703 file = new File(FileUtils.getTempDirectory(), item.getName());
704 item.write(file);
705 }
706 targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null);
707 LOG.info("extractedBagFileLocation " + targetDir);
708 } catch (IOException e) {
709 LOG.error("IOException", e);
710 sendResponseBag(res, e.getMessage(), "failure");
711 } catch (FormatHelper.UnknownFormatException unknownFormatException) {
712 LOG.error("unknownFormatException", unknownFormatException);
713 sendResponseBag(res, unknownFormatException.getMessage(), "failure");
714 }
715 return compressUtils.getAllFilesList(targetDir);
716 }
717
718
719
720
721
722
723
724
725
726 private void sendResponseBag(@Context HttpServletResponse res, String message, String status) {
727 Response response = new Response();
728 response.setMessage(message);
729 response.setStatus(status);
730 sendResponseBag(res, response);
731 }
732
733 private void sendResponseBag(@Context HttpServletResponse res, @Context Response docStoreResponse) {
734 String responseXML = new ResponseHandler().toXML(docStoreResponse);
735 try {
736 File output = File.createTempFile("checkout.", ".output");
737 FileUtils.deleteQuietly(output);
738 output.mkdirs();
739 File file = new File(output + File.separator + "response.xml");
740 Writer writer = null;
741 writer = new BufferedWriter(new FileWriter(file));
742 writer.write(responseXML);
743 writer.close();
744 File zipFile = compressUtils.createZippedBagFile(output);
745 res.setContentType("application/zip");
746 sendResponseAsFile(res, zipFile);
747 zipFile.delete();
748 } catch (IOException e) {
749 LOG.error("IOException", e);
750 }
751 }
752
753
754
755
756
757
758
759
760 private void sendResponseAsFile(HttpServletResponse res, File file) throws IOException {
761 ServletOutputStream stream = res.getOutputStream();
762 FileInputStream fos = new FileInputStream(file.getAbsolutePath());
763 BufferedInputStream buf = new BufferedInputStream(fos);
764 int readBytes = 0;
765 while ((readBytes = buf.read()) != -1) {
766 stream.write(readBytes);
767 }
768 if (stream != null) {
769 stream.close();
770 }
771 if (buf != null) {
772 buf.close();
773 }
774 res.flushBuffer();
775 }
776
777 private void sendUnavailableResponseString(HttpServletResponse response) {
778 try {
779 PrintWriter out = response.getWriter();
780 out.println("The Requested Operation is not available");
781 } catch (IOException e) {
782 LOG.error("IOException", e);
783 }
784 }
785
786 }