Java Code Examples for javax.servlet.http.Part

The following examples show how to use javax.servlet.http.Part. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: java-technology-stack   Author: codeEngraver   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void resolvePartArray() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockPart expected1 = new MockPart("pfilearray", "Hello World 1".getBytes());
	MockPart expected2 = new MockPart("pfilearray", "Hello World 2".getBytes());
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(new MockPart("other", "Hello World 3".getBytes()));
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Part[].class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Part[]);
	Part[] parts = (Part[]) result;
	assertEquals(2, parts.length);
	assertEquals(parts[0], expected1);
	assertEquals(parts[1], expected2);
}
 
Example #2
Source Project: java-technology-stack   Author: codeEngraver   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void resolvePartList() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	MockPart expected1 = new MockPart("pfilelist", "Hello World 1".getBytes());
	MockPart expected2 = new MockPart("pfilelist", "Hello World 2".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(new MockPart("other", "Hello World 3".getBytes()));
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof List);
	assertEquals(Arrays.asList(expected1, expected2), result);
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: StandardMultipartHttpServletRequest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<String>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
		for (Part part : parts) {
			String disposition = part.getHeader(CONTENT_DISPOSITION);
			String filename = extractFilename(disposition);
			if (filename == null) {
				filename = extractFilenameWithCharset(disposition);
			}
			if (filename != null) {
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not parse multipart servlet request", ex);
	}
}
 
Example #4
Source Project: java-technology-stack   Author: codeEngraver   File: RequestParamMapMethodArgumentResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfile", "Hello World".getBytes());
	Part expected2 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Map);
	Map<String, Part> resultMap = (Map<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(expected1, resultMap.get("mfile"));
	assertEquals(expected2, resultMap.get("other"));
}
 
Example #5
@Test
public void sendPart_succ(@Mocked Part part, @Mocked InputStream inputStream)
    throws IOException, InterruptedException, ExecutionException {
  new Expectations() {
    {
      part.getInputStream();
      result = inputStream;
      inputStream.read((byte[]) any);
      result = -1;
    }
  };

  CompletableFuture<Void> future = response.sendPart(part);

  Assert.assertNull(future.get());
}
 
Example #6
Source Project: HongsCORE   Author: ihongs   File: UploadHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 检查上传对象并写入目标目录
 * @param part
 * @param subn
 * @return
 * @throws Wrong
 */
public File upload(Part part, String subn) throws Wrong {
    if (part == null) {
        setResultName("", null);
        return  null;
    }

    /**
     * 从上传项中获取类型并提取扩展名
     */
    String type = part.getContentType( /**/ );
           type = getTypeByMime( type );
    String extn = part.getSubmittedFileName();
           extn = getExtnByName( extn );

    try {
        return upload(part.getInputStream(), type, extn, subn);
    }
    catch ( IOException ex) {
        throw new Wrong(ex, "fore.form.upload.failed");
    }
}
 
Example #7
Source Project: journaldev   Author: journaldev   File: FileUploadServlet.java    License: MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // gets absolute path of the web application
    String applicationPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
     
    // creates the save directory if it does not exists
    File fileSaveDir = new File(uploadFilePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }
    System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
    
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        part.write(uploadFilePath + File.separator + fileName);
    }
 
    request.setAttribute("message", fileName + " File uploaded successfully!");
    getServletContext().getRequestDispatcher("/response.jsp").forward(
            request, response);
}
 
Example #8
Source Project: spring4-understanding   Author: langtianya   File: RequestPartMethodArgumentResolverTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void resolvePartArrayArgument() throws Exception {
	MockPart part1 = new MockPart("requestPart1", "Hello World 1".getBytes());
	MockPart part2 = new MockPart("requestPart2", "Hello World 2".getBytes());
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(part1);
	request.addPart(part2);
	webRequest = new ServletWebRequest(request);

	Object result = resolver.resolveArgument(paramPartArray, null, webRequest, null);

	assertTrue(result instanceof Part[]);
	Part[] parts = (Part[]) result;
	assertThat(parts, Matchers.arrayWithSize(2));
	assertEquals(parts[0], part1);
	assertEquals(parts[1], part2);
}
 
