Example usage for org.springframework.web.multipart MultipartHttpServletRequest getParameterMap

List of usage examples for org.springframework.web.multipart MultipartHttpServletRequest getParameterMap

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartHttpServletRequest getParameterMap.

Prototype

public Map<String, String[]> getParameterMap();

Source Link

Document

Returns a java.util.Map of the parameters of this request.

Usage

From source file:com.myhexin.filter.FileMultipartFilter.java

private void recordXssRequestInfo(MultipartHttpServletRequest mRequest, String illegalParam) {
    Map<String, Object> submitParams = mRequest.getParameterMap();// get
    // post??// w  w  w.  ja v  a 2  s .c  o  m
    Set<String> paramName = submitParams.keySet();

    String requestURL = mRequest.getRequestURL().toString();
    String questMethod = mRequest.getMethod();
    StringBuffer buffer = new StringBuffer();
    for (String pn : paramName) {
        Object paramValues = submitParams.get(pn);

        if (paramValues instanceof String[]) {
            buffer.append(pn + "=");
            for (String submitValue : (String[]) paramValues) {
                buffer.append(submitValue + " ");
            }
            buffer.append(" \\ ");
        } else {
            buffer.append(pn + "=" + paramValues + " \\ ");
        }
    }
    logger.warn("mulipart !!! " + questMethod + " " + requestURL + "  ==" + buffer.toString()
            + " illegal param   " + illegalParam);
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/asyncUpload2", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody//  w w w  .  j  a  v  a  2s .  c  o m
public ResponseEntity<String> asyncFileUpload2(HttpServletRequest request) throws Exception {
    MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
    if (request instanceof MultipartHttpServletRequest) {
        CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("fileUpload");
        List<MultipartFile> fs = (List<MultipartFile>) mpr.getFiles("fileUpload");
        System.out.println("f: " + f);

        for (String key : mpr.getParameterMap().keySet()) {
            System.out.println("Param Key: " + key + "\n Value: " + mpr.getParameterMap().get(key));
        }

        for (String key : mpr.getMultiFileMap().keySet()) {
            System.out.println("xParam Key: " + key + "\n xValue: " + mpr.getMultiFileMap().get(key));
        }

    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    Map<String, Object> parameterMap = new HashMap<>();
    Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");

    //if(request.getContentType().contains("multipart/form-data")){ 

    if (ServletFileUpload.isMultipartContent(request)) {
        Map<String, Object> map = new HashMap<>();
        List<FileItem> filefields = new ArrayList<>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) { //contentType: "image/jpeg", isFormField: false, fileName: "Chrysanthemum.jpg"
            if (item.isFormField()) {
                formfields.put(item.getFieldName(), item.getString());
            } else {
                filefields.add(item);
            }
        }

        parameterMap.put("filefields", filefields);
    }

    return new ResponseEntity<>("success", HttpStatus.OK);
}

From source file:eionet.webq.web.controller.WebQProxyDelegation.java

/**
 * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used.
 *
 * @param uri              the address to forward the request
 * @param fileId           UserFile id stored in session
 * @param multipartRequest file part in multipart request
 * @return response from remote host//  ww  w . java  2 s  .c  om
 * @throws URISyntaxException provide URI is incorrect
 * @throws IOException        could not read file from request
 */
@RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId,
        MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException {

    UserFile file = userFileHelper.getUserFile(fileId, multipartRequest);

    if (!multipartRequest.getFileNames().hasNext()) {
        throw new IllegalArgumentException("File not found in multipart request.");
    }
    Map<String, String[]> parameters = multipartRequest.getParameterMap();
    // limit request to one file
    String fileName = multipartRequest.getFileNames().next();
    MultipartFile multipartFile = multipartRequest.getFile(fileName);

    HttpHeaders authorization = new HttpHeaders();
    if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) {
        authorization = envelopeService.getAuthorizationHeader(file);
    }

    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename());
    fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType()));

    MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
    byte[] content = multipartFile.getBytes();
    request.add("file", new HttpEntity<byte[]>(content, fileHeaders));
    for (Map.Entry<String, String[]> parameter : parameters.entrySet()) {
        if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId")
                && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) {
            request.add(parameter.getKey(),
                    new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0])));
        }
    }

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(
            request, authorization);

    LOGGER.info("/restProxyFileUpload [POST] uri=" + uri);
    return restTemplate.postForObject(uri, requestEntity, String.class);
}

