Search in sources :

Example 41 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project RESTdoclet by IG-Group.

the class FileUploadServlet method doPost.

/* (non-Javadoc)
    * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    * 
    * This method accepts a jar and extracts to a location specified by the header key RESTDOCLET_DEPLOY
    */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String deploySubDir = request.getHeader(RESTDOCLET_DEPLOY);
    String deployDir = configPath + File.separator + deploySubDir;
    File dir = new File(deployDir);
    deleteDir(dir);
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            LOG.info("Upload request to " + deployDir);
            List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory(1024 * 1024, dir)).parseRequest(request);
            for (FileItem item : fileItems) {
                if (item != null) {
                    LOG.debug(item.getName());
                    JarInputStream jis = new JarInputStream(item.getInputStream());
                    JarEntry jarEntry;
                    while ((jarEntry = jis.getNextJarEntry()) != null) {
                        extract(jis, jarEntry, deployDir);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Failed to upload to " + configPath, e);
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JarInputStream(java.util.jar.JarInputStream) JarEntry(java.util.jar.JarEntry) File(java.io.File) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 42 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project zuul by Netflix.

the class FilterScriptManagerServlet method handlePostBody.

private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    org.apache.commons.fileupload.FileItemIterator it = null;
    try {
        it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream stream = it.next();
            InputStream input = stream.openStream();
            // NOTE: we are going to pull the entire stream into memory
            // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
            byte[] uploadedBytes = getBytesFromInputStream(input);
            input.close();
            if (uploadedBytes.length == 0) {
                setUsageError(400, "ERROR: Body contained no data.", response);
                return null;
            }
            return new String(uploadedBytes);
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
    return null;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 43 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project OpenAttestation by OpenAttestation.

the class WLMDataController method uploadManifest.

public ModelAndView uploadManifest(HttpServletRequest req, HttpServletResponse res) {
    log.info("WLMDataController.uploadManifest >>");
    req.getSession().removeAttribute("manifestValue");
    ModelAndView responseView = new ModelAndView(new JSONView());
    List<Map<String, String>> manifestValue = new ArrayList<Map<String, String>>();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    System.out.println(isMultipart);
    if (!isMultipart) {
        responseView.addObject("result", false);
        return responseView;
    }
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                String[] lines = item.getString().split("\\r?\\n");
                for (String values : lines) {
                    if (values.length() > 2) {
                        String[] val = values.split(":");
                        if (val.length == 2) {
                            Map<String, String> manifest = new HashMap<String, String>();
                            manifest.put(val[0], val[1]);
                            manifestValue.add(manifest);
                        } else {
                            responseView.addObject("result", false);
                            return responseView;
                        }
                    }
                }
            }
        }
        log.info("Uploaded Content :: " + manifestValue.toString());
        req.getSession().setAttribute("manifestValue", manifestValue);
        /*responseView.addObject("manifestValue",manifestValue);*/
        responseView.addObject("result", manifestValue.size() > 0 ? true : false);
    } catch (FileUploadException e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    } catch (Exception e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    }
    log.info("WLMDataController.uploadManifest <<<");
    return responseView;
}
Also used : HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException) WLMPortalException(com.intel.mountwilson.common.WLMPortalException) FileItem(org.apache.commons.fileupload.FileItem) JSONView(com.intel.mountwilson.util.JSONView) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) Map(java.util.Map) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 44 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project OpenClinica by OpenClinica.

the class OpenRosaSubmissionController method doFieldDeletion.

/**
     * @api {post} /pages/api/v2/editform/:studyOid/fieldsubmission Submit form data
     * @apiName doSubmission
     * @apiPermission admin
     * @apiVersion 3.8.0
     * @apiParam {String} studyOid Study Oid.
     * @apiParam {String} ecid Key that will be used to look up subject context information while processing submission.
     * @apiGroup Form
     * @apiDescription Submits the data from a completed form.
     */
