Mercurial > hg > LGDataverses
view DVN-web/src/main/java/de/mpiwg/monographs/servlet/SaveResource.java @ 4:9b408c9b05ab
Integration with LGServices.
author | "jurzua <jurzua@mpiwg-berlin.mpg.de>" |
---|---|
date | Thu, 07 May 2015 14:56:46 +0200 |
parents | 2ae72563a29d |
children |
line wrap: on
line source
package de.mpiwg.monographs.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.inject.Inject; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang.StringUtils; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.swordapp.server.AuthCredentials; import org.swordapp.server.DepositReceipt; import org.swordapp.server.ServiceDocumentAPI; import org.swordapp.server.SwordAuthException; import org.swordapp.server.SwordError; import org.swordapp.server.SwordServerException; import org.swordapp.server.UriRegistry; import org.swordapp.server.servlets.SwordServlet; import edu.harvard.iq.dvn.api.datadeposit.ReceiptGenerator; import edu.harvard.iq.dvn.api.datadeposit.ServiceDocumentManagerImpl; import edu.harvard.iq.dvn.api.datadeposit.SwordAuth; import edu.harvard.iq.dvn.api.datadeposit.UrlManager; import edu.harvard.iq.dvn.core.admin.VDCUser; import edu.harvard.iq.dvn.core.study.EditStudyService; import edu.harvard.iq.dvn.core.study.Study; import edu.harvard.iq.dvn.core.study.StudyFileEditBean; import edu.harvard.iq.dvn.core.study.StudyFileServiceLocal; import edu.harvard.iq.dvn.core.study.StudyServiceLocal; import edu.harvard.iq.dvn.core.study.TabularDataFile; import edu.harvard.iq.dvn.core.util.FileUtil; public class SaveResource extends AbstractMonographServlet { private static final long serialVersionUID = 1L; private static final String TMP_DIR = "/gazetteer-server/tmp/"; private int maxFileSize = 100 * 1024; private int maxMemSize = 4 * 1024; private static final Logger logger = Logger.getLogger("monographs.SaveResource"); @EJB private StudyFileServiceLocal studyFileService; @EJB private StudyServiceLocal studyService; @Inject private SwordAuth swordAuth; Map<String, String> params = new HashMap<String, String>(); public void init() throws ServletException { super.init(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("application/json"); JSONObject jsonResponse = new JSONObject(); File file = getFile(request, response); if (file != null && file.length() > 0) { String studyGlobalId = params.get("studyId"); String user = params.get("user"); String password = params.get("password"); //String fileLabel = params.get("fileLabel"); if(StringUtils.isNotEmpty(studyGlobalId) && StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(password)/* && StringUtils.isNotEmpty(fileLabel)*/){ AuthCredentials authCredentials = new AuthCredentials(user, password, null); try { List<StudyFileEditBean> list = saveFile(file, studyGlobalId, authCredentials/*, fileLabel*/); JSONObject fileMetatdata = new JSONObject(); fileMetatdata.put("id", list.get(0).getFileMetadata().getId()); fileMetatdata.put("label", list.get(0).getFileMetadata().getLabel()); fileMetatdata.put("version", list.get(0).getFileMetadata().getVersion()); fileMetatdata.put("description", list.get(0).getFileMetadata().getDescription()); jsonResponse.put("fileMetadata", fileMetatdata); jsonResponse.put("status", "ok"); } catch (Exception e) { logger.log(Level.SEVERE, "Error!!!!!!", e); error(jsonResponse, e); } }else{ jsonResponse.put("status", "error"); jsonResponse.put("error", "The parameters studyId, user and password."); jsonResponse.put("studyId", studyGlobalId); jsonResponse.put("user", user); jsonResponse.put("password", password); //jsonResponse.put("fileLabel", fileLabel); } }else if(file == null){ jsonResponse.put("status", "error"); jsonResponse.put("message", "No file found in the request."); }else { jsonResponse.put("status", "error"); jsonResponse.put("message", "A file has been found as parameter, however it was empty. Check the temporal folder configured in Dataverse. " + TMP_DIR); } java.io.PrintWriter out = response.getWriter(); out.print(jsonResponse); out.flush(); } catch (Exception e) { e.printStackTrace(); } } private File getFile(HttpServletRequest request, HttpServletResponse response) throws IOException { File file = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart){ DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(TMP_DIR)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); StringBuilder sb = new StringBuilder(); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); sb.append(fi.getFieldName()); if(fi.isFormField()){ sb.append(" is Field"); params.put(fi.getFieldName(), fi.getString()); } else { sb.append(" is FILE ***"); // Get the uploaded file parameters String fileName = fi.getName(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(TMP_DIR + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(TMP_DIR + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); sb.append(" Size: " + file.length()); } sb.append("\n"); } } catch (Exception ex) { ex.printStackTrace(); } sb.append((file == null) ? "File is null" : "File Size=" + file.length() + ".\nWhen the file is empty, maybe the tmp folder is wrong configured.\nTMP_DIR: " + TMP_DIR); logger.log(Level.INFO, "getFile Information:\n" + sb.toString()); return file; } return null; } private List<StudyFileEditBean> saveFile(File file, String studyGlobalId, AuthCredentials authCredentials/*, String fileLabel*/) throws Exception { VDCUser vdcUser = swordAuth.auth(authCredentials); Study study = getStudy(studyGlobalId); try { List<StudyFileEditBean> files = getFileList(file, study); studyFileService.addFiles(study.getLatestVersion(), files, vdcUser); return files; } catch (EJBException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to study: " + ex.getMessage()); } } public List<StudyFileEditBean> getFileList(File uploadedInputFile, Study study) throws Exception { List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>(); if (uploadedInputFile.length() != 0) { File dir = new File(uploadedInputFile.getParentFile(), study.getId().toString() ); if ( !dir.exists() ) { dir.mkdir(); } File file = FileUtil.createTempFile(dir, uploadedInputFile.getName()); if (!uploadedInputFile.renameTo(file)) { // in windows environment, rename doesn't work, so we will copy the file instead FileUtil.copyFile(uploadedInputFile, file); uploadedInputFile.delete(); } StudyFileEditBean tempFileBean = new StudyFileEditBean(file, studyService.generateFileSystemNameSequence(), study); tempFileBean.setSizeFormatted(file.length()); fbList.add(tempFileBean); } return fbList; } }