001package org.kuali.ole.web;
002
003import com.google.common.io.CharStreams;
004import gov.loc.repository.bagit.utilities.FormatHelper;
005import org.apache.commons.fileupload.FileItem;
006import org.apache.commons.fileupload.disk.DiskFileItemFactory;
007import org.apache.commons.fileupload.servlet.ServletFileUpload;
008import org.apache.commons.io.FileUtils;
009import org.apache.commons.lang.StringUtils;
010import org.kuali.ole.docstore.common.document.BibMarc;
011import org.kuali.ole.docstore.common.document.License;
012import org.kuali.ole.docstore.common.document.LicenseAttachment;
013import org.kuali.ole.docstore.common.document.Licenses;
014import org.kuali.ole.docstore.common.exception.DocstoreException;
015import org.kuali.ole.docstore.common.exception.DocstoreExceptionProcessor;
016import org.kuali.ole.docstore.common.service.DocstoreService;
017import org.kuali.ole.docstore.service.BeanLocator;
018import org.kuali.ole.utility.CompressUtils;
019import org.slf4j.Logger;
020import org.slf4j.LoggerFactory;
021
022import javax.servlet.ServletException;
023import javax.servlet.http.HttpServlet;
024import javax.servlet.http.HttpServletRequest;
025import javax.servlet.http.HttpServletResponse;
026import java.io.File;
027import java.io.IOException;
028import java.io.PrintWriter;
029import java.util.ArrayList;
030import java.util.Iterator;
031import java.util.List;
032
033/**
034 * Created with IntelliJ IDEA.
035 * User: sambasivam
036 * Date: 2/27/14
037 * Time: 6:13 PM
038 * To change this template use File | Settings | File Templates.
039 */
040public class LicenseRestServlet extends HttpServlet {
041
042    private static final Logger LOG = LoggerFactory.getLogger(LicenseRestServlet.class);
043    private CompressUtils compressUtils = new CompressUtils();
044    DocstoreService ds = BeanLocator.getDocstoreService();
045    private static String responseUrl = "documentrest/license/";
046    private String extractFilePath = FileUtils.getTempDirectoryPath() + File.separator + "bagit";
047
048    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
049
050        PrintWriter out = resp.getWriter();
051        resp.setContentType("text/xml;charset=UTF-8");
052        String result = "";
053        Licenses licenses = null;
054        try {
055            ArrayList<File> files = extractBagFilesFromRequest(req, resp);
056            for(File file : files) {
057                if (file.getName().equalsIgnoreCase("licenses.xml")) {
058                    String licensesXml = FileUtils.readFileToString(file);
059                    licenses = (Licenses) Licenses.deserialize(licensesXml);
060                    for(License license : licenses.getLicenses()) {
061                        if(!license.getFormat().equals("onixpl")) {
062                            LicenseAttachment licenseAttachment = (LicenseAttachment) license;
063                            licenseAttachment.setFilePath(file.getParent());
064                        }
065                    }
066                }
067            }
068            ds.createLicenses(licenses);
069            compressUtils.deleteFiles(files);
070            File extractFile = new File(extractFilePath);
071            extractFile.delete();
072        } catch (Exception e) {
073            LOG.error("EXception : ", e);
074        }
075        StringBuffer ids = new StringBuffer();
076        for(License license : licenses.getLicenses()) {
077            ids.append(license.getId());
078            ids.append("/");
079        }
080
081        out.write(responseUrl+ ids.substring(0, (ids.length()-1)));
082    }
083
084    @Override
085    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
086        PrintWriter out = resp.getWriter();
087        resp.setContentType("text/xml;charset=UTF-8");
088        String result = "";
089        try {
090           result = retrieveLicense(req);
091            out.print(result);
092        } catch (DocstoreException de) {
093            LOG.error("Exception :", de);
094            out.print(DocstoreExceptionProcessor.toXml(de));
095        } catch (Exception e) {
096            LOG.error("Exception :", e);
097            out.print(e);
098        }
099    }
100
101    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
102        PrintWriter out = resp.getWriter();
103        resp.setContentType("text/xml;charset=UTF-8");
104        String result = "";
105
106        try {
107            result = deleteLicense(req);
108            out.print(result);
109        } catch (DocstoreException de) {
110            LOG.error("Exception :", de);
111            out.print(DocstoreExceptionProcessor.toXml(de));
112        } catch (Exception e) {
113            LOG.error("Exception :", e);
114            out.print(e);
115        }
116    }
117
118    private String deleteLicense(HttpServletRequest req) {
119        DocstoreService ds = BeanLocator.getDocstoreService();
120        String licenseId = getIdFromPathInfo(req.getPathInfo());
121        ds.deleteLicense(licenseId);
122        return "Success";
123    }
124
125
126
127    private String retrieveLicense(HttpServletRequest req) {
128        DocstoreService ds = BeanLocator.getDocstoreService();
129        String id = getIdFromPathInfo(req.getPathInfo());
130        if (id.contains("licenseIds")) {
131            String[] splitString = id.split("=");
132            String[] licenseIds = splitString[1].split(",");
133            List<String> licenseIdList = new ArrayList<String>();
134            for (String bibId : licenseIds) {
135                licenseIdList.add(bibId);
136            }
137            Licenses licenses = null;
138            licenses = ds.retrieveLicenses(licenseIdList);
139            return Licenses.serialize(licenses);
140
141        } else {
142            License license = ds.retrieveLicense(id);
143            return license.serialize(license);
144        }
145
146    }
147
148
149    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
150
151        PrintWriter out = resp.getWriter();
152        resp.setContentType("text/xml;charset=UTF-8");
153        String result = "";
154        try {
155            if (req.getPathInfo().startsWith("/trees")) {
156                result = updateLicenses(req);
157            } else {
158                result = updateLicense(req);
159            }
160            out.print(result);
161        } catch (DocstoreException de) {
162            LOG.error("Exception :", de);
163            out.print(DocstoreExceptionProcessor.toXml(de));
164        } catch (Exception e) {
165            LOG.error("Exception :", e);
166            out.print(e);
167        }
168    }
169
170    private String updateLicense(HttpServletRequest req) throws IOException {
171        DocstoreService ds = BeanLocator.getDocstoreService();
172        String requestBody = CharStreams.toString(req.getReader());
173
174        License license = new License();
175        License licenseObj = (License) license.deserialize(requestBody);
176        ds.updateLicense(licenseObj);
177        return responseUrl + licenseObj.getId();
178
179    }
180
181    private String updateLicenses(HttpServletRequest req) throws IOException {
182        DocstoreService ds = BeanLocator.getDocstoreService();
183        String requestBody = CharStreams.toString(req.getReader());
184        Licenses licenses = (Licenses) Licenses.deserialize(requestBody);
185        ds.updateLicenses(licenses);
186        return "";
187    }
188
189
190    private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res)
191            throws Exception {
192        File targetDir = null;
193        try {
194            File file = null;
195            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
196            fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
197            Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
198            while (items.hasNext()) {
199                FileItem item = (FileItem) items.next();
200                file = new File(FileUtils.getTempDirectory(), item.getName());
201                item.write(file);
202            }
203            targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), extractFilePath);
204            LOG.info("extractedBagFileLocation " + targetDir);
205        } catch (IOException e) {
206            LOG.error("IOException", e);
207//            sendResponseBag(res, e.getMessage(), "failure");
208        } catch (FormatHelper.UnknownFormatException unknownFormatException) {
209            LOG.error("unknownFormatException", unknownFormatException);
210//            sendResponseBag(res, unknownFormatException.getMessage(), "failure");
211        }
212        return compressUtils.getAllFilesList(targetDir);
213    }
214
215    private String getIdFromPathInfo(String pathInfo) {
216        String id = "";
217        if (StringUtils.isNotEmpty(pathInfo)) {
218            int length = pathInfo.length();
219            if (pathInfo.endsWith("/")) {
220                pathInfo = pathInfo.substring(0, length - 1);
221            }
222            id = pathInfo.substring(pathInfo.lastIndexOf("/") + 1);
223        }
224        return id;
225    }
226
227}