Search in sources :

Example 66 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project com.revolsys.open by revolsys.

the class WebMethodHandler method requestParameter.

public static WebParameterHandler requestParameter(final WebAnnotationMethodHandlerAdapter adapter, final Parameter parameter, final Annotation annotation) {
    final RequestParam requestParam = (RequestParam) annotation;
    final String name = getName(parameter, requestParam.value());
    final boolean required = requestParam.required();
    final String defaultValueString = requestParam.defaultValue();
    final Class<?> parameterClass = parameter.getType();
    final DataType dataType = DataTypes.getDataType(parameterClass);
    BiFunction<HttpServletRequest, HttpServletResponse, Object> function;
    Object defaultValue = null;
    if (List.class.equals(parameterClass)) {
        if (ValueConstants.DEFAULT_NONE.equals(defaultValueString)) {
            final ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
            final Type[] typeParameters = parameterizedType.getActualTypeArguments();
            final Type elementType = typeParameters[0];
            if (MultipartFile.class.equals(elementType)) {
                function = (request, response) -> {
                    if (request instanceof MultipartRequest) {
                        final MultipartRequest multipartRequest = (MultipartRequest) request;
                        return multipartRequest.getFiles(name);
                    } else {
                        return Collections.emptyList();
                    }
                };
            } else {
                final DataType elementDataType = DataTypes.getDataType(elementType);
                function = (request, response) -> {
                    final List<Object> list = new ArrayList<>();
                    final String[] parameterValues = request.getParameterValues(name);
                    if (parameterValues != null) {
                        for (final String stringValue : parameterValues) {
                            final Object value = elementDataType.toObject(stringValue);
                            list.add(value);
                        }
                    }
                    return list;
                };
            }
        } else {
            throw new IllegalArgumentException("RequestParam.defaultValue not allowed for " + name);
        }
    } else if (parameterClass.isArray()) {
        if (ValueConstants.DEFAULT_NONE.equals(defaultValueString)) {
            final Class<?> elementClass = parameterClass.getComponentType();
            if (MultipartFile.class.equals(elementClass)) {
                function = (request, response) -> {
                    if (request instanceof MultipartRequest) {
                        final MultipartRequest multipartRequest = (MultipartRequest) request;
                        final List<MultipartFile> files = multipartRequest.getFiles(name);
                        return files.toArray();
                    } else {
                        return new MultipartFile[0];
                    }
                };
            } else {
                final DataType elementDataType = DataTypes.getDataType(elementClass);
                function = (request, response) -> {
                    final String[] parameterValues = request.getParameterValues(name);
                    int length;
                    if (parameterValues == null) {
                        length = 0;
                    } else {
                        length = parameterValues.length;
                    }
                    final Object array = Array.newInstance(elementClass, length);
                    for (int i = 0; i < length; i++) {
                        final String stringValue = parameterValues[i];
                        final Object value = elementDataType.toObject(stringValue);
                        Array.set(array, i, value);
                    }
                    return array;
                };
            }
        } else {
            throw new IllegalArgumentException("RequestParam.defaultValue not allowed for " + name);
        }
    } else {
        defaultValue = parseDefaultValueAttribute(dataType, defaultValueString);
        if (MultipartFile.class.equals(parameterClass)) {
            function = (request, response) -> {
                if (request instanceof MultipartRequest) {
                    final MultipartRequest multipartRequest = (MultipartRequest) request;
                    return multipartRequest.getFile(name);
                } else {
                    return null;
                }
            };
        } else {
            function = (request, response) -> {
                return request.getParameter(name);
            };
        }
    }
    return // 
    WebParameterHandler.function(// 
    name, // 
    function, // 
    dataType, // 
    required, // 
    defaultValue);
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) WrappedException(com.revolsys.util.WrappedException) RequestParam(org.springframework.web.bind.annotation.RequestParam) Array(java.lang.reflect.Array) URLDecoder(java.net.URLDecoder) BiFunction(java.util.function.BiFunction) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) Property(com.revolsys.util.Property) CookieValue(org.springframework.web.bind.annotation.CookieValue) RequestContextUtils(org.springframework.web.servlet.support.RequestContextUtils) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) Map(java.util.Map) MultipartRequest(org.springframework.web.multipart.MultipartRequest) Method(java.lang.reflect.Method) HttpSession(javax.servlet.http.HttpSession) WebUtils(org.springframework.web.util.WebUtils) ClassUtils(org.springframework.util.ClassUtils) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) StandardCharsets(java.nio.charset.StandardCharsets) Logs(com.revolsys.logging.Logs) List(java.util.List) Principal(java.security.Principal) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HandlerMapping(org.springframework.web.servlet.HandlerMapping) Type(java.lang.reflect.Type) ServletResponse(javax.servlet.ServletResponse) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) Annotation(java.lang.annotation.Annotation) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) FileCopyUtils(org.springframework.util.FileCopyUtils) Exceptions(com.revolsys.util.Exceptions) HashMap(java.util.HashMap) HttpServletUtils(com.revolsys.ui.web.utils.HttpServletUtils) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) Charset(java.nio.charset.Charset) Parameter(java.lang.reflect.Parameter) Cookie(javax.servlet.http.Cookie) OutputStream(java.io.OutputStream) ServletRequest(javax.servlet.ServletRequest) RequestAttribute(com.revolsys.ui.web.annotation.RequestAttribute) HttpServletResponse(javax.servlet.http.HttpServletResponse) MultiValueMap(org.springframework.util.MultiValueMap) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) DataTypes(com.revolsys.datatype.DataTypes) Reader(com.revolsys.io.Reader) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) Function3(com.revolsys.util.function.Function3) HttpInputMessage(org.springframework.http.HttpInputMessage) ParameterizedType(java.lang.reflect.ParameterizedType) MultipartFile(org.springframework.web.multipart.MultipartFile) Writer(com.revolsys.io.Writer) ValueConstants(org.springframework.web.bind.annotation.ValueConstants) DataType(com.revolsys.datatype.DataType) Collections(java.util.Collections) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) InputStream(java.io.InputStream) StringUtils(org.springframework.util.StringUtils) RequestParam(org.springframework.web.bind.annotation.RequestParam) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ParameterizedType(java.lang.reflect.ParameterizedType) MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) ParameterizedType(java.lang.reflect.ParameterizedType) DataType(com.revolsys.datatype.DataType) MultipartFile(org.springframework.web.multipart.MultipartFile) DataType(com.revolsys.datatype.DataType) List(java.util.List) ArrayList(java.util.ArrayList) MultipartRequest(org.springframework.web.multipart.MultipartRequest)