Example #9
Source Project: java-technology-stack   Author: codeEngraver   File: StandardMultipartHttpServletRequest.java    License: MIT License 6 votes vote down vote up
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
		for (Part part : parts) {
			String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
			ContentDisposition disposition = ContentDisposition.parse(headerValue);
			String filename = disposition.getFilename();
			if (filename != null) {
				if (filename.startsWith("=?") && filename.endsWith("?=")) {
					filename = MimeDelegate.decode(filename);
				}
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		handleParseFailure(ex);
	}
}
 
Example #10
Source Project: servicecomb-java-chassis   Author: apache   File: UploadJaxrsSchema.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/uploadArray2")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String uploadArray2(@FormParam("file1") Part[] file1, @FormParam("message") String message)
    throws IOException {
  StringBuilder stringBuilder = new StringBuilder();
  for (int i = 0; i < file1.length; i++) {
    stringBuilder.append(getStrFromPart(file1[i]));
  }
  return stringBuilder.append(message).toString();
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: StandardMultipartHttpServletRequest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example #12
Source Project: spring4-understanding   Author: langtianya   File: RequestParamMethodArgumentResolverTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void resolvePartNotAnnot() throws Exception {
	MockPart expected = new MockPart("part", "Hello World".getBytes());
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(expected);
	webRequest = new ServletWebRequest(request);

	Object result = resolver.resolveArgument(paramPartNotAnnot, null, webRequest, null);

	assertTrue(result instanceof Part);
	assertEquals("Invalid result", expected, result);
}
 
Example #13
Source Project: eplmp   Author: polarsys   File: PartBinaryResourceTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to upload a native cad to a part
 */
@Test
public void uploadNativeCADToPart() throws Exception {

    //Given
    final File fileToUpload = new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_PART_STORAGE + ResourceUtil.TEST_PART_FILENAME1));
    File uploadedFile = File.createTempFile(ResourceUtil.TARGET_PART_STORAGE + ResourceUtil.FILENAME_TARGET_PART, ResourceUtil.TEMP_SUFFIX);
    HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class);
    Collection<Part> parts = new ArrayList<>();
    parts.add(new PartImpl(fileToUpload));
    Mockito.when(request.getParts()).thenReturn(parts);
    BinaryResource binaryResource = new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.PART_SIZE, new Date());
    OutputStream outputStream = new FileOutputStream(uploadedFile);
    Mockito.when(request.getRequestURI()).thenReturn(ResourceUtil.WORKSPACE_ID + "/parts/" + ResourceUtil.PART_TEMPLATE_ID + "/");
    Mockito.when(productService.saveNativeCADInPartIteration(Matchers.any(PartIterationKey.class), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource);
    Mockito.when(storageManager.getBinaryResourceOutputStream(binaryResource)).thenReturn(outputStream);

    //When
    Response response = partBinaryResource.uploadNativeCADFile(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.PART_NUMBER, ResourceUtil.VERSION, ResourceUtil.ITERATION);
    //Then
    assertNotNull(response);
    assertEquals(response.getStatus(), 201);
    assertEquals(response.getStatusInfo(), Response.Status.CREATED);

    //delete temp file
    uploadedFile.deleteOnExit();

}
 
Example #14
Source Project: servicecomb-java-chassis   Author: apache   File: InspectorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/download/schemas")
@GET
@ApiResponse(code = 200, message = "", response = File.class)
public Response downloadSchemas(@QueryParam("format") SchemaFormat format) {
  if (format == null) {
    format = SchemaFormat.SWAGGER;
  }

  // normally, schema will not be too big, just save them in memory temporarily
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try (ZipOutputStream zos = new ZipOutputStream(os)) {
    for (Entry<String, String> entry : schemas.entrySet()) {
      // begin writing a new ZIP entry, positions the stream to the start of the entry data
      zos.putNextEntry(new ZipEntry(entry.getKey() + format.getSuffix()));

      String content = entry.getValue();
      if (SchemaFormat.HTML.equals(format)) {
        content = swaggerToHtml(content);
      }
      zos.write(content.getBytes(StandardCharsets.UTF_8));
      zos.closeEntry();
    }
  } catch (Throwable e) {
    String msg = "failed to create schemas zip file, format=" + format + ".";
    LOGGER.error(msg, e);
    return Response.failResp(new InvocationException(Status.INTERNAL_SERVER_ERROR, msg));
  }

  Part part = new InputStreamPart(null, new ByteArrayInputStream(os.toByteArray()))
      .setSubmittedFileName(
          RegistrationManager.INSTANCE.getMicroservice().getServiceName() + format.getSuffix() + ".zip");
  return Response.ok(part);
}
 