From source file:com.myhexin.filter.FileMultipartFilter.java

/**
 * //from w  w w.j a va 2 s . com
 * @param mRequest
 * @return true:??false?
 */
public boolean isIlleageXssParam(MultipartHttpServletRequest mRequest) {

    // headerheader?
    if (XSSSecurityConfig.IS_CHECK_HEADER) {
        Enumeration<String> headerParams = mRequest.getHeaderNames();
        while (headerParams.hasMoreElements()) {
            String headerName = headerParams.nextElement();
            String headerValue = mRequest.getHeader(headerName);
            if (XSSSecurityManager.matches(headerValue)) {
                recordXssRequestInfo(mRequest, headerValue);
                return true;
            }
        }
        return false;
    }

    // parameterparameter?
    if (XSSSecurityConfig.IS_CHECK_PARAMETER) {
        Map<String, Object> submitParams = mRequest.getParameterMap();
        Set<String> submitNames = submitParams.keySet();
        for (String submitName : submitNames) {
            Object submitValues = submitParams.get(submitName);
            if (submitValues instanceof String) {
                if (XSSSecurityManager.matches((String) submitValues)) {
                    recordXssRequestInfo(mRequest, submitName + "=" + submitValues);
                    return true;
                }
            } else if (submitValues instanceof String[]) {
                for (String submitValue : (String[]) submitValues) {
                    if (XSSSecurityManager.matches((String) submitValue)) {
                        recordXssRequestInfo(mRequest, submitName + "" + submitValue);
                        return true;
                    }
                }
            }
        }
        return false;
    }
    return false;
}

From source file:org.flowable.cmmn.rest.service.api.runtime.caze.BaseVariableResource.java

protected RestVariable setBinaryVariable(MultipartHttpServletRequest request, CaseInstance caseInstance,
        int responseVariableType, boolean isNew) {

    // Validate input and set defaults
    if (request.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }// ww  w.  j ava 2 s .c om

    // Get first file in the map, ignore possible other files
    MultipartFile file = request.getFile(request.getFileMap().keySet().iterator().next());

    if (file == null) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }

    String variableScope = null;
    String variableName = null;
    String variableType = null;

    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {

        if (paramMap.get(parameterName).length > 0) {

            if (parameterName.equalsIgnoreCase("scope")) {
                variableScope = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("name")) {
                variableName = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("type")) {
                variableType = paramMap.get(parameterName)[0];
            }
        }
    }

    try {

        // Validate input and set defaults
        if (variableName == null) {
            throw new FlowableIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !CmmnRestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new FlowableIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariableScope scope = RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            byte[] variableBytes = IOUtils.toByteArray(file.getInputStream());
            setVariable(caseInstance, variableName, variableBytes, scope, isNew);

        } else if (isSerializableVariableAllowed) {
            // Try deserializing the object
            ObjectInputStream stream = new ObjectInputStream(file.getInputStream());
            Object value = stream.readObject();
            setVariable(caseInstance, variableName, value, scope, isNew);
            stream.close();
        } else {
            throw new FlowableContentNotSupportedException("Serialized objects are not allowed");
        }

        return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null,
                caseInstance.getId());

    } catch (IOException ioe) {
        throw new FlowableIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new FlowableContentNotSupportedException(
                "The provided body contains a serialized object for which the class was not found: "
                        + ioe.getMessage());
    }

}

From source file:org.flowable.cmmn.rest.service.api.runtime.task.TaskVariableBaseResource.java