@RequestMapping(value = "/{studyOID}/fieldsubmission", method = RequestMethod.DELETE)
public ResponseEntity<String> doFieldDeletion(HttpServletRequest request, HttpServletResponse response, @PathVariable("studyOID") String studyOID, @RequestParam(FORM_CONTEXT) String ecid) {
    logger.info("Processing xform field deletion.");
    HashMap<String, String> subjectContext = null;
    Locale locale = LocaleResolver.getLocale(request);
    DataBinder dataBinder = new DataBinder(null);
    Errors errors = dataBinder.getBindingResult();
    Study study = studyDao.findByOcOID(studyOID);
    String requestBody = null;
    String instanceId = null;
    HashMap<String, String> map = new HashMap();
    ArrayList<HashMap> listOfUploadFilePaths = new ArrayList();
    try {
        // Verify Study is allowed to submit
        if (!mayProceed(study)) {
            logger.info("Field Deletions to the study not allowed.  Aborting field submission.");
            return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
        }
        String dir = getAttachedFilePath(studyOID);
        FileProperties fileProperties = new FileProperties();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(fileProperties.getFileSizeMax());
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.getFieldName().equals("instance_id")) {
                instanceId = item.getString();
            } else if (item.getFieldName().equals("xml_submission_fragment_file")) {
                requestBody = item.getString("UTF-8");
            } else if (item.getContentType() != null) {
                if (!new File(dir).exists())
                    new File(dir).mkdirs();
                File file = processUploadedFile(item, dir);
                map.put(item.getFieldName(), file.getPath());
            }
        }
        listOfUploadFilePaths.add(map);
        if (instanceId == null) {
            logger.info("Field Submissions to the study not allowed without a valid instanceId.  Aborting field submission.");
            return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
        }
        // Load user context from ecid
        PFormCache cache = PFormCache.getInstance(context);
        subjectContext = cache.getSubjectContext(ecid);
        // Execute save as Hibernate transaction to avoid partial imports
        openRosaSubmissionService.processFieldSubmissionRequest(study, subjectContext, instanceId, requestBody, errors, locale, listOfUploadFilePaths, SubmissionContainer.FieldRequestTypeEnum.DELETE_FIELD);
    } catch (Exception e) {
        logger.error("Exception while processing xform submission.");
        logger.error(e.getMessage());
        logger.error(ExceptionUtils.getStackTrace(e));
        if (!errors.hasErrors()) {
            // Send a failure response
            logger.info("Submission caused internal error.  Sending error response.");
            return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    if (!errors.hasErrors()) {
        // JsonLog submission with Participate
        if (isParticipantSubmission(subjectContext))
            notifier.notify(studyOID, subjectContext);
        logger.info("Completed xform field submission. Sending successful response");
        String responseMessage = "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">" + "<message>success</message>" + "</OpenRosaResponse>";
        return new ResponseEntity<String>(responseMessage, HttpStatus.CREATED);
    } else {
        logger.info("Field Submission contained errors. Sending error response");
        return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
    }
}
Also used : Locale(java.util.Locale) Study(org.akaza.openclinica.domain.datamap.Study) FileProperties(org.akaza.openclinica.bean.rule.FileProperties) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) Errors(org.springframework.validation.Errors) FileItem(org.apache.commons.fileupload.FileItem) ResponseEntity(org.springframework.http.ResponseEntity) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DataBinder(org.springframework.validation.DataBinder) File(java.io.File) PFormCache(org.akaza.openclinica.web.pform.PFormCache) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 45 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project libresonic by Libresonic.

the class AvatarUploadController method handleRequestInternal.

@RequestMapping(method = RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {
    String username = securityService.getCurrentUsername(request);
    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }
    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);
    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();
            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }
    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult", "model", map);
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)90 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)84 FileItem (org.apache.commons.fileupload.FileItem)72 FileUploadException (org.apache.commons.fileupload.FileUploadException)48 File (java.io.File)44 IOException (java.io.IOException)31 HashMap (java.util.HashMap)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)24 List (java.util.List)21 ArrayList (java.util.ArrayList)20 InputStream (java.io.InputStream)17 ServletException (javax.servlet.ServletException)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)9 Locale (java.util.Locale)8 JSONObject (org.json.JSONObject)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 Iterator (java.util.Iterator)7 Map (java.util.Map)7