001package org.kuali.ole.docstore.common.client;
002
003import org.apache.commons.io.FileUtils;
004import org.apache.commons.io.IOUtils;
005import org.apache.http.HttpEntity;
006import org.apache.http.HttpResponse;
007import org.apache.http.ProtocolVersion;
008import org.apache.http.StatusLine;
009import org.apache.http.client.HttpClient;
010import org.apache.http.client.methods.*;
011import org.apache.http.entity.StringEntity;
012import org.apache.http.entity.mime.Header;
013import org.apache.http.entity.mime.MultipartEntity;
014import org.apache.http.entity.mime.content.FileBody;
015import org.apache.http.impl.client.DefaultHttpClient;
016import org.apache.http.message.BasicHttpResponse;
017import org.apache.http.message.BasicStatusLine;
018import org.apache.http.util.EntityUtils;
019import org.kuali.ole.docstore.common.document.*;
020import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecords;
021import org.kuali.ole.docstore.common.document.content.bib.marc.xstream.BibMarcRecordProcessor;
022
023import org.kuali.ole.docstore.common.exception.DocstoreExceptionProcessor;
024import org.kuali.ole.docstore.common.find.FindParams;
025import org.kuali.ole.docstore.common.search.BrowseParams;
026import org.kuali.ole.docstore.common.search.SearchParams;
027import org.kuali.ole.docstore.common.search.SearchResponse;
028import org.kuali.rice.core.api.config.property.ConfigContext;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031
032import java.io.*;
033import java.net.HttpURLConnection;
034import java.net.URL;
035import java.util.ArrayList;
036import java.util.HashMap;
037import java.util.List;
038import java.util.Map;
039import java.util.zip.ZipEntry;
040import java.util.zip.ZipOutputStream;
041
042
043/**
044 * Created with IntelliJ IDEA.
045 * User: jayabharathreddy
046 * Date: 12/17/13
047 * Time: 5:04 PM
048 * To change this template use File | Settings | File Templates.
049 */
050
051
052public class DocstoreRestClient implements DocstoreClient {
053
054    //    static String DOCSTORE_URL = "http://localhost:8080/oledocstore/documentrest/";
055    private static String DOCSTORE_URL =getDocstoreUrl();
056    private static String BIB_URL = "bib/doc/";
057    private static String RELOAD_URL = "config/reload";
058    private static String BIB_CONTENT_URL = "bib/";
059    private static String SEARCH_URL = "search/";
060    private static String HOLDINGS_URL = "holdings/doc/";
061    private static String HOLDINGS_DOCS_URL = "holdings/docs/";
062    private static String ITEMS_URL = "item/doc/";
063    private static String ITEMS_DOCS_URL = "item/docs/";
064    private static String ITEM_MAP_URL = "item/doc/map";
065    private static String ITEM_CONTENT_URL = "item/";
066    private static String HOLDINGS_TREE_URL = "holdings/doc/tree/";
067    private static String HOLDINGS_TREES_URL = "holdings/doc/trees/";
068    private static String HOLDINGS_TREES_CONTENT_URL = "holdings/tree/";
069    private static String BIB_TREE_URL = "bib/doc/tree/";
070    private static String BIB_TREES_URL = "bib/doc/trees/";
071    private static String FIND_URL = "/doc/find";
072    private static String BROWSE_URL = "browse/";
073    private static String BOUND_URL = "/bound";
074    private static String ANALYTIC_URL = "/analytic";
075    private static String BREAK_ANALYTIC_URL = "/breakAnalytic";
076    private static String TRANSFER_URL = "/transfer/";
077    private static String LICENSES_URL = "license/";
078    private static String LICENSES_TREES_URL = "license/trees/";
079    private static String BULK_UPDATE = "/bulkUpdate";
080    private static String PROCESS_BIB_TREES = "bib/batch";
081
082    private Logger logger = LoggerFactory.getLogger(DocstoreRestClient.class);
083
084    public static String getDocstoreUrl() {
085        if(ConfigContext.getCurrentContextConfig() != null){
086            DOCSTORE_URL = ConfigContext.getCurrentContextConfig().getProperty("ole.docstore.Documentrest.url");
087        }
088        return DOCSTORE_URL;
089    }
090
091    public static void setDocstoreUrl(String url) {
092        DOCSTORE_URL = url;
093    }
094
095    @Override
096    public void createBib(Bib bib) {
097        String requestBody = bib.serialize(bib);
098        RestResponse restResponse = postRequest(requestBody, BIB_URL);
099        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
100            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
101                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
102            }
103            String[] responseString = restResponse.getResponseBody().split("/");
104            if (responseString.length == 4) {
105                bib.setId(responseString[3]);
106            }
107        }
108    }
109
110    @Override
111    public void createHoldings(Holdings holdings) {
112        String requestBody = holdings.serialize(holdings);
113        RestResponse restResponse = postRequest(requestBody, HOLDINGS_URL);
114        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
115            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
116                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
117            }
118            String[] responseString = restResponse.getResponseBody().split("/");
119            if (responseString.length == 4) {
120                holdings.setId(responseString[3]);
121            }
122        }
123    }
124
125    @Override
126    public void createItem(Item item) {
127        String requestBody = item.serialize(item);
128        RestResponse restResponse = postRequest(requestBody, ITEMS_URL);
129        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
130            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
131                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
132            }
133            String[] responseString = restResponse.getResponseBody().split("/");
134            if (responseString.length == 4) {
135                item.setId(responseString[3]);
136            }
137        }
138    }
139
140    @Override
141    public void createHoldingsTree(HoldingsTree holdingsTree) {
142        String requestBody = holdingsTree.serialize(holdingsTree);
143        RestResponse restResponse = postRequest(requestBody, HOLDINGS_TREE_URL);
144        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
145            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
146                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
147            }
148            String[] responseString = restResponse.getResponseBody().split("/");
149            holdingsTree.getHoldings().setId(responseString[4]);
150            if (responseString.length > 4) {
151                int j = 0;
152                for (int i = 5; i < responseString.length; i++) {
153                    if (responseString[i] != null) {
154                        holdingsTree.getItems().get(j).setId(responseString[i]);
155                    }
156                    j++;
157                }
158            }
159        }
160    }
161
162
163
164    @Override
165    public void createBibTree(BibTree bibTree) {
166        String requestBody = bibTree.serialize(bibTree);
167        RestResponse restResponse = postRequest(requestBody, BIB_TREE_URL);
168        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
169            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
170                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
171            }
172            String[] responseString = restResponse.getResponseBody().split("/");
173            if (responseString.length == 5) {
174                bibTree.getBib().setId(responseString[4]);
175            }
176        }
177    }
178
179
180
181    @Override
182    public BibTrees processBibTrees(BibTrees bibTrees) {
183        String requestBody = bibTrees.serialize(bibTrees);
184        RestResponse restResponse = postRequest(requestBody, PROCESS_BIB_TREES);
185        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
186            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
187                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
188            } else {
189                bibTrees = (BibTrees) BibTrees.deserialize(restResponse.getResponseBody());
190            }
191        }
192        return bibTrees;
193    }
194
195    @Override
196    public List<Bib> retrieveBibs(List<String> bibIds) {
197//        String bibIdSb = buildIds(bibIds, "bibIds=");
198        RestResponse restResponse = getBibResponse(buildQueryString(bibIds, "bibId"), BIB_URL);
199        Bibs bibsObj = new Bibs();
200        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
201            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
202                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
203            } else {
204                if (bibIds.size() == 1) {
205                    Bib bib = new Bib();
206                    bibsObj.getBibs().add((Bib) bib.deserialize(restResponse.getResponseBody()));
207                    return bibsObj.getBibs();
208                }
209                bibsObj = (Bibs) Bibs.deserialize(restResponse.getResponseBody());
210
211            }
212        }
213        return bibsObj.getBibs();
214
215    }
216
217    @Override
218    public List<Item> retrieveItems(List<String> itemIds) {
219        RestResponse restResponse = getRequest(buildQueryString(itemIds, "itemId"), ITEMS_URL);
220        Items itemsObj = new Items();
221        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
222            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
223                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
224            } else {
225                if (itemIds.size() == 1) {
226                    Item item = new Item();
227                    itemsObj.getItems().add((Item) item.deserialize(restResponse.getResponseBody()));
228                    return itemsObj.getItems();
229                }
230                itemsObj = (Items) Items.deserialize(restResponse.getResponseBody());
231            }
232        }
233        return itemsObj.getItems();
234    }
235
236    @Override
237    public HashMap<String, Item> retrieveItemMap(List<String> itemIds) {
238        RestResponse restResponse = getRequest(buildQueryString(itemIds, "itemId"), ITEM_MAP_URL);
239        ItemMap itemsObj = new ItemMap();
240        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
241            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
242                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
243            } else {
244                itemsObj = (ItemMap) ItemMap.deserialize(restResponse.getResponseBody());
245            }
246        }
247        return itemsObj.getItemMap();
248    }
249
250    @Override
251    public void createLicenses(Licenses licenses) {
252
253        File bagitFile = null;
254        try {
255            bagitFile = createBagItfile(licenses);
256        } catch (IOException e) {
257            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
258        }
259        RestResponse restResponse = postMultiPartRequest(bagitFile);
260        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
261            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
262                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
263            }
264            String[] responseString = restResponse.getResponseBody().split("/");
265            int idPos = 2;
266            for (License license : licenses.getLicenses()) {
267                license.setId(responseString[idPos]);
268                idPos += 1;
269            }
270        }
271        bagitFile.delete();
272    }
273
274    @Override
275    public License retrieveLicense(String id) {
276        RestResponse restResponse = getRequest(id, LICENSES_URL);
277        License license = new License();
278        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
279            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
280                logger.info(" rest response " + restResponse.getResponseBody());
281                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
282            } else {
283                license = (License) license.deserialize(restResponse.getResponseBody());
284            }
285        }
286        return license;
287
288    }
289
290    private RestResponse postMultiPartRequest(File bagitFile) {
291        HttpClient httpclient = new DefaultHttpClient();
292        FileBody uploadFilePart = new FileBody(bagitFile);
293        MultipartEntity reqEntity = new MultipartEntity();
294        reqEntity.addPart("upload-file", uploadFilePart);
295        HttpPost httpPost = new HttpPost(DOCSTORE_URL + LICENSES_URL);
296        httpPost.setEntity(reqEntity);
297        httpPost.addHeader("multipart/form-data", "text/xml");
298        RestResponse restResponse = new RestResponse();
299        try {
300            EntityUtils.consume(reqEntity);
301            HttpResponse response = httpclient.execute(httpPost);
302            restResponse.setResponse(response);
303            restResponse.setResponseBody(getEncodeEntityValue(response.getEntity()));
304
305        } catch (Exception e) {
306            e.printStackTrace();
307        }
308
309        return restResponse;
310    }
311
312    private File createBagItfile(Licenses licenses) throws IOException {
313        File bagitFolder = new File(FileUtils.getTempDirectoryPath() + File.separator + "bagit");
314        String licensesXml = licenses.serialize(licenses);
315        File licensesXmlFile = new File(bagitFolder + File.separator + "licenses.xml");
316        FileUtils.writeStringToFile(licensesXmlFile, licensesXml);
317        for (License license : licenses.getLicenses()) {
318            if (license instanceof LicenseAttachment) {
319                LicenseAttachment licenseAttachment = (LicenseAttachment) license;
320                File contentFile = new File(licenseAttachment.getFilePath() + File.separator + licenseAttachment.getFileName());
321                FileUtils.copyFileToDirectory(contentFile, bagitFolder);
322            }
323        }
324
325        File bagitFile = createZipFile(bagitFolder);
326        deleteFiles(bagitFile.listFiles());
327        bagitFolder.delete();
328        return bagitFile;
329    }
330
331    @Override
332    public Licenses retrieveLicenses(List<String> ids) {
333        String licenseIds = buildIds(ids, "licenseIds=");
334        RestResponse restResponse = getRequest(licenseIds, LICENSES_URL);
335        Licenses licenses = new Licenses();
336        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
337            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
338                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
339            } else {
340                licenses = (Licenses) Licenses.deserialize(restResponse.getResponseBody());
341            }
342        }
343        return licenses;
344    }
345
346    @Override
347    public void updateLicense(License license) {
348        String requestBody = license.serialize(license);
349        RestResponse restResponse = putRequest(requestBody, LICENSES_URL);
350        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
351            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
352                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
353            }
354        }
355    }
356
357    @Override
358    public void updateLicenses(Licenses licenses) {
359        String requestBody = Licenses.serialize(licenses);
360        RestResponse restResponse = putRequest(requestBody, LICENSES_TREES_URL);
361        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
362            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
363                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
364            }
365        }
366
367    }
368
369    @Override
370    public void deleteLicense(String id) {
371        RestResponse restResponse = deleteRequest(id, LICENSES_URL);
372        if (restResponse.getResponse().getStatusLine().getStatusCode() != 200) {
373            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
374                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
375            }
376        }
377
378    }
379
380    @Override
381    public void createAnalyticsRelation(String seriesHoldingsId, List<String> itemIds) {
382        //To change body of implemented methods use File | Settings | File Templates.
383        String requestBody = buildIds(itemIds, "");
384        RestResponse restResponse = postRequest(requestBody, HOLDINGS_URL + seriesHoldingsId + ANALYTIC_URL);
385        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
386            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
387                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
388            }
389        }
390    }
391
392    @Override
393    public void bulkUpdateHoldings(Holdings holdings, List<String> holdingIds, String canUpdateStaffOnlyFlag) {
394        String requestBody = holdings.serialize(holdings);
395        String holdingUpdateIds = buildIds(holdingIds, "");
396        RestResponse restResponse = putRequest(holdingUpdateIds + "\n" + canUpdateStaffOnlyFlag + "\n" + requestBody, HOLDINGS_URL + "/" + BULK_UPDATE);
397        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
398            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
399                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
400            }
401        }
402    }
403
404    @Override
405    public void bulkUpdateItem(Item item, List<String> itemIds, String canUpdateStaffOnlyFlag) {
406        String requestBody = item.serialize(item);
407        String itemUpdateIds = buildIds(itemIds, "");
408        RestResponse restResponse = putRequest(itemUpdateIds + "\n" + canUpdateStaffOnlyFlag + "\n" + requestBody, ITEMS_URL + "/" + BULK_UPDATE);
409        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
410            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
411                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
412            }
413        }
414    }
415
416    @Override
417    public void breakAnalyticsRelation(String seriesHoldingsId, List<String> itemIds) {
418        String requestBody = buildIds(itemIds, "");
419        RestResponse restResponse = postRequest(requestBody, HOLDINGS_URL + seriesHoldingsId + BREAK_ANALYTIC_URL);
420        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
421            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
422                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
423            }
424        }
425    }
426
427    @Override
428    public Bib retrieveBib(String bibId) {
429        String reqParam = "?bibId=" + bibId;
430        RestResponse restResponse = getBibResponse(reqParam, BIB_URL);
431        Bib bib = new Bib();
432        bib = (Bib) bib.deserialize(restResponse.getResponseBody());
433        return bib;
434    }
435
436    @Override
437    public BibMarcRecords retrieveBibContent(List<String> bibIds) {
438        RestResponse restResponse = getBibResponse(buildQueryString(bibIds, "bibId"), BIB_CONTENT_URL);
439        BibMarcRecords bibMarcRecords = new BibMarcRecords();
440        BibMarcRecordProcessor bibMarcRecordProcessor = new BibMarcRecordProcessor();
441        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
442            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
443                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
444            } else {
445                bibMarcRecords = bibMarcRecordProcessor.fromXML(restResponse.getResponseBody());
446            }
447        }
448        return bibMarcRecords;
449    }
450
451    @Override
452    public HoldingsTrees retrieveHoldingsTrees(List<String> bibIds) {
453        RestResponse restResponse = getRequest(buildQueryString(bibIds, "bibId"), HOLDINGS_TREES_CONTENT_URL);
454        HoldingsTrees holdingsTrees = new HoldingsTrees();
455        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
456            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
457                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
458            } else {
459                holdingsTrees = (HoldingsTrees) holdingsTrees.deserialize(restResponse.getResponseBody());
460            }
461        }
462        return holdingsTrees;
463    }
464
465    @Override
466    public HoldingsTrees retrieveHoldingsDocTrees(List<String> bibIds) {
467        RestResponse restResponse = getRequest(buildQueryString(bibIds, "bibId"), HOLDINGS_TREES_URL);
468        HoldingsTrees holdingsTrees = new HoldingsTrees();
469        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
470            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
471                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
472            } else {
473                holdingsTrees = (HoldingsTrees) holdingsTrees.deserialize(restResponse.getResponseBody());
474            }
475        }
476        return holdingsTrees;
477    }
478
479    @Override
480    public Item retrieveItemByBarcode(String barcode) {
481        RestResponse restResponse = getRequest("?barcode=" + barcode, ITEM_CONTENT_URL);
482        Item item = new Item();
483        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
484            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
485                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
486            } else {
487                item = (Item) item.deserialize(restResponse.getResponseBody());
488            }
489        }
490        return item;
491    }
492
493    @Override
494    public void reloadConfiguration() {
495        RestResponse restResponse = getRequest("", RELOAD_URL);
496    }
497
498    @Override
499    public Holdings retrieveHoldings(String holdingsId) {
500        String reqParam = "?holdingsId=" + holdingsId;
501        RestResponse restResponse = getRequest(reqParam, HOLDINGS_URL);
502        Holdings holdings = new PHoldings();
503        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
504            holdings = (Holdings) holdings.deserialize(restResponse.getResponseBody());
505            if (!holdings.getHoldingsType().equalsIgnoreCase("print")) {
506                holdings = new EHoldings();
507                if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
508                    throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
509                } else {
510                    holdings = (EHoldings) holdings.deserialize(restResponse.getResponseBody());
511                }
512            }
513        }
514        return holdings;
515    }
516
517    @Override
518    public Item retrieveItem(String itemId) {
519        String queryParam = "?itemId=" + itemId;
520        RestResponse restResponse = getRequest(queryParam, ITEMS_URL);
521        Item item = new Item();
522        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
523            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
524                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
525            } else {
526                item = (Item) item.deserialize(restResponse.getResponseBody());
527            }
528        }
529        return item;
530    }
531
532    @Override
533    public HoldingsTree retrieveHoldingsTree(String holdingsId) {
534        HoldingsTree holdingsTree = new HoldingsTree();
535        String reqParam = "?holdingsId=" + holdingsId;
536        RestResponse restResponse = getRequest(reqParam, HOLDINGS_TREE_URL);
537        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
538            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
539                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
540            } else {
541                holdingsTree = (HoldingsTree) holdingsTree.deserialize(restResponse.getResponseBody());
542            }
543        }
544        return holdingsTree;
545    }
546
547    @Override
548    public BibTree retrieveBibTree(String bibId) {
549        BibTree bibTree = new BibTree();
550        String reqParam = "?bibId=" + bibId;
551        RestResponse restResponse = getBibResponse(reqParam, BIB_TREE_URL);
552        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
553            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
554                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
555            } else {
556                bibTree = (BibTree) bibTree.deserialize(restResponse.getResponseBody());
557            }
558        }
559        return bibTree;
560    }
561
562    @Override
563    public BibTrees retrieveBibTrees(List<String> bibIds) {
564        BibTrees bibTrees = new BibTrees();
565
566        RestResponse restResponse = getBibResponse(buildQueryString(bibIds, "bibId"), BIB_TREES_URL);
567        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
568            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
569                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
570            } else {
571                bibTrees = (BibTrees) BibTrees.deserialize(restResponse.getResponseBody());
572            }
573        }
574
575        return bibTrees;
576    }
577
578    @Override
579    public Bib updateBib(Bib bib) {
580        String requestBody = bib.serialize(bib);
581        RestResponse restResponse = putRequest(requestBody, BIB_URL);
582        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
583            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
584                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
585            }
586        }
587        return bib;
588    }
589
590    @Override
591    public Holdings updateHoldings(Holdings holdings) {
592        String requestBody = holdings.serialize(holdings);
593        RestResponse restResponse = putRequest(requestBody, HOLDINGS_URL);
594        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
595            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
596                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
597            }
598        }
599        return holdings;
600    }
601
602    @Override
603    public Item updateItem(Item item) {
604        String requestBody = item.serialize(item);
605        RestResponse restResponse = putRequest(requestBody, ITEMS_URL);
606        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
607            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
608                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
609            }
610        }
611        return item;
612    }
613
614    @Override
615    public String updateItemByBarcode(String barcode, String requestBody) {
616        RestResponse restResponse = patchRequest(requestBody, ITEM_CONTENT_URL + "?barcode=" + barcode);
617        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
618            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
619                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
620            }
621        }
622        return restResponse.getResponseBody();
623    }
624
625    @Override
626    public String patchItem(String requestBody) {
627        RestResponse restResponse = patchRequest(requestBody, ITEM_CONTENT_URL);
628        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
629            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
630                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
631            }
632        }
633        return restResponse.getResponseBody();
634    }
635
636    @Override
637    public void deleteBib(String bibId) {
638        String reqParam = "?bibId=" + bibId;
639        RestResponse restResponse = deleteRequest(reqParam, BIB_URL);
640        if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
641            throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
642        }
643    }
644
645    @Override
646    public void deleteHoldings(String holdingsId) {
647        String reqParam = "?holdingsId=" + holdingsId;
648        RestResponse restResponse = deleteRequest(reqParam, HOLDINGS_URL);
649        if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
650            throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
651        }
652    }
653
654    @Override
655    public void deleteItem(String itemId) {
656        String queryString = "?itemId=" + itemId;
657        RestResponse restResponse = deleteRequest(queryString, ITEMS_URL);
658        if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
659            throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
660        }
661    }
662
663    @Override
664    public void deleteItems(List<String> itemIds) {
665        String queryString = buildIds(itemIds, "?itemId=");
666        RestResponse restResponse = deleteRequest(queryString, ITEMS_DOCS_URL);
667        if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
668            throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
669        }
670    }
671
672    @Override
673    public SearchResponse search(SearchParams searchParams) {
674        String requestBody = searchParams.serialize(searchParams);
675        RestResponse restResponse = postRequest(requestBody, SEARCH_URL);
676        SearchResponse searchResponse = new SearchResponse();
677        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
678            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
679                logger.info("DocstoreRestClient search : " + restResponse.getResponseBody());
680                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
681            } else {
682                searchResponse = (SearchResponse) searchResponse.deserialize(restResponse.getResponseBody());
683            }
684        }
685        return searchResponse;
686    }
687
688    @Override
689    public Bib findBib(Map<String, String> map) {
690        Bib bib = new Bib();
691        FindParams findParams = buildFindParams(map);
692        String requestBody = findParams.serialize(findParams);
693        RestResponse restResponse = postRequest(requestBody, BIB_URL + FIND_URL);
694        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
695            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
696                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
697            } else {
698                bib = (Bib) bib.deserialize(restResponse.getResponseBody());
699            }
700        }
701        return bib;
702    }
703
704    @Override
705    public BibTree findBibTree(Map<String, String> map) {
706        BibTree bibTree = new BibTree();
707        FindParams findParams = buildFindParams(map);
708        String requestBody = findParams.serialize(findParams);
709        RestResponse restResponse = postRequest(requestBody, BIB_TREE_URL + FIND_URL);
710        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
711            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
712                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
713            } else {
714                bibTree = (BibTree) bibTree.deserialize(restResponse.getResponseBody());
715            }
716        }
717        return bibTree;
718    }
719
720    @Override
721    public Holdings findHoldings(Map<String, String> map) {
722        Holdings holdings = new PHoldings();
723        FindParams findParams = buildFindParams(map);
724        String requestBody = findParams.serialize(findParams);
725        RestResponse restResponse = postRequest(requestBody, HOLDINGS_URL + FIND_URL);
726        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
727            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
728                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
729            } else {
730                holdings = (Holdings) holdings.deserialize(restResponse.getResponseBody());
731            }
732        }
733        return holdings;
734    }
735
736    @Override
737    public HoldingsTree findHoldingsTree(Map<String, String> map) {
738        HoldingsTree holdingsTree = new HoldingsTree();
739        FindParams findParams = buildFindParams(map);
740        String requestBody = findParams.serialize(findParams);
741        RestResponse restResponse = postRequest(requestBody, HOLDINGS_TREE_URL + FIND_URL);
742        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
743            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
744                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
745            } else {
746                holdingsTree = (HoldingsTree) holdingsTree.deserialize(restResponse.getResponseBody());
747            }
748        }
749        return holdingsTree;
750    }
751
752    @Override
753    public Item findItem(Map<String, String> map) {
754        Item item = new Item();
755        FindParams findParams = buildFindParams(map);
756        String requestBody = findParams.serialize(findParams);
757        RestResponse restResponse = postRequest(requestBody, ITEMS_URL + FIND_URL);
758        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
759            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
760                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
761            } else {
762                item = (Item) item.deserialize(restResponse.getResponseBody());
763            }
764        }
765        return item;
766    }
767
768    @Override
769    public SearchResponse browseItems(BrowseParams browseParams) {
770        String requestBody = browseParams.serialize(browseParams);
771        RestResponse restResponse = postRequest(requestBody, BROWSE_URL + ITEMS_URL);
772        SearchResponse searchResponse = new SearchResponse();
773        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
774            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
775                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
776            } else {
777                searchResponse = (SearchResponse) searchResponse.deserialize(restResponse.getResponseBody());
778            }
779        }
780        return searchResponse;
781    }
782
783    @Override
784    public SearchResponse browseHoldings(BrowseParams browseParams) {
785        String requestBody = browseParams.serialize(browseParams);
786        RestResponse restResponse = postRequest(requestBody, BROWSE_URL + HOLDINGS_URL);
787        SearchResponse searchResponse = new SearchResponse();
788        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
789            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
790                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
791            } else {
792                searchResponse = (SearchResponse) searchResponse.deserialize(restResponse.getResponseBody());
793            }
794        }
795        return searchResponse;
796    }
797
798    @Override
799    public void boundWithBibs(String holdingsId, List<String> bibIds) {
800        String requestBody = buildIds(bibIds, "");
801        RestResponse restResponse = postRequest(requestBody, HOLDINGS_URL + holdingsId + BOUND_URL);
802        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
803            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
804                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
805            }
806        }
807    }
808
809    @Override
810    public void transferHoldings(List<String> holdingsIds, String bibId) {
811
812        RestResponse restResponse = postRequest(" ", BIB_URL + bibId + TRANSFER_URL + buildQueryString(holdingsIds, "holdingsId"));
813        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
814            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
815                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
816            }
817        }
818    }
819
820    @Override
821    public void transferItems(List<String> itemIds, String holdingsId) {
822        String reqParam = buildQueryString(itemIds, "itemId");
823        RestResponse restResponse = postRequest(" ", HOLDINGS_URL + holdingsId + TRANSFER_URL + reqParam);
824        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
825            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
826                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
827            }
828        }
829    }
830
831    @Override
832    public void deleteBibs(List<String> bibIds) {
833        RestResponse restResponse = deleteRequest(buildQueryString(bibIds, "bibId"), BIB_URL);
834        //if (restResponse.getResponse().getStatusLine().getStatusCode() != 200) {
835            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
836                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
837            }
838        //}
839    }
840
841
842    /////////////////////////////////// Utility Methods  /////////////////////
843
844
845    private String buildQueryString(List<String> ids, String queryParam) {
846        StringBuilder reqParam = new StringBuilder("?");
847        int size = ids.size();
848        for (int i = 0; i < size; i++) {
849            reqParam.append(queryParam);
850            reqParam.append("=");
851            reqParam.append(ids.get(i));
852            if (i != (size - 1)) {
853                reqParam.append("&");
854            }
855        }
856        return reqParam.toString();
857    }
858
859    private String buildQueryPostString(List<String> ids, String queryParam) {
860        StringBuilder reqParam = new StringBuilder("");
861        int size = ids.size();
862        for (int i = 0; i < size; i++) {
863            reqParam.append(queryParam);
864            reqParam.append("=");
865            reqParam.append(ids.get(i));
866            if (i != (size - 1)) {
867                reqParam.append("&");
868            }
869        }
870        return reqParam.toString();
871    }
872
873    public String buildIds(List<String> ids, String value) {
874        StringBuilder idSb = new StringBuilder(value);
875        for (String id : ids) {
876            if (ids.get(ids.size() - 1).equals(id)) {
877                idSb.append(id);
878            } else {
879                idSb.append(id + ",");
880            }
881        }
882        return idSb.toString();
883    }
884
885    public FindParams buildFindParams(Map<String, String> map) {
886        FindParams findParams = new FindParams();
887        FindParams.Map findMap = new FindParams.Map();
888        for (Map.Entry mapEntry : map.entrySet()) {
889            FindParams.Map.Entry entry = new FindParams.Map.Entry();
890            entry.setKey((String) mapEntry.getKey());
891            entry.setValue((String) mapEntry.getValue());
892            findMap.getEntry().add(entry);
893        }
894        findParams.setMap(findMap);
895        return findParams;
896    }
897
898    public RestResponse patchRequest(String requestBody, String param) {
899        HttpClient client = new DefaultHttpClient();
900        String result = new String();
901        RestResponse response = new RestResponse();
902        HttpPatch patch = new HttpPatch(DOCSTORE_URL + param);
903        try {
904            StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
905            patch.setEntity(stringEntity);
906            response.setResponse(client.execute(patch));
907            result = getEncodeEntityValue(response.getResponse().getEntity());
908        } catch (Exception e) {
909            logger.error("PATCH response error is ::", e);
910        }
911        response.setResponseBody(result);
912        logger.debug(" PATCH Response Body :: ", response.getResponseBody());
913        return response;
914    }
915
916    public RestResponse postRequest(String requestBody, String param) {
917        HttpClient client = new DefaultHttpClient();
918        String result = new String();
919        RestResponse response = new RestResponse();
920        HttpPost post = new HttpPost(DOCSTORE_URL + param);
921        try {
922            StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
923            post.setEntity(stringEntity);
924            response.setResponse(client.execute(post));
925            result = getEncodeEntityValue(response.getResponse().getEntity());
926        } catch (Exception e) {
927            logger.error("POST response error is ::", e);
928        }
929        response.setResponseBody(result);
930        logger.debug(" POST Response Body :: ", response.getResponseBody());
931        return response;
932    }
933
934    public RestResponse putRequest(String requestBody, String param) {
935        HttpClient client = new DefaultHttpClient();
936        String result = new String();
937        HttpPut put = new HttpPut(DOCSTORE_URL + param);
938        RestResponse response = new RestResponse();
939        try {
940            StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
941            put.setEntity(stringEntity);
942            response.setResponse(client.execute(put));
943            result = getEncodeEntityValue(response.getResponse().getEntity());
944        } catch (Exception e) {
945            logger.error("PUT response error is :: ", e);
946        }
947        response.setResponseBody(result);
948        logger.debug(" PUT Response Body :: ", response.getResponseBody());
949        return response;
950    }
951
952    private RestResponse getRequest(String id, String param) {
953        HttpClient client = new DefaultHttpClient();
954        HttpGet get = new HttpGet(DOCSTORE_URL + param + id);
955        String result = new String();
956        RestResponse response = new RestResponse();
957        try {
958            response.setResponse(client.execute(get));
959            // HttpEntity entity = response.getResponse().getEntity();
960            result = getEncodeEntityValue(response.getResponse().getEntity());
961        } catch (Exception e) {
962            logger.error("GET response error is ::", e);
963        }
964        response.setResponseBody(result);
965        logger.debug(" GET Response Body :: ", response.getResponseBody());
966        return response;
967    }
968
969    private RestResponse getBibResponse(String id, String param) {
970        RestResponse response = new RestResponse();
971        response.setContentType("text/html; charset=utf-8");
972        try {
973            URL aURL = new URL(DOCSTORE_URL + param + id);
974            StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "OK");
975            HttpResponse httpResponse = new BasicHttpResponse(statusLine);
976            String result = getHttpResponse(new InputStreamReader(aURL.openStream()), response.getContentType());
977            response.setResponseBody(result);
978            response.setResponse(httpResponse);
979            logger.debug(" GET Response Body :: ", response.getResponseBody());
980        } catch (Exception ex) {
981            ex.printStackTrace();
982            logger.error("Exception :", ex);
983        }
984        return response;
985    }
986
987    public RestResponse deleteRequest(String id, String param) {
988        String result = new String();
989        RestResponse response = new RestResponse();
990        HttpClient client = new DefaultHttpClient();
991        HttpDelete delete = new HttpDelete(DOCSTORE_URL + param + id);
992        try {
993            response.setResponse(client.execute(delete));
994            result = getEncodeEntityValue(response.getResponse().getEntity());
995        } catch (Exception e) {
996            logger.error("DELETE response error is ::", e);
997        }
998        response.setResponseBody(result);
999        logger.debug("DELETE Response Body :: ", response.getResponseBody());
1000        return response;
1001    }
1002
1003    private String getEncodeEntityValue(HttpEntity entity) throws Exception {
1004        String result = EntityUtils.toString(entity, "UTF-8");
1005        return result;
1006    }
1007
1008    private String getHttpResponse(InputStreamReader inputStreamReader, String contentType) throws Exception {
1009        StringWriter writer = new StringWriter();
1010        //   writer.setContentType("text/html; charset=utf-8");
1011        IOUtils.copy(inputStreamReader, writer);
1012        return writer.toString();
1013    }
1014
1015    public File createZipFile(File sourceDir) throws IOException {
1016        File zipFile = File.createTempFile("tmp", ".zip");
1017        String path = sourceDir.getAbsolutePath();
1018        ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
1019        ArrayList<File> fileList = getAllFilesList(sourceDir);
1020        for (File file : fileList) {
1021            ZipEntry ze = new ZipEntry(file.getAbsolutePath().substring(path.length() + 1));
1022            zip.putNextEntry(ze);
1023            FileInputStream fis = new FileInputStream(file);
1024            org.apache.commons.compress.utils.IOUtils.copy(fis, zip);
1025            fis.close();
1026            zip.closeEntry();
1027        }
1028        zip.close();
1029        return zipFile;
1030    }
1031
1032    public ArrayList<File> getAllFilesList(File directory) {
1033        ArrayList<File> fileList = new ArrayList<File>();
1034        if (directory.isFile())
1035            fileList.add(directory);
1036        else if (directory.isDirectory())
1037            for (File innerFile : directory.listFiles())
1038                fileList.addAll(getAllFilesList(innerFile));
1039        return fileList;
1040    }
1041
1042
1043    public void deleteFiles(File[] files) {
1044        try {
1045            for (File file : files) {
1046                try {
1047                    file.delete();
1048                } catch (Exception e) {
1049                }
1050            }
1051        } catch (Exception e) {
1052        }
1053    }
1054
1055    public List<Bib> acquisitionSearchRetrieveBibs(List<String> bibIds) {
1056//        String bibIdSb = buildIds(bibIds, "bibIds=");
1057        RestResponse restResponse = sendPostForAcquisitionSearch(DOCSTORE_URL+BIB_URL+"searchAcquistion",buildQueryPostString(bibIds, "bibId"));
1058        Bibs bibsObj = new Bibs();
1059        if (restResponse.getResponse().getStatusLine().getStatusCode() == 200) {
1060            if (restResponse.getResponseBody().startsWith("<org.kuali.ole.docstore.common.exception")) {
1061                throw DocstoreExceptionProcessor.fromXML(restResponse.getResponseBody());
1062            } else {
1063                if (bibIds.size() == 1) {
1064                    Bib bib = new Bib();
1065                    bibsObj.getBibs().add((Bib) bib.deserialize(restResponse.getResponseBody()));
1066                    return bibsObj.getBibs();
1067                }
1068                bibsObj = (Bibs) Bibs.deserialize(restResponse.getResponseBody());
1069
1070            }
1071        }
1072        return bibsObj.getBibs();
1073
1074    }
1075
1076    private RestResponse sendPostForAcquisitionSearch(String url, String urlParameters) {
1077
1078        StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "OK");
1079        HttpResponse httpResponse = new BasicHttpResponse(statusLine);
1080        String postResponse = null;
1081        try {
1082            URL obj = new URL(url);
1083            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
1084            con.setRequestMethod("POST");
1085            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
1086            con.setDoOutput(true);
1087            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
1088            wr.writeBytes(urlParameters);
1089            wr.flush();
1090            wr.close();
1091            int responseCode = con.getResponseCode();
1092            BufferedReader in = new BufferedReader(
1093                    new InputStreamReader(con.getInputStream()));
1094            String inputLine;
1095            StringBuffer response = new StringBuffer();
1096            while ((inputLine = in.readLine()) != null) {
1097                response.append(inputLine);
1098            }
1099            in.close();
1100            postResponse = response.toString();
1101        } catch (Exception e) {
1102            e.printStackTrace();
1103        }
1104
1105        RestResponse response = new RestResponse();
1106        response.setContentType("text/html; charset=utf-8");
1107        response.setResponseBody(postResponse);
1108        response.setResponse(httpResponse);
1109        return response;
1110    }
1111
1112}