protected RestVariable setBinaryVariable(MultipartHttpServletRequest request, Task task, boolean isNew) {

    // Validate input and set defaults
    if (request.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }/*from  ww  w.j a v a  2 s.  c  o  m*/

    // Get first file in the map, ignore possible other files
    MultipartFile file = request.getFile(request.getFileMap().keySet().iterator().next());

    if (file == null) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }

    String variableScope = null;
    String variableName = null;
    String variableType = null;

    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {

        if (paramMap.get(parameterName).length > 0) {

            if (parameterName.equalsIgnoreCase("scope")) {
                variableScope = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("name")) {
                variableName = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("type")) {
                variableType = paramMap.get(parameterName)[0];
            }
        }
    }

    try {

        if (variableName == null) {
            throw new FlowableIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !CmmnRestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new FlowableIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariableScope scope = RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            byte[] variableBytes = IOUtils.toByteArray(file.getInputStream());
            setVariable(task, variableName, variableBytes, scope, isNew);

        } else if (isSerializableVariableAllowed) {
            // Try deserializing the object
            ObjectInputStream stream = new ObjectInputStream(file.getInputStream());
            Object value = stream.readObject();
            setVariable(task, variableName, value, scope, isNew);
            stream.close();

        } else {
            throw new FlowableContentNotSupportedException("Serialized objects are not allowed");
        }

        return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, task.getId(),
                null);

    } catch (IOException ioe) {
        throw new FlowableIllegalArgumentException("Error getting binary variable", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new FlowableContentNotSupportedException(
                "The provided body contains a serialized object for which the class was not found: "
                        + ioe.getMessage());
    }

}

From source file:org.flowable.rest.service.api.runtime.process.BaseExecutionVariableResource.java

protected RestVariable setBinaryVariable(MultipartHttpServletRequest request, Execution execution,
        int responseVariableType, boolean isNew) {

    // Validate input and set defaults
    if (request.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }/*from  ww w  .  j  av  a2  s . com*/

    // Get first file in the map, ignore possible other files
    MultipartFile file = request.getFile(request.getFileMap().keySet().iterator().next());

    if (file == null) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }

    String variableScope = null;
    String variableName = null;
    String variableType = null;

    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {

        if (paramMap.get(parameterName).length > 0) {

            if (parameterName.equalsIgnoreCase("scope")) {
                variableScope = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("name")) {
                variableName = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("type")) {
                variableType = paramMap.get(parameterName)[0];
            }
        }
    }

    try {

        // Validate input and set defaults
        if (variableName == null) {
            throw new FlowableIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new FlowableIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariableScope scope = RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            byte[] variableBytes = IOUtils.toByteArray(file.getInputStream());
            setVariable(execution, variableName, variableBytes, scope, isNew);

        } else if (isSerializableVariableAllowed) {
            // Try deserializing the object
            ObjectInputStream stream = new ObjectInputStream(file.getInputStream());
            Object value = stream.readObject();
            setVariable(execution, variableName, value, scope, isNew);
            stream.close();
        } else {
            throw new FlowableContentNotSupportedException("Serialized objects are not allowed");
        }

        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null, null,
                    execution.getId());
        } else {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null,
                    execution.getId(), null);
        }

    } catch (IOException ioe) {
        throw new FlowableIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new FlowableContentNotSupportedException(
                "The provided body contains a serialized object for which the class is nog found: "
                        + ioe.getMessage());
    }

}

From source file:org.flowable.rest.service.api.runtime.task.TaskVariableBaseResource.java

protected RestVariable setBinaryVariable(MultipartHttpServletRequest request, Task task, boolean isNew) {

    // Validate input and set defaults
    if (request.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }/*  w  w  w.  j  ava  2  s .c o m*/

    // Get first file in the map, ignore possible other files
    MultipartFile file = request.getFile(request.getFileMap().keySet().iterator().next());

    if (file == null) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }

    String variableScope = null;
    String variableName = null;
    String variableType = null;

    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {

        if (paramMap.get(parameterName).length > 0) {

            if (parameterName.equalsIgnoreCase("scope")) {
                variableScope = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("name")) {
                variableName = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("type")) {
                variableType = paramMap.get(parameterName)[0];
            }
        }
    }

    try {

        if (variableName == null) {
            throw new FlowableIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new FlowableIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariableScope scope = RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            byte[] variableBytes = IOUtils.toByteArray(file.getInputStream());
            setVariable(task, variableName, variableBytes, scope, isNew);

        } else if (isSerializableVariableAllowed) {
            // Try deserializing the object
            ObjectInputStream stream = new ObjectInputStream(file.getInputStream());
            Object value = stream.readObject();
            setVariable(task, variableName, value, scope, isNew);
            stream.close();

        } else {
            throw new FlowableContentNotSupportedException("Serialized objects are not allowed");
        }

        return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, task.getId(),
                null, null);

    } catch (IOException ioe) {
        throw new FlowableIllegalArgumentException("Error getting binary variable", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new FlowableContentNotSupportedException(
                "The provided body contains a serialized object for which the class is nog found: "
                        + ioe.getMessage());
    }

}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

