Search in sources :

Example 81 with FileItem

use of org.apache.commons.fileupload.FileItem 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 82 with FileItem

use of org.apache.commons.fileupload.FileItem in project sonarqube by SonarSource.

the class CommonsMultipartRequestHandler method handleRequest.

/**
     * <p> Parses the input stream and partitions the parsed items into a set
     * of form fields and a set of file items. In the process, the parsed
     * items are translated from Commons FileUpload <code>FileItem</code>
     * instances to Struts <code>FormFile</code> instances. </p>
     *
     * @param request The multipart request to be processed.
     * @throws ServletException if an unrecoverable error occurs.
     */
public void handleRequest(HttpServletRequest request) throws ServletException {
    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
    // Create and configure a DIskFileUpload instance.
    DiskFileUpload upload = new DiskFileUpload();
    // The following line is to support an "EncodingFilter"
    // see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold(ac));
    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(ac));
    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();
    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }
    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) DiskFileUpload(org.apache.commons.fileupload.DiskFileUpload) Hashtable(java.util.Hashtable) Iterator(java.util.Iterator) ModuleConfig(org.apache.struts.config.ModuleConfig) ArrayList(java.util.ArrayList) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 83 with FileItem

use of org.apache.commons.fileupload.FileItem 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 84 with FileItem

use of org.apache.commons.fileupload.FileItem 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 85 with FileItem

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

the class UploadController method handleRequestInternal.

@RequestMapping(method = { RequestMethod.POST })
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<>();
    List<File> uploadedFiles = new ArrayList<>();
    List<File> unzippedFiles = new ArrayList<>();
    TransferStatus status = null;
    try {
        status = statusService.createUploadStatus(playerService.getPlayer(request, response, false, false));
        status.setBytesTotal(request.getContentLength());
        request.getSession().setAttribute(UPLOAD_STATUS, status);
        // Check that we have a file upload request
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new Exception("Illegal request.");
        }
        File dir = null;
        boolean unzip = false;
        UploadListener listener = new UploadListenerImpl(status);
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<?> items = upload.parseRequest(request);
        // First, look for "dir" and "unzip" parameters.
        for (Object o : items) {
            FileItem item = (FileItem) o;
            if (item.isFormField() && "dir".equals(item.getFieldName())) {
                dir = new File(item.getString());
            } else if (item.isFormField() && "unzip".equals(item.getFieldName())) {
                unzip = true;
            }
        }
        if (dir == null) {
            throw new Exception("Missing 'dir' parameter.");
        }
        // Look for file items.
        for (Object o : items) {
            FileItem item = (FileItem) o;
            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName.trim().length() > 0) {
                    File targetFile = new File(dir, new File(fileName).getName());
                    if (!securityService.isUploadAllowed(targetFile)) {
                        throw new Exception("Permission denied: " + StringUtil.toHtml(targetFile.getPath()));
                    }
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    item.write(targetFile);
                    uploadedFiles.add(targetFile);
                    LOG.info("Uploaded " + targetFile);
                    if (unzip && targetFile.getName().toLowerCase().endsWith(".zip")) {
                        unzip(targetFile, unzippedFiles);
                    }
                }
            }
        }
    } catch (Exception x) {
        LOG.warn("Uploading failed.", x);
        map.put("exception", x);
    } finally {
        if (status != null) {
            statusService.removeUploadStatus(status);
            request.getSession().removeAttribute(UPLOAD_STATUS);
            User user = securityService.getCurrentUser(request);
            securityService.updateUserByteCounts(user, 0L, 0L, status.getBytesTransfered());
        }
    }
    map.put("uploadedFiles", uploadedFiles);
    map.put("unzippedFiles", unzippedFiles);
    return new ModelAndView("upload", "model", map);
}
Also used : User(org.libresonic.player.domain.User) ModelAndView(org.springframework.web.servlet.ModelAndView) UploadListener(org.libresonic.player.upload.UploadListener) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) MonitoredDiskFileItemFactory(org.libresonic.player.upload.MonitoredDiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) TransferStatus(org.libresonic.player.domain.TransferStatus) MonitoredDiskFileItemFactory(org.libresonic.player.upload.MonitoredDiskFileItemFactory) ZipFile(org.apache.tools.zip.ZipFile) File(java.io.File) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

FileItem (org.apache.commons.fileupload.FileItem)165 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)78 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)72 FileUploadException (org.apache.commons.fileupload.FileUploadException)59 File (java.io.File)55 IOException (java.io.IOException)51 ArrayList (java.util.ArrayList)40 HashMap (java.util.HashMap)32 ServletException (javax.servlet.ServletException)30 List (java.util.List)27 InputStream (java.io.InputStream)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)23 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)16 Map (java.util.Map)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)10 Test (org.junit.Test)10 Iterator (java.util.Iterator)9 FileItemWrap (com.github.bordertech.wcomponents.file.FileItemWrap)8 Locale (java.util.Locale)8