View Javadoc
1   package org.kuali.ole.docstore.engine.service.rest;
2   
3   import com.google.common.io.CharStreams;
4   import org.apache.commons.lang.StringUtils;
5   import org.kuali.ole.docstore.common.document.*;
6   import org.kuali.ole.docstore.common.document.config.DocumentSearchConfig;
7   import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecords;
8   import org.kuali.ole.docstore.common.document.content.bib.marc.OrderBibMarcRecord;
9   import org.kuali.ole.docstore.common.document.content.bib.marc.xstream.BibMarcRecordProcessor;
10  import org.kuali.ole.docstore.common.document.ids.BibId;
11  import org.kuali.ole.docstore.common.document.ids.BibIds;
12  import org.kuali.ole.docstore.common.document.ids.HoldingsId;
13  import org.kuali.ole.docstore.common.exception.*;
14  import org.kuali.ole.docstore.common.find.FindParams;
15  import org.kuali.ole.docstore.common.service.DocstoreService;
16  import org.kuali.ole.docstore.service.BeanLocator;
17  import org.slf4j.Logger;
18  import org.slf4j.LoggerFactory;
19  import org.kuali.ole.docstore.common.exception.DocstoreExceptionProcessor;
20  
21  import javax.servlet.ServletException;
22  import javax.servlet.http.HttpServlet;
23  import javax.servlet.http.HttpServletRequest;
24  import javax.servlet.http.HttpServletResponse;
25  import java.io.*;
26  import java.util.ArrayList;
27  import java.util.HashMap;
28  import java.util.List;
29  import java.util.Map;
30  
31  /**
32   * Created with IntelliJ IDEA.
33   * User: mjagan
34   * Date: 3/2/14
35   * Time: 7:28 PM
36   * To change this template use File | Settings | File Templates.
37   */
38  public class BibRestServlet extends HttpServlet {
39      private static final Logger LOG = LoggerFactory.getLogger(BibRestServlet.class);
40      private static String responseUrl = "documentrest/bib/doc/";
41      private static String responseTreeUrl = "documentrest/bib/doc/tree/";
42      public static BibMarcRecordProcessor bibMarcRecordProcessor = new BibMarcRecordProcessor();
43      @Override
44      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
45          PrintWriter out = resp.getWriter();
46          resp.setContentType("application/xml;charset=UTF-8");
47          String result = "";
48          try {
49              if (req.getPathInfo() != null && req.getPathInfo().startsWith("/reload")) {
50                  DocumentSearchConfig.getDocumentSearchConfig();
51                  DocumentSearchConfig.reloadDocumentConfig();
52              } else if (req.getPathInfo() != null && req.getPathInfo().contains("doc")) {
53                  if (req.getPathInfo().startsWith("/doc/trees")) {
54                      result = retrieveBibTrees(req);
55                  } else if (req.getPathInfo().startsWith("/doc/tree")) {
56                      result = retrieveBibTree(req);
57                  } else {
58                      result = retrieveBib(req);
59                  }
60              } else {
61                  result = retrieveBibContent(req);
62              }
63              out.print(result);
64          } catch (DocstoreException de) {
65              LOG.error("Docstore Exception :", de);
66              out.print(DocstoreExceptionProcessor.toXml(de));
67          } catch (Exception e) {
68              LOG.error("Exception :", e);
69              out.print(e);
70          }
71      }
72  
73      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
74  
75          PrintWriter out = resp.getWriter();
76          resp.setContentType("application/xml;charset=UTF-8");
77          String result = "";
78          try {
79              if (req.getPathInfo().startsWith("/tree/doc/find")) {
80                  result = findBibTree(req);
81              } else if (req.getPathInfo().startsWith("/doc/find")) {
82                  result = findBib(req);
83              } else if (req.getPathInfo().startsWith("/doc/trees")) {
84                  result = createBibTrees(req);
85              } else if (req.getPathInfo().startsWith("/doc/tree")) {
86                  result = createBibTree(req);
87              } else if (req.getPathInfo().contains("/transfer")) {
88                  result = transferHoldings(req);
89              } else {
90                  result = createBib(req);
91              }
92              out.print(result);
93          } catch (DocstoreException de) {
94              LOG.error("Exception :", de);
95              out.print(DocstoreExceptionProcessor.toXml(de));
96          } catch (Exception e) {
97              LOG.error("Exception :", e);
98              out.print(e);
99          }
100     }
101 
102 
103     protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
104 
105         PrintWriter out = resp.getWriter();
106         resp.setContentType("application/xml;charset=UTF-8");
107         String result = "";
108         try {
109             if (req.getPathInfo().startsWith("/doc/trees")) {
110                 result = updateBibs(req);
111             } else {
112                 result = updateBib(req);
113             }
114             out.print(result);
115         } catch (DocstoreException de) {
116             LOG.error("Exception :", de);
117             out.print(DocstoreExceptionProcessor.toXml(de));
118         } catch (Exception e) {
119             LOG.error("Exception :", e);
120             out.print(e);
121         }
122     }
123 
124     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
125         PrintWriter out = resp.getWriter();
126         resp.setContentType("application/xml;charset=UTF-8");
127         String result = "";
128 
129         try {
130             result = deleteBibs(req);
131             out.print(result);
132         } catch (DocstoreException de) {
133             LOG.error("Exception :", de);
134             out.print(DocstoreExceptionProcessor.toXml(de));
135         } catch (Exception e) {
136             LOG.error("Exception :", e);
137             out.print(e);
138         }
139     }
140 
141     private String deleteBib(HttpServletRequest req) {
142         DocstoreService ds = BeanLocator.getDocstoreService();
143         String bibId = getIdFromPathInfo(req.getPathInfo());
144         ds.deleteBib(bibId);
145         return "Success";
146     }
147 
148     private String deleteBibs(HttpServletRequest req) {
149         DocstoreService ds = BeanLocator.getDocstoreService();
150         Map params = req.getParameterMap();
151         String[] bibIds = (String[]) params.get("bibId");
152         List<String> bibIdList = new ArrayList<String>();
153         for (String bibId : bibIds) {
154             bibIdList.add(bibId);
155         }
156             ds.deleteBibs(bibIdList);
157         return "Success";
158     }
159 
160     private String getIdFromPathInfo(String pathInfo) {
161         String id = "";
162         if (StringUtils.isNotEmpty(pathInfo)) {
163             int length = pathInfo.length();
164             if (pathInfo.endsWith("/")) {
165                 pathInfo = pathInfo.substring(0, length - 1);
166             }
167             id = pathInfo.substring(pathInfo.lastIndexOf("/") + 1);
168         }
169         return id;
170     }
171 
172     private String findBibTree(HttpServletRequest req) throws IOException {
173         DocstoreService ds = BeanLocator.getDocstoreService();
174         String requestBody = CharStreams.toString(req.getReader());
175         BibTree bibTree = new BibTree();
176         FindParams findParams = new FindParams();
177         findParams = (FindParams) findParams.deserialize(requestBody);
178         HashMap<String, String> hashMap = new HashMap();
179         List<FindParams.Map.Entry> entries = findParams.getMap().getEntry();
180         for (FindParams.Map.Entry entry : entries) {
181             hashMap.put(entry.getKey(), entry.getValue());
182         }
183         bibTree = ds.findBibTree(hashMap);
184         return bibTree.serialize(bibTree);
185 
186     }
187 
188     private String findBib(HttpServletRequest req) throws IOException {
189         DocstoreService ds = BeanLocator.getDocstoreService();
190         String requestBody = CharStreams.toString(req.getReader());
191         Bib bib = new BibMarc();
192         FindParams findParams = new FindParams();
193         findParams = (FindParams) findParams.deserialize(requestBody);
194         HashMap<String, String> hashMap = new HashMap();
195         List<FindParams.Map.Entry> entries = findParams.getMap().getEntry();
196         for (FindParams.Map.Entry entry : entries) {
197             hashMap.put(entry.getKey(), entry.getValue());
198         }
199         bib = ds.findBib(hashMap);
200         return (bib.serialize(bib));
201     }
202 
203     private String createBib(HttpServletRequest req) throws IOException {
204         DocstoreService ds = BeanLocator.getDocstoreService();
205         String requestBody = CharStreams.toString(req.getReader());
206         Bib bib = new BibMarc();
207         Bib bibObj = (Bib) bib.deserialize(requestBody);
208         ds.createBib(bibObj);
209         String responseStr = responseUrl + bibObj.getId();
210         return responseStr;
211     }
212 
213     private String updateBib(HttpServletRequest req) throws IOException {
214         DocstoreService ds = BeanLocator.getDocstoreService();
215         String requestBody = CharStreams.toString(req.getReader());
216 
217         Bib bib = new BibMarc();
218         Bib bibObj = (Bib) bib.deserialize(requestBody);
219         ds.updateBib(bibObj);
220         return responseUrl + bibObj.getId();
221     }
222 
223     private String updateBibs(HttpServletRequest req) throws IOException {
224         DocstoreService ds = BeanLocator.getDocstoreService();
225         String requestBody = CharStreams.toString(req.getReader());
226         Bibs bibs = (Bibs) Bibs.deserialize(requestBody);
227         ds.updateBibs(bibs.getBibs());
228 
229         BibImportResponse bibImportResponse = new BibImportResponse();
230         for (int i = 0; i < bibs.getBibs().size(); i++) {
231             BibImportResult bibImportResult = new BibImportResult();
232             OrderBibMarcRecord orderBibMarcRecord = new OrderBibMarcRecord();
233             bibImportResult.setOrderBibMarcRecord(orderBibMarcRecord);
234             if (bibs.getBibs().get(i).getId() != null) {
235                 bibImportResult.setMessage("success");
236                 BibMarcRecords bibMarcRecords = bibMarcRecordProcessor.fromXML(bibs.getBibs().get(i).getContent());
237                 orderBibMarcRecord.setBibMarcRecord(bibMarcRecords.getRecords().get(0));
238                 orderBibMarcRecord.setFailureReason("success");
239             } else {
240                 bibImportResult.setId(String.valueOf(i));
241                 orderBibMarcRecord.setFailureReason("failure");
242             }
243             bibImportResponse.getBibImportResults().add(bibImportResult);
244 
245             BibId bibId1 = new BibId();
246             bibId1.setId(bibs.getBibs().get(i).getId());
247             orderBibMarcRecord.setBibId(bibId1);
248 
249         }
250         return BibImportResponse.serialize(bibImportResponse);
251     }
252 
253     private String retrieveBib(HttpServletRequest req) {
254         DocstoreService ds = BeanLocator.getDocstoreService();
255         Map params = req.getParameterMap();
256         String[] bibIds = (String[]) params.get("bibId");
257         List<String> bibIdList = new ArrayList<String>();
258 
259         for (String bibId : bibIds) {
260             bibIdList.add(bibId);
261         }
262         List<Bib> bibs = null;
263         bibs = ds.retrieveBibs(bibIdList);
264         if (bibs.size() == 1) {
265             Bib bib = new Bib();
266             return bib.serialize(bibs.get(0));
267         }
268         Bibs bibsObj = new Bibs();
269         bibsObj.getBibs().addAll(bibs);
270         return Bibs.serialize(bibsObj);
271     }
272 
273     private String retrieveBibContent(HttpServletRequest req) {
274         DocstoreService ds = BeanLocator.getDocstoreService();
275         StringBuffer contentBuffer = new StringBuffer();
276         BibMarcRecords bibMarcRecords = new BibMarcRecords();
277         BibMarcRecordProcessor bibMarcRecordProcessor = new BibMarcRecordProcessor();
278         List<String> bibIdList = new ArrayList<String>();
279         Map params = req.getParameterMap();
280         String[] queryVariables = (String[]) params.get("bibId");
281         if (queryVariables.length > 0) {
282             for (String bibId : queryVariables) {
283                 bibIdList.add(bibId);
284             }
285         }
286         if (bibIdList != null && bibIdList.size() > 1) {
287             List<Bib> bibs = ds.retrieveBibs(bibIdList);
288             for (Bib bibRecord : bibs) {
289                 bibMarcRecords.getRecords().addAll(bibMarcRecordProcessor.fromXML(bibRecord.getContent()).getRecords());
290             }
291             if (bibMarcRecords != null) {
292                 contentBuffer.append(bibMarcRecordProcessor.generateXML(bibMarcRecords.getRecords()));
293             }
294         } else if (bibIdList != null && bibIdList.size() == 1) {
295             Bib bib = ds.retrieveBib(bibIdList.get(0));
296             bibMarcRecords = bibMarcRecordProcessor.fromXML(bib.getContent());
297             contentBuffer.append(bibMarcRecordProcessor.generateXML(bibMarcRecords.getRecords()));
298         }
299         return contentBuffer.toString();
300     }
301 
302     private String retrieveBibTree(HttpServletRequest req) {
303         DocstoreService ds = BeanLocator.getDocstoreService();
304         String id = req.getParameter("bibId");
305         BibTree bibTree = ds.retrieveBibTree(id);
306         return bibTree.serialize(bibTree);
307     }
308 
309     private String createBibTree(HttpServletRequest req) throws IOException {
310         DocstoreService ds = BeanLocator.getDocstoreService();
311         String requestBody = CharStreams.toString(req.getReader());
312         BibTree bibTree = new BibTree();
313             bibTree = (BibTree) bibTree.deserialize(requestBody);
314             ds.createBibTree(bibTree);
315         return responseTreeUrl + bibTree.getBib().getId();
316     }
317 
318     private String createBibTrees(HttpServletRequest req) throws IOException {
319         DocstoreService ds = BeanLocator.getDocstoreService();
320         String requestBody = CharStreams.toString(req.getReader());
321         BibTrees bibTrees = new BibTrees();
322         bibTrees = (BibTrees) bibTrees.deserialize(requestBody);
323         ds.createBibTrees(bibTrees);
324         BibImportResponse bibImportResponse = new BibImportResponse();
325 //        BibIds bibIds = new BibIds();
326 //        bibImportResponse.setBibIds(bibIds);
327 
328         for (int i = 0; i < bibTrees.getBibTrees().size(); i++) {
329 
330             BibImportResult bibImportResult = new BibImportResult();
331             OrderBibMarcRecord orderBibMarcRecord = new OrderBibMarcRecord();
332             bibImportResult.setOrderBibMarcRecord(orderBibMarcRecord);
333 
334             String bibId = bibTrees.getBibTrees().get(i).getBib().getId();
335             if (bibTrees.getBibTrees().get(i).getBib().getId() != null) {
336                 bibImportResult.setMessage("success");
337                 BibMarcRecords bibMarcRecords = bibMarcRecordProcessor.fromXML(bibTrees.getBibTrees().get(i).getBib().getContent());
338                 orderBibMarcRecord.setBibMarcRecord(bibMarcRecords.getRecords().get(0));
339                 orderBibMarcRecord.setFailureReason("success");
340 
341             } else {
342                 bibImportResult.setId(String.valueOf(i));
343             }
344             bibImportResponse.getBibImportResults().add(bibImportResult);
345 
346             BibId bibIdObj = new BibId();
347             bibIdObj.setId(bibId);
348             orderBibMarcRecord.setBibId(bibIdObj);
349 
350             for(HoldingsTree holdingsTree : (bibTrees.getBibTrees().get(i).getHoldingsTrees())) {
351 
352                 HoldingsId holdingsId = new HoldingsId();
353                 holdingsId.setId(holdingsTree.getHoldings().getId());
354                 bibIdObj.getHoldingsIds().add(holdingsId);
355                 for(Item item : holdingsTree.getItems()) {
356                     holdingsId.getItems().add(item.getId());
357                 }
358             }
359         }
360         return BibImportResponse.serialize(bibImportResponse);
361     }
362 
363     private String transferHoldings(HttpServletRequest req) {
364         DocstoreService ds = BeanLocator.getDocstoreService();
365         //String[] transferStr = req.getPathInfo().split("transfer");
366         String bibId = req.getPathInfo().split("/")[2];
367         Map params = req.getParameterMap();
368         String[] splitHoldingIds = (String[]) params.get("holdingsId");
369         List<String> holdingsIds = new ArrayList<String>();
370         for (String holdingsId : splitHoldingIds) {
371             holdingsIds.add(holdingsId);
372         }
373         ds.transferHoldings(holdingsIds, bibId);
374         return "Success";
375     }
376 
377     private String retrieveBibTrees(HttpServletRequest req) {
378         DocstoreService ds = BeanLocator.getDocstoreService();
379         List<String> bibIdList = new ArrayList<String>();
380         Map params = req.getParameterMap();
381         String[] bibIds = (String[]) params.get("bibId");
382         for (String bibId : bibIds) {
383             bibIdList.add(bibId);
384         }
385         return BibTrees.serialize(ds.retrieveBibTrees(bibIdList));
386     }
387 
388 }