@SuppressWarnings("unchecked")
private Object createPayloadFromMultipartRequest(MultipartHttpServletRequest multipartRequest) {
    Map<String, Object> payloadMap = new HashMap<String, Object>(multipartRequest.getParameterMap());
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
        MultipartFile multipartFile = entry.getValue();
        if (multipartFile.isEmpty()) {
            continue;
        }//from   ww w.j a v a  2s.c o m
        try {
            if (this.copyUploadedFiles) {
                File tmpFile = File.createTempFile("si_", null);
                multipartFile.transferTo(tmpFile);
                payloadMap.put(entry.getKey(), tmpFile);
                if (logger.isDebugEnabled()) {
                    logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename()
                            + "] to temporary file [" + tmpFile.getAbsolutePath() + "]");
                }
            } else if (multipartFile.getContentType() != null
                    && multipartFile.getContentType().startsWith("text")) {
                String multipartFileAsString = this.multipartCharset != null
                        ? new String(multipartFile.getBytes(), this.multipartCharset)
                        : new String(multipartFile.getBytes());
                payloadMap.put(entry.getKey(), multipartFileAsString);
            } else {
                payloadMap.put(entry.getKey(), multipartFile.getBytes());
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read contents of multipart file", e);
        }
    }
    return Collections.unmodifiableMap(payloadMap);
}

From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java

private void doTestParameters(MultipartHttpServletRequest request) {
    Set<String> parameterNames = new HashSet<>();
    Enumeration<String> parameterEnum = request.getParameterNames();
    while (parameterEnum.hasMoreElements()) {
        parameterNames.add(parameterEnum.nextElement());
    }/*from w w  w  .  j av a2  s.  c om*/
    assertEquals(3, parameterNames.size());
    assertTrue(parameterNames.contains("field3"));
    assertTrue(parameterNames.contains("field4"));
    assertTrue(parameterNames.contains("getField"));
    assertEquals("value3", request.getParameter("field3"));
    List<String> parameterValues = Arrays.asList(request.getParameterValues("field3"));
    assertEquals(1, parameterValues.size());
    assertTrue(parameterValues.contains("value3"));
    assertEquals("value4", request.getParameter("field4"));
    parameterValues = Arrays.asList(request.getParameterValues("field4"));
    assertEquals(2, parameterValues.size());
    assertTrue(parameterValues.contains("value4"));
    assertTrue(parameterValues.contains("value5"));
    assertEquals("value4", request.getParameter("field4"));
    assertEquals("getValue", request.getParameter("getField"));

    List<String> parameterMapKeys = new ArrayList<>();
    List<Object> parameterMapValues = new ArrayList<>();
    for (Object o : request.getParameterMap().keySet()) {
        String key = (String) o;
        parameterMapKeys.add(key);
        parameterMapValues.add(request.getParameterMap().get(key));
    }
    assertEquals(3, parameterMapKeys.size());
    assertEquals(3, parameterMapValues.size());
    int field3Index = parameterMapKeys.indexOf("field3");
    int field4Index = parameterMapKeys.indexOf("field4");
    int getFieldIndex = parameterMapKeys.indexOf("getField");
    assertTrue(field3Index != -1);
    assertTrue(field4Index != -1);
    assertTrue(getFieldIndex != -1);
    parameterValues = Arrays.asList((String[]) parameterMapValues.get(field3Index));
    assertEquals(1, parameterValues.size());
    assertTrue(parameterValues.contains("value3"));
    parameterValues = Arrays.asList((String[]) parameterMapValues.get(field4Index));
    assertEquals(2, parameterValues.size());
    assertTrue(parameterValues.contains("value4"));
    assertTrue(parameterValues.contains("value5"));
    parameterValues = Arrays.asList((String[]) parameterMapValues.get(getFieldIndex));
    assertEquals(1, parameterValues.size());
    assertTrue(parameterValues.contains("getValue"));
}