001 package org.kuali.ole.docstore.discovery.rest; 002 003 import gov.loc.repository.bagit.utilities.FormatHelper; 004 import org.apache.commons.fileupload.FileItem; 005 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 006 import org.apache.commons.fileupload.servlet.ServletFileUpload; 007 import org.apache.commons.io.FileUtils; 008 import org.apache.commons.lang.StringUtils; 009 import org.kuali.ole.RepositoryBrowser; 010 import org.kuali.ole.RepositoryManager; 011 import org.kuali.ole.docstore.OleDocStoreException; 012 import org.kuali.ole.docstore.discovery.service.ServiceLocator; 013 import org.kuali.ole.docstore.model.xmlpojo.ingest.Request; 014 import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument; 015 import org.kuali.ole.docstore.model.xmlpojo.ingest.Response; 016 import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument; 017 import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler; 018 import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler; 019 import org.kuali.ole.docstore.service.BeanLocator; 020 import org.kuali.ole.docstore.service.IngestNIndexHandlerService; 021 import org.kuali.ole.docstore.util.PropertyUtil; 022 import org.kuali.ole.pojo.OleException; 023 import org.kuali.ole.repository.DeleteManager; 024 import org.kuali.ole.repository.DocumentStoreManager; 025 import org.kuali.ole.repository.NodeHandler; 026 import org.kuali.ole.service.OleUuidCheckWebService; 027 import org.kuali.ole.service.OleWebServiceProvider; 028 import org.kuali.ole.service.impl.OleWebServiceProviderImpl; 029 import org.kuali.ole.utility.CompressUtils; 030 import org.slf4j.Logger; 031 import org.slf4j.LoggerFactory; 032 import org.springframework.web.bind.annotation.PathVariable; 033 034 import javax.jcr.Node; 035 import javax.jcr.Session; 036 import javax.servlet.ServletOutputStream; 037 import javax.servlet.http.HttpServletRequest; 038 import javax.servlet.http.HttpServletResponse; 039 import javax.ws.rs.*; 040 import javax.ws.rs.core.Context; 041 import javax.ws.rs.core.MediaType; 042 import java.io.*; 043 import java.util.ArrayList; 044 import java.util.HashMap; 045 import java.util.Iterator; 046 import java.util.List; 047 048 049 /** 050 * Created with IntelliJ IDEA. 051 * User: Sreekanth 052 * Date: 8/3/12 053 * Time: 3:47 PM 054 * To change this template use File | Settings | File Templates. 055 */ 056 @Path("/documents") 057 public class DocumentResources { 058 private static final Logger LOG = LoggerFactory 059 .getLogger(DocumentResources.class); 060 private IngestNIndexHandlerService ingestNIndexHandlerService = BeanLocator 061 .getIngestNIndexHandlerService(); 062 private DocumentStoreManager documentStoreManager = BeanLocator.getDocumentStoreManager(); 063 private CompressUtils compressUtils = new CompressUtils(); 064 065 066 /** 067 * This method ingest the string content and returns the response 068 * 069 * @return 070 * @throws IOException 071 */ 072 @POST 073 @Consumes({MediaType.MULTIPART_FORM_DATA}) 074 @Produces({MediaType.TEXT_XML}) 075 public String create(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception { 076 String xmlResponse = null; 077 File targetDir = null; 078 String fileData = null; 079 boolean isMultipart = ServletFileUpload.isMultipartContent(request); 080 String updatesEnabled = "true"; 081 boolean isUpdateEnabled = true; 082 if ("false".equalsIgnoreCase(updatesEnabled)) { 083 isUpdateEnabled = false; 084 } 085 else { 086 isUpdateEnabled = true; 087 } 088 if (isMultipart) { 089 LOG.info("Processing in Multipart : START"); 090 FileItem item = getFileItemFromRequest(request); 091 String contentType = item.getContentType(); 092 LOG.info("content type-->" + contentType); 093 if (contentType.equalsIgnoreCase(MediaType.APPLICATION_OCTET_STREAM)) { 094 File outputFile = new File(FileUtils.getTempDirectory(), item.getName()); 095 item.write(outputFile); 096 targetDir = compressUtils.extractZippedBagFile(outputFile.getAbsolutePath(), null); 097 ArrayList<File> files = compressUtils.getAllFilesList(targetDir); 098 try { 099 RequestHandler rh = new RequestHandler(); 100 Request dsRequest = null; 101 for (File file : files) { 102 if (file.getName().equalsIgnoreCase("request.xml")) { 103 String rqStr = FileUtils.readFileToString(file); 104 dsRequest = rh.toObject(rqStr); 105 for (RequestDocument rd : dsRequest.getRequestDocuments()) { 106 if (rd.getDocumentName() != null) { 107 for (File fl : files) { 108 if (fl.getName().equals(rd.getDocumentName())) { 109 rd.setDocumentName(fl.getAbsolutePath()); 110 break; 111 } 112 } 113 } 114 } 115 if ("ingest".equalsIgnoreCase(dsRequest.getOperation())) { 116 if (isUpdateEnabled) { 117 Response docStoreResponse = ingestNIndexHandlerService 118 .ingestNIndexRequestDocuments(dsRequest); 119 sendResponseBag(response, docStoreResponse); 120 } 121 else { 122 sendUnavailableResponseString(response); 123 } 124 } 125 else if ("checkIn".equalsIgnoreCase(dsRequest.getOperation())) { 126 if (isUpdateEnabled) { 127 Response dsResponse = new Response(); 128 checkIn(dsRequest, dsResponse); 129 sendResponseBag(response, dsResponse); 130 } 131 else { 132 sendUnavailableResponseString(response); 133 } 134 135 } 136 else { 137 response.sendError(HttpServletResponse.SC_BAD_REQUEST, 138 "Invalid Request Operation: " + dsRequest.getOperation()); 139 } 140 break; 141 } 142 } 143 files.add(files.get(files.size() - 1).getParentFile()); 144 compressUtils.deleteFiles(files); 145 } 146 catch (Exception e) { 147 LOG.error("Invalid Request : " + e.getMessage(), e); 148 e.printStackTrace(); 149 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Request : " + e.getMessage()); 150 } 151 LOG.info("Processing in Multipart : END"); 152 153 154 } 155 else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML)) { 156 File file = new File(FileUtils.getTempDirectory(), item.getName()); 157 item.write(file); 158 fileData = FileUtils.readFileToString(file, "UTF-8"); 159 file.delete(); 160 xmlResponse = ingestNIndexHandlerService.ingestNIndexRequestDocuments(fileData); 161 LOG.info("response-->" + xmlResponse); 162 /*Request dsRequest = new RequestHandler().toObject(fileData); 163 Response dsResponse = BeanLocator.getDocumentServiceImpl().process(dsRequest); 164 xmlResponse = new ResponseHandler().toXML(dsResponse); 165 LOG.info("xmlResponse-->" + xmlResponse);*/ 166 167 168 } 169 170 } 171 172 return xmlResponse; 173 174 } 175 176 /** 177 * This methods reads the uploaded file content from request and returns the file content 178 * 179 * @param request 180 * @param response 181 * @return 182 * @throws IOException 183 */ 184 private String getFileContent(@Context HttpServletRequest request, @Context HttpServletResponse response) 185 throws IOException 186 187 { 188 int maxFileSize = 50 * 1024; 189 int maxMemSize = 4 * 1024; 190 File file = null; 191 DiskFileItemFactory factory = new DiskFileItemFactory(); 192 // maximum size that will be stored in memory 193 factory.setSizeThreshold(maxMemSize); 194 // Location to save data that is larger than maxMemSize. 195 File output = File.createTempFile("ingest.", ".output"); 196 FileUtils.deleteQuietly(output); 197 factory.setRepository(output); 198 199 // Create a new file upload handler 200 ServletFileUpload upload = new ServletFileUpload(factory); 201 202 // maximum file size to be uploaded. 203 upload.setSizeMax(maxFileSize); 204 String fileData = null; 205 try { 206 // Parse the request to get file items. 207 List fileItems = upload.parseRequest(request); 208 209 // Process the uploaded file items 210 Iterator i = fileItems.iterator(); 211 212 while (i.hasNext()) { 213 FileItem fi = (FileItem) i.next(); 214 if (!fi.isFormField()) { 215 216 // Get the uploaded file parameters 217 String fieldName = fi.getFieldName(); 218 String fileName = fi.getName(); 219 String contentType = fi.getContentType(); 220 LOG.debug("item Name = " + fi.getName() + " ; content type = " + fi.getContentType()); 221 boolean isInMemory = fi.isInMemory(); 222 long sizeInBytes = fi.getSize(); 223 224 // Write the file 225 fi.write(output); 226 LOG.debug("Uploaded Filename: " + fileName); 227 LOG.debug("Uploaded output path: " + output.getAbsolutePath()); 228 } 229 } 230 fileData = FileUtils.readFileToString(output, "UTF-8"); 231 output.delete(); 232 233 } 234 catch (Exception ex) { 235 LOG.error("error while ingesting :" + ex); 236 } 237 238 return fileData; 239 } 240 241 242 /** 243 * @return 244 */ 245 private FileItem getFileItemFromRequest(@Context HttpServletRequest req) throws Exception, Exception { 246 int maxFileSize = 50 * 1024; 247 int maxMemSize = 4 * 1024; 248 File file = null; 249 DiskFileItemFactory factory = new DiskFileItemFactory(); 250 // maximum size that will be stored in memory 251 factory.setSizeThreshold(maxMemSize); 252 253 // Create a new file upload handler 254 ServletFileUpload upload = new ServletFileUpload(factory); 255 256 // maximum file size to be uploaded. 257 upload.setSizeMax(maxFileSize); 258 String fileData = null; 259 260 // Parse the request to get file items. 261 List fileItems = upload.parseRequest(req); 262 263 // Process the uploaded file items 264 Iterator i = fileItems.iterator(); 265 266 FileItem fi = null; 267 while (i.hasNext()) { 268 fi = (FileItem) i.next(); 269 if (!fi.isFormField()) { 270 271 // Get the uploaded file parameters 272 String fieldName = fi.getFieldName(); 273 String fileName = fi.getName(); 274 String contentType = fi.getContentType(); 275 LOG.debug( 276 "In getFileContent() item Name = " + fi.getName() + " ; content type = " + fi.getContentType()); 277 278 } 279 } 280 return fi; 281 } 282 283 /** 284 * @param id 285 * @return 286 */ 287 288 @GET 289 @Path("{id}") 290 @Produces({MediaType.TEXT_XML, MediaType.TEXT_PLAIN}) 291 public String findById(@PathParam("id") String id) throws Exception { 292 LOG.info("id--> " + id); 293 String xmlResponse = null; 294 try { 295 xmlResponse = checkOut(id, null); 296 LOG.debug("checkOut response-->" + xmlResponse); 297 } 298 catch (Exception e) { 299 LOG.error("Exception while checkout" + e); 300 } 301 302 303 return xmlResponse; 304 } 305 306 /** 307 * @return 308 * @throws Exception 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 } 335 else { 336 int startIndex = Integer.parseInt(staringUUID); 337 LOG.debug("numUUIDs -->" + numUUIDs); 338 int endIndex = Integer.parseInt(numUUIDs); 339 RepositoryBrowser repositoryBrowser = new RepositoryBrowser(); 340 List<String> uuidList = repositoryBrowser.getUUIDs(category, type, format, startIndex, endIndex); 341 Response response = buildResponse(uuidList, category, type, format); 342 responseXML = new ResponseHandler().toXML(response); 343 LOG.debug("response XML-->" + responseXML); 344 345 } 346 return responseXML; 347 } 348 349 /** 350 * This method builds the response for the list of UUID's 351 * 352 * @param uuidList 353 * @param category 354 * @param type 355 * @param format 356 * @return 357 */ 358 public Response buildResponse(List<String> uuidList, String category, String type, String format) { 359 Response response = new Response(); 360 response.setOperation("getUUIDs"); 361 ArrayList<ResponseDocument> responseDocumentList = new ArrayList<ResponseDocument>(); 362 for (int i = 0; i < uuidList.size(); i++) { 363 ResponseDocument responseDocument = new ResponseDocument(); 364 responseDocument.setId(String.valueOf(i + 1)); 365 responseDocument.setCategory(category); 366 responseDocument.setType(type); 367 responseDocument.setFormat(format); 368 responseDocument.setUuid(uuidList.get(i)); 369 responseDocumentList.add(responseDocument); 370 } 371 response.setDocuments(responseDocumentList); 372 return response; 373 } 374 375 @PUT 376 @Consumes({MediaType.APPLICATION_XML}) 377 @Produces({MediaType.TEXT_XML}) 378 public String update(@PathVariable("stringContent") String stringContent) { 379 LOG.debug("check in content-->" + stringContent); 380 RequestHandler requestHandler = new RequestHandler(); 381 Request request = requestHandler.toObject(stringContent); 382 String checkInResponse = checkIn(request, null); 383 LOG.debug("checkInResponse-->" + checkInResponse); 384 return checkInResponse; 385 } 386 387 388 @DELETE 389 @Path("{id}") 390 @Produces({MediaType.TEXT_XML}) 391 public String remove(@PathParam("id") String ids, @QueryParam("identifierType") String identifierType, 392 @QueryParam("operation") String operation) throws IOException { 393 LOG.debug("ids-->" + ids); 394 LOG.debug("identifier-->" + identifierType); 395 LOG.debug("operation-->" + operation); 396 Request request = null; 397 request = buildRequest(ids, identifierType, operation); 398 Response response = processDeleteRequest(request); 399 LOG.debug("response-->" + new ResponseHandler().toXML(response)); 400 return new ResponseHandler().toXML(response); 401 } 402 403 @DELETE 404 @Produces({MediaType.TEXT_XML}) 405 public String removeDocuments(@PathVariable("deleteRequest") String deleteRequest) throws IOException { 406 LOG.debug("request xml for delete-->" + deleteRequest); 407 RequestHandler requestHandler = new RequestHandler(); 408 Request request = requestHandler.toObject(deleteRequest); 409 Response response = processDeleteRequest(request); 410 String deleteResponse = new ResponseHandler().toXML(response); 411 LOG.debug("delete response -->" + deleteResponse); 412 413 return deleteResponse; 414 } 415 416 private Request buildRequest(String ids, String identifierType, String operation) { 417 String[] Id = ids.split(","); 418 List<String> idList = new ArrayList<String>(); 419 List<String> uuidList = new ArrayList<String>(); 420 Request request = new Request(); 421 for (int i = 0; i < Id.length; i++) { 422 idList.add(Id[i]); 423 LOG.debug("adding -->" + idList); 424 } 425 if ((!StringUtils.isBlank(identifierType)) && identifierType.equalsIgnoreCase("SCN") || identifierType 426 .equalsIgnoreCase("ISBN")) { 427 uuidList = ServiceLocator.getQueryService().getUUIDList(idList, identifierType); 428 } 429 else { 430 uuidList = idList; 431 } 432 request = buildRequest(uuidList, operation); 433 return request; 434 435 436 } 437 438 private Request buildRequest(List<String> uuidList, String operation) { 439 Request request = new Request(); 440 List<RequestDocument> requestDocumentList = new ArrayList<RequestDocument>(); 441 request.setUser("ole-khuntley"); 442 request.setOperation(operation); 443 for (int i = 0; i < uuidList.size(); i++) { 444 RequestDocument requestDocument = new RequestDocument(); 445 requestDocument.setUuid(uuidList.get(i)); 446 requestDocumentList.add(requestDocument); 447 } 448 request.setRequestDocuments(requestDocumentList); 449 return request; 450 } 451 452 protected Response processDeleteRequest(Request dsRequest) throws IOException { 453 DeleteManager deleteManager = new DeleteManager(); 454 List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>(); 455 requestDocuments = dsRequest.getRequestDocuments(); 456 Response response = null; 457 String uuidsNotInOle = null; 458 String serviceURL = null; 459 StringBuilder uuidsSB = null; 460 try { 461 if ((requestDocuments == null) || (requestDocuments.size() == 0)) { 462 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failed", 463 "Deletion failed: No documents specified for deletion."); 464 } 465 else { 466 // Build a csv of UUIDs of the documents to be deleted. 467 uuidsSB = new StringBuilder(); 468 for (RequestDocument requestDocument : requestDocuments) { 469 uuidsSB.append(requestDocument.getUuid()).append(","); 470 } 471 serviceURL = PropertyUtil.getPropertyUtil().getProperty("uuidCheckServiceURL"); 472 LOG.info(" uuidCheckServiceURL --------> " + serviceURL); 473 boolean verifiedWithOLE = true; 474 try { 475 // Use OLE web service to verify the existence of the UUIDs in OLE. 476 OleWebServiceProvider oleWebServiceProvider = new OleWebServiceProviderImpl(); 477 478 OleUuidCheckWebService oleUuidCheckWebService = (OleUuidCheckWebService) oleWebServiceProvider 479 .getService("org.kuali.ole.service.OleUuidCheckWebService", "oleUuidCheckWebService", 480 serviceURL); 481 482 uuidsNotInOle = oleUuidCheckWebService 483 .checkUuidExsistence(uuidsSB.substring(0, uuidsSB.length() - 1)); 484 } 485 catch (Exception e) { 486 verifiedWithOLE = false; 487 LOG.error("Check uuid call to OLE failed:", e); 488 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure", 489 "Deletion failed: Exception while connecting to OLE service to verify the existence of documents." 490 + e.getMessage()); 491 } 492 if (verifiedWithOLE) { 493 LOG.info("response uuids from OLE " + uuidsNotInOle); 494 // If the UUIDs do not exist in OLE, delete them from docstore. 495 if ((uuidsNotInOle != null) && (uuidsNotInOle.length() > 0)) { 496 String[] uuids = StringUtils.split(uuidsNotInOle, ","); 497 requestDocuments = new ArrayList<RequestDocument>(); 498 for (String id : uuids) { 499 RequestDocument requestDocument = new RequestDocument(); 500 requestDocument.setUuid(id); 501 requestDocuments.add(requestDocument); 502 } 503 dsRequest.setRequestDocuments(requestDocuments); 504 try { 505 response = deleteManager.deleteDocs(dsRequest); 506 } 507 catch (Exception e) { 508 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure", 509 "Deletion failed: Exception while deleting from docstore. " 510 + e.getMessage()); 511 } 512 } 513 else { 514 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure", 515 "Deletion failed: Documents exist in OLE database and cannot be deleted."); 516 } 517 } 518 } 519 } 520 catch (Exception e) { 521 LOG.error("delete operation failed:", e); 522 response = deleteManager.getResponse(dsRequest, requestDocuments, "Failure", "Failed : " + e.getMessage()); 523 } 524 return response; 525 } 526 527 public String checkIn(Request dsRequest, Response dsResponse) { 528 if (dsResponse == null) { 529 dsResponse = new Response(); 530 } 531 String checkInResponse = null; 532 List<String> latestVersion = new ArrayList<String>(); 533 try { 534 dsResponse.setOperation(dsRequest.getOperation()); 535 dsResponse.setUser(dsRequest.getUser()); 536 for (int i = 0; i < dsRequest.getRequestDocuments().size(); i++) { 537 RequestDocument requestDocument = dsRequest.getRequestDocuments().get(i); 538 requestDocument.setOperation(dsRequest.getOperation()); 539 latestVersion.add(documentStoreManager.updateRecord(requestDocument)); 540 ResponseDocument responseDocument = new ResponseDocument(); 541 responseDocument.setUuid(requestDocument.getUuid()); 542 responseDocument.setVersion(latestVersion.get(i)); 543 responseDocument.setId(requestDocument.getId()); 544 responseDocument.setCategory(requestDocument.getCategory()); 545 responseDocument.setType(requestDocument.getType()); 546 responseDocument.setFormat(requestDocument.getFormat()); 547 dsResponse.getDocuments().add(responseDocument); 548 } 549 550 Response response = ingestNIndexHandlerService.buildResponse(dsRequest); 551 checkInResponse = printResponse(response, dsRequest.getOperation(), "Success", "Documents checked in", 552 "Successfully checked in "); 553 } 554 /* try { 555 dsResponse = BeanLocator.getDocumentServiceImpl().process(dsRequest); 556 checkInResponse =(new ResponseHandler().toXML(dsResponse)); 557 }*/ 558 catch (Exception ex) { 559 Response response = ingestNIndexHandlerService.buildResponse(dsRequest); 560 String failOverMessage = ex.getMessage(); 561 failOverMessage = failOverMessage.replace("javax.jcr.ItemNotFoundException", "Document Not Found for uuid"); 562 checkInResponse = printResponse(response, dsRequest.getOperation(), "Failure", "Checkin failed", 563 failOverMessage); 564 } 565 return checkInResponse; 566 } 567 568 private String printResponse(Response response, String operation, String status, String message, 569 String statusMessage) { 570 String resp = null; 571 if (response == null) { 572 response = new Response(); 573 } 574 response.setOperation(operation); 575 response.setStatus(status); 576 response.setMessage(message); 577 response.setStatusMessage(statusMessage); 578 resp = new ResponseHandler().toXML(response); 579 return resp; 580 } 581 582 protected String checkOut(String uuid, String requestType) throws IOException { 583 584 String checkoutResponse = null; 585 try { 586 // HashMap<String, String> checkOutMap = null; 587 // checkOutMap = new HashMap<String, String>(); 588 // checkOutMap.put("uuid", uuid); 589 /* Request req = getRequest(uuid, "RestWebUser", "checkOut"); 590 Response dsResponse = BeanLocator.getDocumentServiceImpl().process(req); 591 if (dsResponse != null) { 592 for (ResponseDocument responseDocument : dsResponse.getDocuments()) { 593 if (responseDocument != null && responseDocument.getContent() != null) { 594 checkoutResponse = responseDocument.getContent().getContent(); 595 } 596 checkoutResponse = checkoutResponse + "\n"; 597 } 598 }*/ 599 checkoutResponse = documentStoreManager.checkOut(uuid, "RestWebUser", "restCheckOut"); 600 if (null == requestType || !requestType.equals("raw") && checkoutResponse != null) { 601 checkoutResponse = checkoutResponse.replaceAll("&", "&"); 602 checkoutResponse = checkoutResponse.replaceAll("< ", "< "); 603 } 604 } 605 catch (Exception ex) { 606 LOG.error("Error while performing checkout process", ex); 607 checkoutResponse = printResponse(null, "Check-out", "Failure", "Checkout failed", 608 "Error while performing checkout process"); 609 } 610 return checkoutResponse; 611 612 } 613 614 private Request getRequest(String uuid, String userId, String action) throws OleDocStoreException, OleException { 615 616 Node nodeByUUID = null; 617 Session session = null; 618 Request req = new Request(); 619 if (action == null || "".equalsIgnoreCase(action)) { 620 action = "checkOut"; 621 } 622 if (userId == null || "".equalsIgnoreCase(action)) { 623 userId = "RestWebUser"; 624 } 625 session = RepositoryManager.getRepositoryManager().getSession(userId, action); 626 String cat = null; 627 String type = null; 628 String format = null; 629 try { 630 NodeHandler nodeHandler = new NodeHandler(); 631 nodeByUUID = nodeHandler.getNodeByUUID(session, uuid); 632 String nodePath = nodeByUUID.getPath(); 633 String[] splitLine = nodePath.split("/"); 634 635 if (splitLine != null && splitLine.length >= 4) { 636 cat = splitLine[1]; 637 type = splitLine[2]; 638 format = splitLine[3]; 639 } 640 else { 641 throw new OleDocStoreException(" This is not a valid UUID "); 642 } 643 req.setOperation(action); 644 req.setUser(userId); 645 List<RequestDocument> reqDocList = new ArrayList<RequestDocument>(); 646 RequestDocument reqDoc = buildRequest(cat, type, format, uuid); 647 reqDocList.add(reqDoc); 648 req.setRequestDocuments(reqDocList); 649 } 650 catch (Exception e) { 651 LOG.info(e.getMessage(), e); 652 throw new OleDocStoreException(e); 653 } 654 finally { 655 session.logout(); 656 } 657 return req; 658 } 659 660 private RequestDocument buildRequest(String cat, String type, String format, String uuid) { 661 RequestDocument reqDoc = new RequestDocument(); 662 reqDoc.setCategory(cat); 663 reqDoc.setType(type); 664 reqDoc.setFormat(format); 665 reqDoc.setUuid(uuid); 666 return reqDoc; 667 668 } 669 670 private ArrayList<File> extractBagFilesFromRequest(@Context HttpServletRequest req, 671 @Context HttpServletResponse res) throws Exception { 672 File targetDir = null; 673 try { 674 File file = null; 675 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); 676 fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB 677 Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator(); 678 while (items.hasNext()) { 679 FileItem item = (FileItem) items.next(); 680 LOG.info("item Name = " + item.getName() + " ; content type = " + item.getContentType()); 681 file = new File(FileUtils.getTempDirectory(), item.getName()); 682 item.write(file); 683 } 684 targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null); 685 LOG.info("extractedBagFileLocation " + targetDir); 686 } 687 catch (IOException e) { 688 LOG.error("IOException", e); 689 sendResponseBag(res, e.getMessage(), "failure"); 690 } 691 catch (FormatHelper.UnknownFormatException unknownFormatException) { 692 LOG.error("unknownFormatException", unknownFormatException); 693 sendResponseBag(res, unknownFormatException.getMessage(), "failure"); 694 } 695 return compressUtils.getAllFilesList(targetDir); 696 } 697 698 /** 699 * Method to send response for a request in a zipped bag. 700 * 701 * @param res 702 * @param message 703 * @param status 704 * @return 705 */ 706 private void sendResponseBag(@Context HttpServletResponse res, String message, String status) { 707 Response response = new Response(); 708 response.setMessage(message); 709 response.setStatus(status); 710 sendResponseBag(res, response); 711 } 712 713 private void sendResponseBag(@Context HttpServletResponse res, @Context Response docStoreResponse) { 714 String responseXML = new ResponseHandler().toXML(docStoreResponse); 715 try { 716 File output = File.createTempFile("checkout.", ".output"); 717 FileUtils.deleteQuietly(output); 718 output.mkdirs(); 719 File file = new File(output + File.separator + "response.xml"); 720 Writer writer = null; 721 writer = new BufferedWriter(new FileWriter(file)); 722 writer.write(responseXML); 723 writer.close(); 724 File zipFile = compressUtils.createZippedBagFile(output); 725 res.setContentType("application/zip"); 726 sendResponseAsFile(res, zipFile); 727 zipFile.delete(); 728 } 729 catch (IOException e) { 730 LOG.error("IOException", e); 731 } 732 } 733 734 /** 735 * Method sends the response generated for the given request 736 * 737 * @param res 738 * @param file 739 * @throws IOException 740 */ 741 private void sendResponseAsFile(HttpServletResponse res, File file) throws IOException { 742 ServletOutputStream stream = res.getOutputStream(); 743 FileInputStream fos = new FileInputStream(file.getAbsolutePath()); 744 BufferedInputStream buf = new BufferedInputStream(fos); 745 int readBytes = 0; 746 while ((readBytes = buf.read()) != -1) { 747 stream.write(readBytes); 748 } 749 if (stream != null) { 750 stream.close(); 751 } 752 if (buf != null) { 753 buf.close(); 754 } 755 res.flushBuffer(); 756 } 757 758 private void sendUnavailableResponseString(HttpServletResponse response) { 759 try { 760 PrintWriter out = response.getWriter(); 761 out.println("The Requested Operation is not available"); 762 } 763 catch (IOException e) { 764 LOG.error("IOException", e); 765 } 766 } 767 768 }