Search in sources :

Example 46 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project endpoints-java by cloudendpoints.

the class RestServletRequestParamReader method read.

@Override
public Object[] read() throws ServiceException {
    // TODO: Take charset from content-type as encoding
    try {
        EndpointMethod method = getMethod();
        if (method.getParameterClasses().length == 0) {
            return new Object[0];
        }
        HttpServletRequest servletRequest = endpointsContext.getRequest();
        JsonNode node;
        // this case, each part represents a named parameter instead.
        if (ServletFileUpload.isMultipartContent(servletRequest)) {
            try {
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iter = upload.getItemIterator(servletRequest);
                ObjectNode obj = (ObjectNode) objectReader.createObjectNode();
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        obj.put(item.getFieldName(), IoUtil.readStream(item.openStream()));
                    } else {
                        throw new BadRequestException("unable to parse multipart form field");
                    }
                }
                node = obj;
            } catch (FileUploadException e) {
                throw new BadRequestException("unable to parse multipart request", e);
            }
        } else {
            String requestBody = IoUtil.readRequestBody(servletRequest);
            logger.atFine().log("requestBody=%s", requestBody);
            // Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to
            // path and query parameters being injected into the body), bodies are optional here, so we
            // create an empty body and inject named parameters to make deserialize work.
            node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() : objectReader.readTree(requestBody);
        }
        if (!node.isObject()) {
            throw new BadRequestException("expected a JSON object body");
        }
        ObjectNode body = (ObjectNode) node;
        Map<String, Class<?>> parameterMap = getParameterMap(method);
        // the order of precedence is resource field > query parameter > path parameter.
        for (Enumeration<?> e = servletRequest.getParameterNames(); e.hasMoreElements(); ) {
            String parameterName = (String) e.nextElement();
            if (!body.has(parameterName)) {
                Class<?> parameterClass = parameterMap.get(parameterName);
                ApiParameterConfig parameterConfig = parameterConfigMap.get(parameterName);
                if (parameterClass != null && parameterConfig.isRepeated()) {
                    ArrayNode values = body.putArray(parameterName);
                    for (String value : servletRequest.getParameterValues(parameterName)) {
                        values.add(value);
                    }
                } else {
                    body.put(parameterName, servletRequest.getParameterValues(parameterName)[0]);
                }
            }
        }
        for (Entry<String, String> entry : rawPathParameters.entrySet()) {
            String parameterName = entry.getKey();
            Class<?> parameterClass = parameterMap.get(parameterName);
            if (parameterClass != null && !body.has(parameterName)) {
                if (parameterConfigMap.get(parameterName).isRepeated()) {
                    ArrayNode values = body.putArray(parameterName);
                    for (String value : COMPOSITE_PATH_SPLITTER.split(entry.getValue())) {
                        values.add(value);
                    }
                } else {
                    body.put(parameterName, entry.getValue());
                }
            }
        }
        for (Entry<String, ApiParameterConfig> entry : parameterConfigMap.entrySet()) {
            if (!body.has(entry.getKey()) && entry.getValue().getDefaultValue() != null) {
                body.put(entry.getKey(), entry.getValue().getDefaultValue());
            }
        }
        return deserializeParams(body);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
        logger.atInfo().withCause(e).log("Unable to read request parameter(s)");
        throw new BadRequestException(e);
    }
}
Also used : ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) EndpointMethod(com.google.api.server.spi.EndpointMethod) BadRequestException(com.google.api.server.spi.response.BadRequestException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 47 with FileUploadException

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

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

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

use of org.apache.commons.fileupload.FileUploadException in project sling by apache.

the class ParameterSupport method getRequestParameterMapInternal.

private ParameterMap getRequestParameterMapInternal() {
    if (this.postParameterMap == null) {
        // SLING-508 Try to force servlet container to decode parameters
        // as ISO-8859-1 such that we can recode later
        String encoding = getServletRequest().getCharacterEncoding();
        if (encoding == null) {
            encoding = Util.ENCODING_DIRECT;
            try {
                getServletRequest().setCharacterEncoding(encoding);
            } catch (UnsupportedEncodingException uee) {
                throw new SlingUnsupportedEncodingException(uee);
            }
        }
        // SLING-152 Get parameters from the servlet Container
        ParameterMap parameters = new ParameterMap();
        // fallback is only used if this request has been started by a service call
        boolean useFallback = getServletRequest().getAttribute(MARKER_IS_SERVICE_PROCESSING) != null;
        boolean addContainerParameters = false;
        // Query String
        final String query = getServletRequest().getQueryString();
        if (query != null) {
            try {
                InputStream input = Util.toInputStream(query);
                Util.parseQueryString(input, encoding, parameters, false);
                addContainerParameters = checkForAdditionalParameters;
            } catch (IllegalArgumentException e) {
                this.log.error("getRequestParameterMapInternal: Error parsing request", e);
            } catch (UnsupportedEncodingException e) {
                throw new SlingUnsupportedEncodingException(e);
            } catch (IOException e) {
                this.log.error("getRequestParameterMapInternal: Error parsing request", e);
            }
            useFallback = false;
        } else {
            addContainerParameters = checkForAdditionalParameters;
            useFallback = true;
        }
        // POST requests
        final boolean isPost = "POST".equals(this.getServletRequest().getMethod());
        if (isPost) {
            // WWW URL Form Encoded POST
            if (isWWWFormEncodedContent(this.getServletRequest())) {
                try {
                    InputStream input = this.getServletRequest().getInputStream();
                    Util.parseQueryString(input, encoding, parameters, false);
                    addContainerParameters = checkForAdditionalParameters;
                } catch (IllegalArgumentException e) {
                    this.log.error("getRequestParameterMapInternal: Error parsing request", e);
                } catch (UnsupportedEncodingException e) {
                    throw new SlingUnsupportedEncodingException(e);
                } catch (IOException e) {
                    this.log.error("getRequestParameterMapInternal: Error parsing request", e);
                }
                this.requestDataUsed = true;
                useFallback = false;
            }
            // Multipart POST
            if (ServletFileUpload.isMultipartContent(new ServletRequestContext(this.getServletRequest()))) {
                if (isStreamed(parameters, this.getServletRequest())) {
                    // special case, the request is Multipart and streamed processing has been requested
                    try {
                        this.getServletRequest().setAttribute(REQUEST_PARTS_ITERATOR_ATTRIBUTE, new RequestPartsIterator(this.getServletRequest()));
                        this.log.debug("getRequestParameterMapInternal: Iterator<javax.servlet.http.Part> available as request attribute named request-parts-iterator");
                    } catch (IOException e) {
                        this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
                    } catch (FileUploadException e) {
                        this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
                    }
                    // The request data has been passed to the RequestPartsIterator, hence from a RequestParameter pov its been used, and must not be used again.
                    this.requestDataUsed = true;
                    // must not try and get anything from the request at this point so avoid jumping through the stream.
                    addContainerParameters = false;
                    useFallback = false;
                } else {
                    this.parseMultiPartPost(parameters);
                    this.requestDataUsed = true;
                    addContainerParameters = checkForAdditionalParameters;
                    useFallback = false;
                }
            }
        }
        if (useFallback) {
            getContainerParameters(parameters, encoding, true);
        } else if (addContainerParameters) {
            getContainerParameters(parameters, encoding, false);
        }
        // apply any form encoding (from '_charset_') in the parameter map
        Util.fixEncoding(parameters);
        this.postParameterMap = parameters;
    }
    return this.postParameterMap;
}
Also used : InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)88 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)65 FileItem (org.apache.commons.fileupload.FileItem)57 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)51 IOException (java.io.IOException)37 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)22 List (java.util.List)21 File (java.io.File)20 InputStream (java.io.InputStream)19 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)19 FileItemStream (org.apache.commons.fileupload.FileItemStream)19 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)16 ServletException (javax.servlet.ServletException)12 Map (java.util.Map)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 Iterator (java.util.Iterator)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6