HttpFormData implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws IOException { if (!"POST".equals(request.getMethod())) { response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); return; } String tempDirectory = System.getProperty("java.io.tmpdir"); for (HttpRequest.HttpPart httpPart : request.getParts().values()) { String filename = httpPart.getFileName().orElse(null); if (filename == null) { continue; } logger.info("Processed file: " + filename); Path filePath = Paths.get(tempDirectory, filename).toAbsolutePath(); Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING); Files.delete(filePath); } request.getQueryParameters().forEach( (fieldName, fieldValues) -> { String firstFieldValue = fieldValues.get(0); logger.info(String.format( "Processed field: %s (value: %s)", fieldName, firstFieldValue)); }); }  @Override void service(HttpRequest request, HttpResponse response);  }
@Test public void functionsHttpMethod_shouldErrorOnGet() throws IOException { when(request.getMethod()).thenReturn("GET"); new HttpFormData().service(request, response); writerOut.flush(); verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); }
@Test public void functionsHttpFormData_shouldSaveFiles() throws IOException { when(request.getMethod()).thenReturn("POST"); InputStream stream = new ByteArrayInputStream("foo text%n".getBytes(StandardCharsets.UTF_8)); MockHttpPart mockHttpPart = new MockHttpPart(); mockHttpPart.setFileName("foo.txt"); mockHttpPart.setInputStream(stream); Map<String, HttpPart> httpParts = Map.of("mock", mockHttpPart); when(request.getParts()).thenReturn(httpParts); new HttpFormData().service(request, response); assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo( "Processed file: foo.txt"); }
@Test public void functionsHttpFormData_shouldProcessFields() throws IOException { when(request.getMethod()).thenReturn("POST"); when(request.getParts()).thenReturn(Map.of()); Map<String, List<String>> queryParams = Map.of("foo", List.of("bar")); when(request.getQueryParameters()).thenReturn(queryParams); when(request.getFirstQueryParameter("foo")).thenReturn(Optional.of("bar")); new HttpFormData().service(request, response); assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo( "Processed field: foo (value: bar)"); }