Example #15
Source Project: BotLibre   Author: BotLibre   File: AvatarImportServlet.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	LoginBean loginBean = getLoginBean(request, response);
	if (loginBean == null) {
		httpSessionTimeout(request, response);
		return;
	}
	AvatarBean bean = loginBean.getBean(AvatarBean.class);
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		byte[] bytes = null;
		Collection<Part> files = request.getParts();
		int count = 0;
		for (Part filePart : files) {
			if (!filePart.getName().equals("file")) {
				continue;
			}
			if (filePart != null) {
				InputStream stream = filePart.getInputStream();
				int max = Site.MAX_UPLOAD_SIZE * 2;
				if (loginBean.isSuper()) {
					max = max * 10;
				}
				bytes = BotBean.loadImageFile(stream, true, max);
			}
			if ((bytes == null) || (bytes.length == 0)) {
				continue;
			}
			bean.importAvatar(bytes);
			count++;
		}
		if (count == 0) {
			throw new BotException("Please select the avatar files to import");
		}
		response.sendRedirect("avatar?id=" + bean.getInstanceId());
	} catch (Throwable failed) {
		loginBean.error(failed);
		response.sendRedirect("browse-avatar.jsp");
	}
}
 
Example #16
Source Project: eplmp   Author: polarsys   File: PartBinaryResourceTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to upload a file to a part with special characters
 *
 * @throws Exception
 */
@Test
public void uploadFileWithSpecialCharactersToPart() throws Exception {
    //Given
    File fileToUpload = new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_PART_STORAGE) + ResourceUtil.FILENAME_TO_UPLOAD_PART_SPECIAL_CHARACTER);
    File uploadedFile = File.createTempFile(ResourceUtil.TARGET_PART_STORAGE + ResourceUtil.FILENAME_TO_UPLOAD_PART_SPECIAL_CHARACTER, ResourceUtil.TEMP_SUFFIX);
    HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class);
    Collection<Part> parts = new ArrayList<>();
    parts.add(new PartImpl(fileToUpload));
    Mockito.when(request.getParts()).thenReturn(parts);
    BinaryResource binaryResource = new BinaryResource(ResourceUtil.FILENAME_TO_UPLOAD_PART_SPECIAL_CHARACTER, ResourceUtil.PART_SIZE, new Date());

    OutputStream outputStream = new FileOutputStream(uploadedFile);
    Mockito.when(request.getRequestURI()).thenReturn(ResourceUtil.WORKSPACE_ID + "/parts/" + ResourceUtil.PART_TEMPLATE_ID + "/");
    Mockito.when(productService.saveFileInPartIteration(Matchers.any(PartIterationKey.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource);
    Mockito.when(storageManager.getBinaryResourceOutputStream(binaryResource)).thenReturn(outputStream);

    //When
    Response response = partBinaryResource.uploadAttachedFiles(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.PART_NUMBER, ResourceUtil.VERSION, ResourceUtil.ITERATION);
    //Then
    assertNotNull(response);
    assertEquals(response.getStatus(), 201);
    assertEquals(response.getStatusInfo(), Response.Status.CREATED);
    assertEquals(response.getLocation().toString(), (ResourceUtil.WORKSPACE_ID + "/parts/" + ResourceUtil.PART_TEMPLATE_ID + "/" + URLEncoder.encode(ResourceUtil.getFilePath(ResourceUtil.SOURCE_PART_STORAGE) + ResourceUtil.FILENAME_TO_UPLOAD_PART_SPECIAL_CHARACTER, "UTF-8")));
    //delete temp file
    uploadedFile.deleteOnExit();

}
 
Example #17
Source Project: eplmp   Author: polarsys   File: DocumentBinaryResourceTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to upload several file to a document
 *
 * @throws Exception
 */
@Test
public void uploadSeveralFilesToDocumentsTemplates() throws Exception {

    //Given
    HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class);
    Collection<Part> filesParts = new ArrayList<>();
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME1))));
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE) + ResourceUtil.FILENAME2)));
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME3))));

    BinaryResource binaryResource1 = new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.DOCUMENT_SIZE, new Date());
    BinaryResource binaryResource2 = new BinaryResource(ResourceUtil.FILENAME2, ResourceUtil.DOCUMENT_SIZE, new Date());
    BinaryResource binaryResource3 = new BinaryResource(ResourceUtil.FILENAME3, ResourceUtil.DOCUMENT_SIZE, new Date());

    File uploadedFile1 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME1, ResourceUtil.TEMP_SUFFIX);
    File uploadedFile2 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME2, ResourceUtil.TEMP_SUFFIX);
    File uploadedFile3 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME3, ResourceUtil.TEMP_SUFFIX);

    OutputStream outputStream1 = new FileOutputStream(uploadedFile1);
    OutputStream outputStream2 = new FileOutputStream(uploadedFile2);
    OutputStream outputStream3 = new FileOutputStream(uploadedFile3);
    Mockito.when(request.getParts()).thenReturn(filesParts);
    Mockito.when(documentService.saveFileInDocument(Matchers.any(DocumentIterationKey.class), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource1, binaryResource1, binaryResource2, binaryResource2, binaryResource3, binaryResource3);
    Mockito.when(storageManager.getBinaryResourceOutputStream(Matchers.any(BinaryResource.class))).thenReturn(outputStream1, outputStream2, outputStream3);
    //When
    Response response = documentBinaryResource.uploadDocumentFiles(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION);

    //Then
    assertNotNull(response);
    assertEquals(Response.Status.NO_CONTENT, response.getStatusInfo());

    //delete temp files
    uploadedFile1.deleteOnExit();
    uploadedFile2.deleteOnExit();
    uploadedFile3.deleteOnExit();

}
 
