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);
}
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);
}
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"));
}
}
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);
}
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);
}
Aggregations