Example 67 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method uploadWithPath.

@ApiOperation(value = "Upload a file to a store with a path", notes = "Must have write access to the store")
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/{name}/**")
public ResponseEntity<List<FileModel>> uploadWithPath(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("name") String name, @AuthenticationPrincipal User user, @RequestParam(required = false, defaultValue = "false") boolean overwrite, MultipartHttpServletRequest multipartRequest, HttpServletRequest request) throws IOException {
    FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(name);
    if (def == null)
        throw new NotFoundRestException();
    // Check Permissions
    def.ensureStoreWritePermission(user);
    String pathInStore = parsePath(request);
    File root = def.getRoot().getCanonicalFile();
    Path rootPath = root.toPath();
    File outputDirectory = new File(root, pathInStore).getCanonicalFile();
    if (!outputDirectory.toPath().startsWith(rootPath)) {
        throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", pathInStore));
    }
    if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
    }
    if (!outputDirectory.exists()) {
        if (!outputDirectory.mkdirs())
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
    }
    // Put the file where it belongs
    List<FileModel> fileModels = new ArrayList<>();
    MultiValueMap<String, MultipartFile> filemap = multipartRequest.getMultiFileMap();
    for (String nameField : filemap.keySet()) {
        for (MultipartFile file : filemap.get(nameField)) {
            String filename;
            if (file instanceof CommonsMultipartFile) {
                FileItem fileItem = ((CommonsMultipartFile) file).getFileItem();
                filename = fileItem.getName();
            } else {
                filename = file.getName();
            }
            File newFile = findUniqueFileName(outputDirectory, filename, overwrite);
            File parent = newFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            try (OutputStream output = new FileOutputStream(newFile, false)) {
                try (InputStream input = file.getInputStream()) {
                    StreamUtils.copy(input, output);
                }
            }
            fileModels.add(fileToModel(newFile, root, request.getServletContext()));
        }
    }
    return new ResponseEntity<>(fileModels, HttpStatus.OK);
}
Also used : Path(java.nio.file.Path) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) FileItem(org.apache.commons.fileupload.FileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) FileOutputStream(java.io.FileOutputStream) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 68 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project ma-modules-public by infiniteautomation.

the class JsonEmportV2Controller method uploadConfigurationFile.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Upload 1 configuration json file", notes = "Files should only contain the json object to be imported")
@RequestMapping(method = RequestMethod.POST, value = "/upload-file", consumes = { "multipart/form-data", "multipart/form-data;boundary=-----SWAG_BOUND" })
public ResponseEntity<ImportStatusProvider> uploadConfigurationFile(MultipartHttpServletRequest multipartRequest, UriComponentsBuilder builder, HttpServletRequest request, @ApiParam(value = "timeout for Status Resource to Expire, defaults to 5 minutes", required = false, allowMultiple = false) @RequestParam(value = "timeout", required = false) Long timeout, @AuthenticationPrincipal User user) throws RestValidationFailedException, IOException, JsonException {
    Map<String, MultipartFile> map = multipartRequest.getFileMap();
    if (map.size() != 1)
        throw new BadRequestException(new TranslatableMessage("rest.error.oneFileOnly"));
    Iterator<String> itr = multipartRequest.getFileNames();
    MultipartFile file = multipartRequest.getFile(itr.next());
    if (!file.isEmpty()) {
        JsonReader jr = new JsonReader(Common.JSON_CONTEXT, new String(file.getBytes()));
        JsonObject jo = jr.read(JsonObject.class);
        String resourceId = importStatusResources.generateResourceId();
        ImportStatusProvider statusProvider = new ImportStatusProvider(importStatusResources, resourceId, websocket, timeout, jo, user);
        // Setup the Temporary Resource
        this.importStatusResources.put(resourceId, statusProvider);
        URI location = builder.path("/v2/json-emport/import/{id}").buildAndExpand(resourceId).toUri();
        return getResourceCreated(statusProvider, location);
    } else {
        throw new BadRequestException(new TranslatableMessage("rest.error.noFileProvided"));
    }
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) JsonReader(com.serotonin.json.JsonReader) JsonObject(com.serotonin.json.type.JsonObject) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 69 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project Gemma by PavlidisLab.

the class FileUploadController method handleRequestInternal.

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
    if (!(request instanceof MultipartHttpServletRequest)) {
        return null;
    }
    Map<String, Object> model = new HashMap<>();
    if (request instanceof FailedMultipartHttpServletRequest) {
        String errorMessage = ((FailedMultipartHttpServletRequest) request).getErrorMessage();
        model.put("success", false);
        model.put("error", errorMessage);
    } else {
        MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = mrequest.getFileMap();
        if (fileMap.size() > 1) {
            FileUploadController.log.error("Attempted to upload multiple files, returning error");
            model.put("success", false);
            model.put("error", "Sorry, can't upload more than one file at a time yet");
        }
        for (String key : fileMap.keySet()) {
            MultipartFile multipartFile = fileMap.get(key);
            File copiedFile = null;
            try {
                copiedFile = FileUploadUtil.copyUploadedFile(multipartFile, request);
                FileUploadController.log.info("Uploaded file: " + copiedFile);
                model.put("success", true);
                model.put("localFile", StringEscapeUtils.escapeJava(copiedFile.getAbsolutePath()));
                model.put("originalFile", multipartFile.getOriginalFilename());
                model.put("size", multipartFile.getSize());
            } catch (Exception e) {
                FileUploadController.log.error("Error in upload: " + e.getMessage(), e);
                model.put("success", false);
                model.put("error", e.getMessage());
            }
            if (copiedFile == null) {
                FileUploadController.log.error("Error in upload: unknown problem getting file");
                model.put("success", false);
                model.put("error", "unknown problem getting file");
            }
        }
    }
    return new ModelAndView(new JSONView("text/html; charset=utf-8"), model);
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) JSONView(ubic.gemma.web.view.JSONView) FailedMultipartHttpServletRequest(ubic.gemma.web.util.upload.FailedMultipartHttpServletRequest) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) FailedMultipartHttpServletRequest(ubic.gemma.web.util.upload.FailedMultipartHttpServletRequest)

Example 70 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project molgenis by molgenis.

the class ImportWizardControllerTest method createMultipartFile.

private MultipartFile createMultipartFile(String filename) throws IOException {
    File file = new File("/src/test/resources/" + filename);
    DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(), file.getParentFile());
    fileItem.getOutputStream();
    return new CommonsMultipartFile(fileItem);
}
Also used : File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile)

Aggregations

MultipartFile (org.springframework.web.multipart.MultipartFile)272 File (java.io.File)151 IOException (java.io.IOException)71 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)71 MockMultipartFile (org.springframework.mock.web.MockMultipartFile)53 Test (org.junit.Test)41 FileInputStream (java.io.FileInputStream)37 ArrayList (java.util.ArrayList)30 JobConfig4DB (com.vip.saturn.job.console.mybatis.entity.JobConfig4DB)28 Test (org.junit.jupiter.api.Test)27 InputStream (java.io.InputStream)25 MultipartHttpServletRequest (org.springframework.web.multipart.MultipartHttpServletRequest)24 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)20 ByteArrayInputStream (java.io.ByteArrayInputStream)19 FileOutputStream (java.io.FileOutputStream)18 Date (java.util.Date)18 List (java.util.List)18 PostMapping (org.springframework.web.bind.annotation.PostMapping)17 MockMultipartFile (org.springframework.web.testfixture.servlet.MockMultipartFile)17 Path (java.nio.file.Path)15