Example #18
Source Project: spring-cloud-openfeign   Author: spring-cloud   File: ValidFeignClientTests.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipartFilenames",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String multipartFilenames(HttpServletRequest request) throws Exception {
	return request.getParts().stream().map(Part::getSubmittedFileName)
			.collect(Collectors.joining(","));
}
 
Example #19
Source Project: eplmp   Author: polarsys   File: ProductInstanceBinaryResource.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String uploadAFile(String workspaceId, Part formPart, ProductInstanceIterationKey pdtIterationKey)
        throws EntityNotFoundException, EntityAlreadyExistsException, AccessRightException, NotAllowedException, CreationException, UserNotActiveException, StorageException, IOException, WorkspaceNotEnabledException {

    String fileName = Normalizer.normalize(formPart.getSubmittedFileName(), Normalizer.Form.NFC);
    // Init the binary resource with a null length
    BinaryResource binaryResource = productInstanceManagerLocal.saveFileInProductInstance(workspaceId, pdtIterationKey, fileName, 0);
    OutputStream outputStream = storageManager.getBinaryResourceOutputStream(binaryResource);
    long length = BinaryResourceUpload.uploadBinary(outputStream, formPart);
    productInstanceManagerLocal.saveFileInProductInstance(workspaceId, pdtIterationKey, fileName, (int) length);
    return fileName;
}
 
Example #20
Source Project: java-technology-stack   Author: codeEngraver   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 5 votes vote down vote up
@Test
public void resolvePart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockPart expected = new MockPart("pfile", "Hello World".getBytes());
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(expected);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Part);
	assertEquals("Invalid result", expected, result);
}
 
Example #21
Source Project: spring4-understanding   Author: langtianya   File: StandardMultipartHttpServletRequest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Exception ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example #22
Source Project: eplmp   Author: polarsys   File: DocumentBinaryResourceTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to upload a file to a document with special characters
 *
 * @throws Exception
 */
@Test
public void uploadFileWithSpecialCharactersToDocumentTemplates() throws Exception {

    //Given
    HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class);
    Collection<Part> filesParts = new ArrayList<>();
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE) + ResourceUtil.FILENAME2)));

    BinaryResource binaryResource = new BinaryResource(Tools.unAccent(ResourceUtil.FILENAME2), ResourceUtil.DOCUMENT_SIZE, new Date());

    File uploadedFile1 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME2, ResourceUtil.TEMP_SUFFIX);


    OutputStream outputStream1 = new FileOutputStream(uploadedFile1);

    Mockito.when(request.getParts()).thenReturn(filesParts);
    Mockito.when(documentService.saveFileInDocument(Matchers.any(DocumentIterationKey.class), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource);
    Mockito.when(storageManager.getBinaryResourceOutputStream(Matchers.any(BinaryResource.class))).thenReturn(outputStream1);
    Mockito.when(request.getRequestURI()).thenReturn(ResourceUtil.WORKSPACE_ID + "/documents/" + ResourceUtil.DOCUMENT_ID + "/" + ResourceUtil.FILENAME2);


    //When
    Response response = documentBinaryResource.uploadDocumentFiles(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION);

    //Then
    assertNotNull(response);
    assertEquals(201, response.getStatus());
    assertEquals(Response.Status.CREATED, response.getStatusInfo());

    //delete tem file
    uploadedFile1.deleteOnExit();
}
 
