View Javadoc
1   package org.kuali.ole.web;
2   
3   import com.google.common.io.CharStreams;
4   import gov.loc.repository.bagit.utilities.FormatHelper;
5   import org.apache.commons.fileupload.FileItem;
6   import org.apache.commons.fileupload.disk.DiskFileItemFactory;
7   import org.apache.commons.fileupload.servlet.ServletFileUpload;
8   import org.apache.commons.io.FileUtils;
9   import org.apache.commons.lang.StringUtils;
10  import org.kuali.ole.docstore.common.document.BibMarc;
11  import org.kuali.ole.docstore.common.document.License;
12  import org.kuali.ole.docstore.common.document.LicenseAttachment;
13  import org.kuali.ole.docstore.common.document.Licenses;
14  import org.kuali.ole.docstore.common.exception.BibImportResponse;
15  import org.kuali.ole.docstore.common.exception.BibImportResult;
16  import org.kuali.ole.docstore.common.exception.DocstoreException;
17  import org.kuali.ole.docstore.common.exception.DocstoreExceptionProcessor;
18  import org.kuali.ole.docstore.common.service.DocstoreService;
19  import org.kuali.ole.docstore.service.BeanLocator;
20  import org.kuali.ole.utility.CompressUtils;
21  import org.slf4j.Logger;
22  import org.slf4j.LoggerFactory;
23  
24  import javax.servlet.ServletException;
25  import javax.servlet.http.HttpServlet;
26  import javax.servlet.http.HttpServletRequest;
27  import javax.servlet.http.HttpServletResponse;
28  import java.io.File;
29  import java.io.IOException;
30  import java.io.PrintWriter;
31  import java.util.ArrayList;
32  import java.util.Iterator;
33  import java.util.List;
34  
35  /**
36   * Created with IntelliJ IDEA.
37   * User: sambasivam
38   * Date: 2/27/14
39   * Time: 6:13 PM
40   * To change this template use File | Settings | File Templates.
41   */
42  public class LicenseRestServlet extends HttpServlet {
43  
44      private static final Logger LOG = LoggerFactory.getLogger(LicenseRestServlet.class);
45      private CompressUtils compressUtils = new CompressUtils();
46      DocstoreService ds = BeanLocator.getDocstoreService();
47      private static String responseUrl = "documentrest/license/";
48      private String extractFilePath = FileUtils.getTempDirectoryPath() + File.separator + "bagit";
49  
50      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
51  
52          PrintWriter out = resp.getWriter();
53          resp.setContentType("text/xml;charset=UTF-8");
54          String result = "";
55          Licenses licenses = null;
56          try {
57              ArrayList<File> files = extractBagFilesFromRequest(req, resp);
58              for(File file : files) {
59                  if (file.getName().equalsIgnoreCase("licenses.xml")) {
60                      String licensesXml = FileUtils.readFileToString(file);
61                      licenses = (Licenses) Licenses.deserialize(licensesXml);
62                      for(License license : licenses.getLicenses()) {
63                          if(!license.getFormat().equals("onixpl")) {
64                              LicenseAttachment licenseAttachment = (LicenseAttachment) license;
65                              licenseAttachment.setFilePath(file.getParent());
66                          }
67                      }
68                  }
69              }
70              ds.createLicenses(licenses);
71              compressUtils.deleteFiles(files);
72              File extractFile = new File(extractFilePath);
73              extractFile.delete();
74          } catch (Exception e) {
75              LOG.error("EXception : ", e);
76          }
77          StringBuffer ids = new StringBuffer();
78          for(License license : licenses.getLicenses()) {
79              ids.append(license.getId());
80              ids.append("/");
81          }
82  
83          out.write(responseUrl+ ids.substring(0, (ids.length()-1)));
84      }
85  
86      @Override
87      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
88          PrintWriter out = resp.getWriter();
89          resp.setContentType("text/xml;charset=UTF-8");
90          String result = "";
91          try {
92             result = retrieveLicense(req);
93              out.print(result);
94          } catch (DocstoreException de) {
95              LOG.error("Exception :", de);
96              out.print(DocstoreExceptionProcessor.toXml(de));
97          } catch (Exception e) {
98              LOG.error("Exception :", e);
99              out.print(e);
100         }
101     }
102 
103     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
104         PrintWriter out = resp.getWriter();
105         resp.setContentType("text/xml;charset=UTF-8");
106         String result = "";
107 
108         try {
109             result = deleteLicense(req);
110             out.print(result);
111         } catch (DocstoreException de) {
112             LOG.error("Exception :", de);
113             out.print(DocstoreExceptionProcessor.toXml(de));
114         } catch (Exception e) {
115             LOG.error("Exception :", e);
116             out.print(e);
117         }
118     }
119 
120     private String deleteLicense(HttpServletRequest req) {
121         DocstoreService ds = BeanLocator.getDocstoreService();
122         String licenseId = getIdFromPathInfo(req.getPathInfo());
123         ds.deleteLicense(licenseId);
124         return "Success";
125     }
126 
127 
128 
129     private String retrieveLicense(HttpServletRequest req) {
130         DocstoreService ds = BeanLocator.getDocstoreService();
131         String id = getIdFromPathInfo(req.getPathInfo());
132         if (id.contains("licenseIds")) {
133             String[] splitString = id.split("=");
134             String[] licenseIds = splitString[1].split(",");
135             List<String> licenseIdList = new ArrayList<String>();
136             for (String bibId : licenseIds) {
137                 licenseIdList.add(bibId);
138             }
139             Licenses licenses = null;
140             licenses = ds.retrieveLicenses(licenseIdList);
141             return Licenses.serialize(licenses);
142 
143         } else {
144             License license = ds.retrieveLicense(id);
145             return license.serialize(license);
146         }
147 
148     }
149 
150 
151     protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
152 
153         PrintWriter out = resp.getWriter();
154         resp.setContentType("text/xml;charset=UTF-8");
155         String result = "";
156         try {
157             if (req.getPathInfo().startsWith("/trees")) {
158                 result = updateLicenses(req);
159             } else {
160                 result = updateLicense(req);
161             }
162             out.print(result);
163         } catch (DocstoreException de) {
164             LOG.error("Exception :", de);
165             out.print(DocstoreExceptionProcessor.toXml(de));
166         } catch (Exception e) {
167             LOG.error("Exception :", e);
168             out.print(e);
169         }
170     }
171 
172     private String updateLicense(HttpServletRequest req) throws IOException {
173         DocstoreService ds = BeanLocator.getDocstoreService();
174         String requestBody = CharStreams.toString(req.getReader());
175 
176         License license = new License();
177         License licenseObj = (License) license.deserialize(requestBody);
178         ds.updateLicense(licenseObj);
179         return responseUrl + licenseObj.getId();
180 
181     }
182 
183     private String updateLicenses(HttpServletRequest req) throws IOException {
184         DocstoreService ds = BeanLocator.getDocstoreService();
185         String requestBody = CharStreams.toString(req.getReader());
186         Licenses licenses = (Licenses) Licenses.deserialize(requestBody);
187         ds.updateLicenses(licenses);
188 
189         BibImportResponse bibImportResponse = new BibImportResponse();
190         for (int i = 0; i < licenses.getLicenses().size(); i++) {
191             BibImportResult bibImportResult = new BibImportResult();
192             if (licenses.getLicenses().get(i).getId() != null) {
193                 bibImportResult.setMessage("success");
194             } else {
195                 bibImportResult.setId(String.valueOf(i));
196             }
197             bibImportResponse.getBibImportResults().add(bibImportResult);
198         }
199         return BibImportResponse.serialize(bibImportResponse);
200     }
201 
202 
203     private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res)
204             throws Exception {
205         File targetDir = null;
206         try {
207             File file = null;
208             DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
209             fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
210             Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
211             while (items.hasNext()) {
212                 FileItem item = (FileItem) items.next();
213                 file = new File(FileUtils.getTempDirectory(), item.getName());
214                 item.write(file);
215             }
216             targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), extractFilePath);
217             LOG.info("extractedBagFileLocation " + targetDir);
218         } catch (IOException e) {
219             LOG.error("IOException", e);
220 //            sendResponseBag(res, e.getMessage(), "failure");
221         } catch (FormatHelper.UnknownFormatException unknownFormatException) {
222             LOG.error("unknownFormatException", unknownFormatException);
223 //            sendResponseBag(res, unknownFormatException.getMessage(), "failure");
224         }
225         return compressUtils.getAllFilesList(targetDir);
226     }
227 
228     private String getIdFromPathInfo(String pathInfo) {
229         String id = "";
230         if (StringUtils.isNotEmpty(pathInfo)) {
231             int length = pathInfo.length();
232             if (pathInfo.endsWith("/")) {
233                 pathInfo = pathInfo.substring(0, length - 1);
234             }
235             id = pathInfo.substring(pathInfo.lastIndexOf("/") + 1);
236         }
237         return id;
238     }
239 
240 }