List of usage examples for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE
String MULTIPART_FORM_DATA_VALUE
To view the source code for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE.
Click Source Link
From source file:com.wavemaker.tools.apidocs.tools.spring.resolver.MultiPartFileResolver.java
@Override public List<Parameter> resolveParameter(final int index, final TypeInformation typeInformation, final Annotation[] annotations, final Operation operation) { SpringParameterParser parameterParser = new SpringParameterParser(index, typeInformation.getGenericType(), annotations);/*from w w w. j a v a 2 s .c om*/ Parameter parameter = parameterParser.parse(); if (!(parameter instanceof BodyParameter)) { final boolean array = typeInformation.isArray(); Property property = new FileProperty(); property.setRequired(true); if (parameter instanceof FormParameter) { if (array) { ((FormParameter) parameter).items(property); } else { ((FormParameter) parameter).property(property); } } else if (parameter instanceof QueryParameter) { if (array) { ((QueryParameter) parameter).items(property); } else { ((QueryParameter) parameter).property(property); } } } parameter.setName(parameter.getName()); ((AbstractParameter) parameter).setResolver(typeInformation.getActualType().getName()); // setting consumes to multi part form operation.setConsumes(Lists.newArrayList(MediaType.MULTIPART_FORM_DATA_VALUE)); return CollectionUtil.asList(parameter); }
From source file:org.openlmis.fulfillment.web.TemplateControllerIntegrationTest.java
@Test public void shouldAddReportTemplate() throws IOException { ClassPathResource podReport = new ClassPathResource("jasperTemplates/proofOfDelivery.jrxml"); try (InputStream podStream = podReport.getInputStream()) { restAssured.given().header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) .multiPart("file", podReport.getFilename(), podStream) .formParam("name", TEMPLATE_CONTROLLER_TEST).formParam("description", TEMPLATE_CONTROLLER_TEST) .when().post(RESOURCE_URL).then().statusCode(200); }/* w w w. j av a 2s . co m*/ assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); }
From source file:org.openlmis.fulfillment.web.TemplateControllerIntegrationTest.java
@Test public void shouldReturnBadRequestWhenTemplateExist() throws IOException { ClassPathResource podReport = new ClassPathResource("jasperTemplates/proofOfDelivery.jrxml"); given(templateRepository.findByName(TEMPLATE_CONTROLLER_TEST)).willReturn(new Template()); try (InputStream podStream = podReport.getInputStream()) { restAssured.given().header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) .multiPart("file", podReport.getFilename(), podStream) .formParam("name", TEMPLATE_CONTROLLER_TEST).formParam("description", TEMPLATE_CONTROLLER_TEST) .when().post(RESOURCE_URL).then().statusCode(400); }/*from ww w. j a v a 2s. c o m*/ assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); }
From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseStatus(value = HttpStatus.CREATED) @ResponseBody JSONArr create(HttpServletRequest request) throws IOException, FileUploadException { return create(null, request); }
From source file:com.epam.ta.reportportal.ws.controller.impl.LogController.java
@Override @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) @ResponseBody// w w w . jav a 2 s.co m // @ApiOperation("Create log (batching operation)") // Specific handler should be added for springfox in case of similar POST // request mappings @ApiIgnore public ResponseEntity<BatchSaveOperatingRS> createLog(@PathVariable String projectName, @RequestPart(value = Constants.LOG_REQUEST_JSON_PART) SaveLogRQ[] createLogRQs, HttpServletRequest request, Principal principal) { String prjName = EntityUtils.normalizeProjectName(projectName); /* * Since this is multipart request we can retrieve list of uploaded * files */ Map<String, MultipartFile> uploadedFiles = getUploadedFiles(request); BatchSaveOperatingRS response = new BatchSaveOperatingRS(); EntryCreatedRS responseItem; /* Go through all provided save log request items */ for (SaveLogRQ createLogRq : createLogRQs) { try { validateSaveRQ(createLogRq); String filename = createLogRq.getFile() == null ? null : createLogRq.getFile().getName(); if (StringUtils.isEmpty(filename)) { /* * There is no filename in request. Use simple save * method */ responseItem = createLog(prjName, createLogRq, principal); } else { /* Find by request part */ MultipartFile data = findByFileName(filename, uploadedFiles); BusinessRule.expect(data, Predicates.notNull()).verify(ErrorType.BINARY_DATA_CANNOT_BE_SAVED, Suppliers.formattedSupplier("There is no request part or file with name {}", filename)); /* * If provided content type is null or this is octet * stream, try to detect real content type of binary * data */ if (!StringUtils.isEmpty(data.getContentType()) && !MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(data.getContentType())) { responseItem = createLogMessageHandler.createLog(createLogRq, new BinaryData(data.getContentType(), data.getSize(), data.getInputStream()), data.getOriginalFilename(), prjName); } else { byte[] consumedData = IOUtils.toByteArray(data.getInputStream()); responseItem = createLogMessageHandler.createLog(createLogRq, new BinaryData(contentTypeResolver.detectContentType(consumedData), data.getSize(), new ByteArrayInputStream(consumedData)), data.getOriginalFilename(), prjName); } } response.addResponse(new BatchElementCreatedRS(responseItem.getId())); } catch (Exception e) { response.addResponse( new BatchElementCreatedRS(ExceptionUtils.getStackTrace(e), ExceptionUtils.getMessage(e))); } } return new ResponseEntity<>(response, HttpStatus.CREATED); }
From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java
@RequestMapping(value = "/{wsName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseStatus(value = HttpStatus.CREATED) @ResponseBody JSONArr create(@PathVariable String wsName, HttpServletRequest request) throws IOException, FileUploadException { WorkspaceInfo ws;//from ww w .j a v a 2s . c o m Resource styles; if (wsName == null) { ws = null; styles = dataDir().getRoot("styles"); } else { ws = findWorkspace(wsName, catalog()); styles = dataDir().get(ws, "styles"); } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); @SuppressWarnings("unchecked") List<FileItem> input = (List<FileItem>) upload.parseRequest(request); JSONArr created = new JSONArr(); for (FileItem file : input) { String filename = file.getName(); // trim filename if required if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/')); } if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\')); } String ext = fileExt(filename); if (!ICON_FORMATS.containsKey(ext)) { String msg = "Icon " + filename + " format " + ext + " unsupported - try:" + ICON_FORMATS.keySet(); LOG.warning(msg); throw new FileUploadException(msg); } try { InputStream data = file.getInputStream(); Resources.copy(data, styles, filename); icon(created.addObject(), ws, styles.get(filename), request); } catch (Exception e) { throw new FileUploadException("Unable to write " + filename, e); } } return created; }
From source file:com.phoenixnap.oss.ramlapisync.data.ApiActionMetadata.java
private void collectBodyParams(Entry<String, RamlMimeType> mime) { if (mime.getKey().equals(MediaType.MULTIPART_FORM_DATA_VALUE) && ResourceParser.doesActionTypeSupportMultipartMime(actionType)) { collectRequestParamsForMime(action.getBody().get(MediaType.MULTIPART_FORM_DATA_VALUE)); } else if (mime.getKey().equals(MediaType.APPLICATION_FORM_URLENCODED_VALUE) && ResourceParser.doesActionTypeSupportMultipartMime(actionType)) { collectRequestParamsForMime(action.getBody().get(MediaType.APPLICATION_FORM_URLENCODED_VALUE)); }/*www . j a v a 2s . c om*/ if (ResourceParser.doesActionTypeSupportRequestBody(actionType) && mime.getKey().toLowerCase().contains("json")) { // Continue here! String schema = mime.getValue().getSchema(); if (StringUtils.hasText(schema)) { ApiBodyMetadata requestBody = SchemaHelper.mapSchemaToPojo(parent.getDocument(), schema, parent.getBasePackage() + NamingHelper.getDefaultModelPackage(), StringUtils.capitalize(getName()) + "Request", null); if (requestBody != null) { setRequestBody(requestBody, mime.getKey()); } } } }
From source file:de.unimannheim.spa.process.rest.ProjectRestControllerTest.java
@Test public void itShouldCreateAndReturnNewProcessWithFile() throws Exception { final String projectIDForTest = createProjectAndReturnID(); final String processLabelToTest = "newProcessLabelToTest"; MockMultipartFile processFileToTest = new MockMultipartFile("processFile", "example-spa.bpmn", MediaType.MULTIPART_FORM_DATA_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile())); mockMvc.perform(fileUpload("/projects/" + projectIDForTest + "/processes").file(processFileToTest) .param("processLabel", processLabelToTest).param("format", "BPMN2")).andExpect(status().isCreated()) .andExpect(content().contentType(JSON_CONTENT_TYPE)) .andExpect(jsonPath("$.id", containsString("http://www.uni-mannheim.de/spa/DataBucket/"))) .andExpect(jsonPath("$.label", equalTo(processLabelToTest))); }
From source file:de.unimannheim.spa.process.rest.ProjectRestControllerTest.java
@Test public void itShouldReturnNotFoundForCreatingAProcessInNonExistentProjectID() throws Exception { final String processLabelToTest = "newProcessLabelToTest"; MockMultipartFile processFileToTest = new MockMultipartFile("processFile", "example-spa.bpmn", MediaType.MULTIPART_FORM_DATA_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile())); mockMvc.perform(fileUpload("/projects/" + NON_EXISTENT_PROJECT_ID_TO_TEST + "/processes") .file(processFileToTest).param("processLabel", processLabelToTest).param("format", "BPMN2")) .andExpect(status().isNotFound()); }