Example #23
Source Project: servicecomb-java-chassis   Author: apache   File: TestInspectorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void testDownloadHtmlById(String schemaId) throws IOException {
  Response response = inspector.getSchemaContentById(schemaId, SchemaFormat.HTML, true);

  Part part = response.getResult();
  Assert.assertEquals(schemaId + ".html", part.getSubmittedFileName());
  Assert.assertNull(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION));
  Assert.assertEquals(MediaType.TEXT_HTML, response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE));

  try (InputStream is = part.getInputStream()) {
    Assert.assertTrue(IOUtils.toString(is, StandardCharsets.UTF_8).endsWith("</html>"));
  }
}
 
Example #24
Source Project: servicecomb-java-chassis   Author: apache   File: UploadJaxrsSchema.java    License: Apache License 2.0 5 votes vote down vote up
private static String getStrFromPart(Part file1) {
  try (InputStream is1 = file1.getInputStream()) {
    return IOUtils.toString(is1, "utf-8");
  } catch (IOException e) {
    e.printStackTrace();
  }
  return "";
}
 
Example #25
Source Project: spring4-understanding   Author: langtianya   File: MockHttpServletRequest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
	List<Part> result = new LinkedList<Part>();
	for (List<Part> list : this.parts.values()) {
		result.addAll(list);
	}
	return result;
}
 
Example #26
Source Project: spring-analysis-note   Author: Vip-Augus   File: MockHttpServletRequest.java    License: MIT License 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, ServletException {
	List<Part> result = new LinkedList<>();
	for (List<Part> list : this.parts.values()) {
		result.addAll(list);
	}
	return result;
}
 
Example #27
Source Project: servicecomb-java-chassis   Author: apache   File: TestStandardHttpServletResponseEx.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void sendPart_failed(@Mocked Part part) throws Throwable {
  RuntimeException error = new RuntimeExceptionWithoutStackTrace();
  new Expectations() {
    {
      response.getOutputStream();
      result = error;
    }
  };

  expectedException.expect(Matchers.sameInstance(error));

  responseEx.sendPart(part).get();
}
 
Example #28
Source Project: fenixedu-cms   Author: FenixEdu   File: PostResource.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Atomic(mode = TxMode.WRITE)
public void createFileFromRequest(Post post, Part part) throws IOException {
    AdminPosts.ensureCanEditPost(post);
    GroupBasedFile groupBasedFile = new GroupBasedFile(part.getName(), part.getName(),
            part.getInputStream(), Group.logged());

    PostFile postFile = new PostFile(post, groupBasedFile, false, 0);
    post.addFiles(postFile);
}
 
Example #29
Source Project: tomee   Author: apache   File: HttpRequestImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, ServletException {
    if (parts == null) { // assume it is not init
        parts = CommonsFileUploadPartFactory.read(this);
    }
    return parts;
}
 
Example #30
Source Project: servicecomb-java-chassis   Author: apache   File: TestServerRestArgsFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void asyncBeforeSendResponse_part(@Mocked RestOperationMeta restOperationMeta) {
  ResponsesMeta responsesMeta = new ResponsesMeta();
  responsesMeta.getResponseMap().put(202, RestObjectMapperFactory.getRestObjectMapper().constructType(Part.class));
  new Expectations(RestMetaUtils.class) {
    {
      responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE);
      result = response;
      response.getResult();
      result = part;
      response.getStatusCode();
      result = 202;
      invocation.findResponseType(202);
      result = TypeFactory.defaultInstance().constructType(Part.class);
    }
  };
  new MockUp<HttpServletResponseEx>(responseEx) {
    @Mock
    CompletableFuture<Void> sendPart(Part body) {
      invokedSendPart = true;
      return null;
    }
  };

  Assert.assertNull(filter.beforeSendResponseAsync(invocation, responseEx));
  Assert.assertTrue(invokedSendPart);
}