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 filename = extractFilename(part.getHeader(CONTENT_DISPOSITION)); if (filename != null) { files.add(part.getName(), new StandardMultipartFile(part, filename)); } else { this.multipartParameterNames.add(part.getName()); } } setMultipartFiles(files); } catch (Exception ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } }
/** * {@inheritDoc} */ @Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; }
private static void initPropertyMap() { PROPERTY_MAP.put(BooleanProperty.class, SimpleType.constructUnsafe(Boolean.class)); PROPERTY_MAP.put(FloatProperty.class, SimpleType.constructUnsafe(Float.class)); PROPERTY_MAP.put(DoubleProperty.class, SimpleType.constructUnsafe(Double.class)); PROPERTY_MAP.put(DecimalProperty.class, SimpleType.constructUnsafe(BigDecimal.class)); PROPERTY_MAP.put(ByteProperty.class, SimpleType.constructUnsafe(Byte.class)); PROPERTY_MAP.put(ShortProperty.class, SimpleType.constructUnsafe(Short.class)); PROPERTY_MAP.put(IntegerProperty.class, SimpleType.constructUnsafe(Integer.class)); PROPERTY_MAP.put(BaseIntegerProperty.class, SimpleType.constructUnsafe(Integer.class)); PROPERTY_MAP.put(LongProperty.class, SimpleType.constructUnsafe(Long.class)); // stringProperty包含了enum的场景,并不一定是转化为string // 但是,如果统一走StringPropertyConverter则可以处理enum的场景 PROPERTY_MAP.put(StringProperty.class, SimpleType.constructUnsafe(String.class)); PROPERTY_MAP.put(DateProperty.class, SimpleType.constructUnsafe(LocalDate.class)); PROPERTY_MAP.put(DateTimeProperty.class, SimpleType.constructUnsafe(Date.class)); PROPERTY_MAP.put(ByteArrayProperty.class, SimpleType.constructUnsafe(byte[].class)); PROPERTY_MAP.put(FileProperty.class, SimpleType.constructUnsafe(Part.class)); }
@Override @SuppressWarnings("unchecked") public T get() { final MinijaxRequestContext context = MinijaxRequestContext.getThreadLocal(); final Class<?> c = key.getType(); final MinijaxForm form = context.getForm(); final String name = key.getName(); if (c == InputStream.class) { return form == null ? null : (T) form.getInputStream(name); } if (c == Part.class) { return form == null ? null : (T) form.getPart(name); } String value = form == null ? null : form.getString(name); final DefaultValue defaultValue = key.getDefaultValue(); if (value == null && defaultValue != null) { value = defaultValue.value(); } return (T) context.getApplication().convertParamToType(value, c, key.getAnnotations()); }
@Test public void fileBoundaryInfo_nullSubmittedFileName(@Mocked Part part) { new Expectations() { { part.getSubmittedFileName(); result = null; part.getContentType(); result = "abc"; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part); Assert.assertEquals("\r\n" + "--boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"null\"\r\n" + "Content-Type: abc\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n", buffer.toString()); }
@Test public void fileBoundaryInfo_validSubmittedFileName(@Mocked Part part) { new Expectations() { { part.getSubmittedFileName(); result = "a.txt"; part.getContentType(); result = MediaType.TEXT_PLAIN; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part); Assert.assertEquals("\r\n" + "--boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"a.txt\"\r\n" + "Content-Type: text/plain\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n", buffer.toString()); }
public static List<Part> parseAll(final String str) { final int index = str.indexOf('\n'); final String boundary = str.substring(0, index) + "\n"; if (str.length() <= 2 * boundary.length()) { return Collections.emptyList(); } final String content = str.substring(index + 1, str.length() - boundary.length()); final String[] strParts = content.split(boundary, 0); final List<Part> parts = new ArrayList<>(strParts.length); for (final String strPart : strParts) { parts.add(MockPart.parse(strPart)); } return parts; }
@Test public void testKeyValue() throws IOException { final String mockContent = "------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" + "Content-Disposition: form-data; name=\"key\"\n" + "\n" + "myvalue1\n" + "------WebKitFormBoundarycTqA2AimXQHBAJbZ"; final List<Part> parts = MockPart.parseAll(mockContent); assertNotNull(parts); assertEquals(1, parts.size()); final Part part = parts.get(0); assertEquals("key", part.getName()); assertEquals("myvalue1", IOUtils.toString(part.getInputStream(), StandardCharsets.UTF_8)); }
@Test public void testDoPutSyncLost() throws IOException, ServletException { cut.cleanUpWS(Paths.get(new File(wd).getPath())); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getServletPath()).thenReturn(SERVLET_PATH); Mockito.when(request.getRequestURI()).thenReturn(SERVLET_PATH + NEW_ARTIFACT_PATH); Part part1 = Mockito.mock(Part.class); Mockito.when(part1.getInputStream()).thenReturn(TestUtils.getZipStream("newProject.zip")); Collection<Part> parts = Collections.singleton(part1); Mockito.when(request.getParts()).thenReturn(parts); cut.doPut(request, response); Mockito.verify(response, times(NO_CONTENT_STATS)).setStatus(HttpServletResponse.SC_NO_CONTENT); NO_CONTENT_STATS++; }
@Test public void testDoPostSyncLost() throws IOException, ServletException { cut.cleanUpWS(Paths.get(new File(wd).getPath())); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURI()).thenReturn(SERVLET_PATH + ARTIFACT_PATH); Mockito.when(request.getServletPath()).thenReturn(SERVLET_PATH); Part part1 = Mockito.mock(Part.class); Mockito.when(part1.getInputStream()).thenReturn(TestUtils.getZipStream("postTest.zip")); Collection<Part> parts = Collections.singleton(part1); Mockito.when(request.getParts()).thenReturn(parts); cut.doPost(request, response); Mockito.verify(response, times(NO_CONTENT_STATS)).setStatus(HttpServletResponse.SC_NO_CONTENT); NO_CONTENT_STATS++; }
@Override public Form asForm() { final MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); for (final Part part : values.values()) { if (part.getSubmittedFileName() != null) { continue; } try { map.add(part.getName(), IOUtils.toString(part.getInputStream(), StandardCharsets.UTF_8)); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } return new Form(map); }
public void doPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); Collection<Part> parts = req.getParts(); File uploadDir = new File(inputDir + "/upload"); if (!uploadDir.exists()) uploadDir.mkdirs(); byte[] buffer = new byte[8 * 1024]; for (Part part : parts) { File uploadedFile = new File(uploadDir,getFileName(part)); InputStream input = part.getInputStream(); try { OutputStream output = new FileOutputStream(uploadedFile); try { int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } finally { output.close(); } } finally { input.close(); } LOGGER.info("saved csv-file " + uploadedFile); job.getResponse().sendRedirect("getScopusAuthorData?listName="+ uploadedFile); } }
public InputStream getInputStream(SectionInfo info) { Part file = getMultipartFile(info); if( file != null ) { try { return file.getInputStream(); } catch( IOException e ) { SectionUtils.throwRuntime(e); } } return null; }
@Test public void testMultipleLines() throws IOException { final String mockContent = "------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" + "Content-Disposition: form-data; name=\"key\"\n" + "\n" + "myvalue1\n" + "myvalue1\n" + "------WebKitFormBoundarycTqA2AimXQHBAJbZ"; final List<Part> parts = MockPart.parseAll(mockContent); assertNotNull(parts); assertEquals(1, parts.size()); final Part part = parts.get(0); assertEquals("key", part.getName()); assertEquals("myvalue1" + "\n" + "myvalue1", IOUtils.toString(part.getInputStream(), StandardCharsets.UTF_8)); }
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException { if (sharedFileItemFactory.get() == null) { // Not a big deal if two threads actually set this up DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( 1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir")); fileItemFactory.setFileCleaningTracker( FileCleanerCleanup.getFileCleaningTracker(servletContext)); sharedFileItemFactory.compareAndSet(null, fileItemFactory); } try { return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request) .stream().map(FileItemPart::new).collect(Collectors.toList()); } catch (FileUploadException e) { throw new IOException(e.getMessage()); } }
/** * Gestiona la subida de archivos */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //obtiene el path relativo de subida de archivos de la aplicación String savePath = getServletContext().getInitParameter("file-upload"); // crea la carpeta donde se guardaran los archivos si no existe File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } //Obtiene el archivo desde la petición Part file = request.getPart("documentoEvidencia"); String fileName = getFilename(file); //extrae la extension y el nombre de archivo por separado int dot = fileName.lastIndexOf("."); String fileNameExt = fileName.substring(dot); fileName = fileName.substring(0, dot); //remplaza cualquier caracter del tipo espacio, puntos y otros por guión bajo. fileName = fileName.replaceAll("\\W","_"); Date fecha = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS"); String fechaStr = (String)sdf.format((fecha)); file.write(savePath + File.separator + fechaStr +"_"+ fileName + fileNameExt); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); if(fileName != null) response.getWriter().write(savePath + File.separator + fechaStr +"_"+ fileName + fileNameExt); else response.getWriter().write(""); }
@Override public Collection<Part> getParts() throws IOException, ServletException { if (parts == null) { loadParts(); } return parts; }
@Test public void transferTo() throws IllegalStateException, IOException { File dest = new File("/dest"); Holder<String> destName = new Holder<>(); new MockUp<Part>(part) { @Mock void write(String fileName) throws IOException { destName.value = fileName; } }; multipartFile.transferTo(dest); Assert.assertEquals(dest.getPath(), destName.value); }
@Override public Part getPart(String name) throws IOException, ServletException { Object value = findPartInputValue(name); if (value == null) { return null; } if (Part.class.isInstance(value)) { return (Part) value; } if (InputStream.class.isInstance(value)) { return new InputStreamPart(name, (InputStream) value); } if (Resource.class.isInstance(value)) { return new ResourcePart(name, (Resource) value); } if (File.class.isInstance(value)) { return new FilePart(name, (File) value); } throw new IllegalStateException( String.format("File input parameter of %s could be %s / %s / %s or %s, but got %s.", name, Part.class.getName(), InputStream.class.getName(), Resource.class.getName(), File.class.getName(), value.getClass().getName())); }
public Part typeImagem(String imagem) { @SuppressWarnings("UnusedAssignment") Part image= null; if( null != imagem)switch (imagem) { case "empLogo":image=this.getLogotipoEmpresa();break; case "empCabe":image=this.getCabecalhoEmpresa();break; default:image=this.getRodapeEmpresa();break; } return image; }
String getHashPart() throws IOException, ServletException { Part part = getPart(); if (part != null) { return String.valueOf(part.hashCode()); } return ""; }
@Test public void testFile() throws IOException { final String mockContent = "------WebKitFormBoundaryoyr33TDQmcUAD5A7\n" + "Content-Disposition: form-data; name=\"attachdoc\"; filename=\"hello.txt\"\n" + "Content-Type: text/plain\n" + "X-Other-Header: foo\n" + "X-Other-Header: bar\n" + "\n" + "Hello world\n" + "------WebKitFormBoundaryoyr33TDQmcUAD5A7"; final List<Part> parts = MockPart.parseAll(mockContent); assertNotNull(parts); assertEquals(1, parts.size()); final Part part = parts.get(0); assertEquals("attachdoc", part.getName()); assertEquals("text/plain", part.getContentType()); assertEquals("hello.txt", part.getSubmittedFileName()); assertEquals(11, part.getSize()); assertEquals("Hello world", IOUtils.toString(part.getInputStream(), StandardCharsets.UTF_8)); assertEquals("Hello world", ((MockPart) part).getValue()); assertEquals( new HashSet<>(Arrays.asList("Content-Disposition", "Content-Type", "X-Other-Header")), new HashSet<>(part.getHeaderNames())); assertEquals(Arrays.asList("foo", "bar"), part.getHeaders("X-Other-Header")); }
/** * {@inheritDoc} */ @Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; }
private static String getFilename(Part part) { for (String cd : part.getHeader("content-disposition").split(";")) { if (cd.trim().startsWith("filename")) { String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix. } } return null; }
void initialSync(HttpServletRequest request, HttpServletResponse response, String workspaceRoot, String workspaceSaveDir) throws IOException, ServletException { // Expected: one part containing zip Part part = request.getParts().iterator().next(); try (final InputStream inputStream = part.getInputStream()) { syncWorkspace(inputStream, new File(workspaceSaveDir)); response.getWriter().append(workspaceRoot); response.setStatus(HttpServletResponse.SC_CREATED); } catch (NoSuchElementException ePart) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } }
private void addNewFiles(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String artifactRelPath; artifactRelPath = request.getRequestURI().substring(request.getServletPath().length() + 1 ); File destination = new File(FilenameUtils.normalize(this.saveDir + artifactRelPath)); if (destination.exists()) { LOG.info("File to be added already exist: " + destination.getPath()); response.setContentType("application/json"); response.getWriter().append(String.format("{ \"error\": \"already exists %s\"}", destination.getPath())); response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } // Expected: one part containing zip try{ Part part = request.getParts().iterator().next(); WSChangeObserver changeObserver = new WSChangeObserver(ChangeType.CHANGE_CREATED, lspDestPath); if (extract(part.getInputStream(), changeObserver)) { changeObserver.notifyLSP(); response.setContentType("application/json"); response.getWriter().append(String.format("{ \"created\": \"%s\"}", artifactRelPath)); response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setContentType("application/json"); response.getWriter().append(String.format("{ \"error\": \"conflict %s\"}", artifactRelPath)); response.setStatus(HttpServletResponse.SC_CONFLICT); } } catch (NoSuchElementException ePart) { response.setContentType("application/json"); response.getWriter().append(String.format("{ \"error\": \"exception for %s\"}", artifactRelPath)); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } }
/** * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check if it is LSP registration String lspReg = request.getHeader("Register-lsp"); if ( lspReg != null ) { handleLSPDest(Boolean.parseBoolean(lspReg), request.getReader()); return; } // Otherwise process data passed from DI if( !checkSync() ) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } String artifactRelPath = request.getRequestURI().substring(request.getServletPath().length() + 1); String artifactPath = this.saveDir + artifactRelPath; File destination = new File(FilenameUtils.normalize(artifactPath)); // Expected: one part containing zip try{ Part part = request.getParts().iterator().next(); WSChangeObserver changeObserver = new WSChangeObserver(ChangeType.CHANGE_UPDATED, lspDestPath); if (destination.exists() && !destination.isDirectory() && extract(part.getInputStream(), changeObserver)) { changeObserver.notifyLSP(); response.setContentType("application/json"); response.getWriter().append(String.format("{ \"updated\": \"%s\"}", artifactRelPath)); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } catch (NoSuchElementException ePart) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } }
@Test public void testNewProject() throws IOException, ServletException { HttpServletRequest requestInit = Mockito.mock(HttpServletRequest.class); Part part1 = Mockito.mock(Part.class); Mockito.when(part1.getInputStream()).thenReturn(TestUtils.getZipStream("putTest.zip")); Collection<Part> parts = Collections.singleton(part1); Mockito.when(requestInit.getParts()).thenReturn(parts); String workspaceSaveDir = testUtil.getWdPath().toString(); cut.initialSync(requestInit, response, "file://" + workspaceSaveDir, workspaceSaveDir); CREATED_CALLS++; HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getServletPath()).thenReturn(SERVLET_PATH); Mockito.when(request.getRequestURI()).thenReturn(SERVLET_PATH + NEW_ARTIFACT_PATH); part1 = Mockito.mock(Part.class); Mockito.when(part1.getInputStream()).thenReturn(TestUtils.getZipStream("newProject.zip")); parts = Collections.singleton(part1); Mockito.when(request.getParts()).thenReturn(parts); cut.doPut(request, response); Mockito.verify(response, times(CREATED_CALLS)).setStatus(HttpServletResponse.SC_CREATED); CREATED_CALLS++; //'/newProject/newModule/java1/test1.java' assertTrue("File create ", new File(wd + File.separator + "newProject" + File.separator + "newModule" + File.separator + "java1" + File.separator + "test1.java").exists()); }
private Object getUploadedFiles(String strParamValue, String frontier, FrontierMethod frontierMethod, MethodParam methodParam, Map<String,Object> uploadsMap, HttpServletRequest request) throws FrontierCallException { String uploadName = strParamValue.substring(strParamValue.indexOf(":")+1,strParamValue.length()); if(!uploadsMap.containsKey(uploadName)) throw new FrontierCallException(frontier,methodParam.getName(),"The upload request data is corrupted"); Double totalD = (Double) uploadsMap.get(uploadName); int total = totalD.intValue(); if(total<1) throw new MissingFrontierParamException(frontier,frontierMethod.getName(),methodParam.getName()); FileUpload[] files = new FileUpload[total]; for(int i=0; i<total;i++){ try { String partName = uploadName + "_file_" + i; Part part = request.getPart(partName); if (part == null) throw new FrontierCallException(frontier, methodParam.getName(), "The upload request data is corrupted"); files[i] = new FileUpload(part); }catch (IOException | ServletException ex){ throw new FrontierCallException(frontier, methodParam.getName(), "Failed to decode uploaded content",ex); } } if(methodParam.getType().isArray())return files; else{ if(files.length>1) throw new FrontierCallException(frontier,methodParam.getName(),"One file expected. "+files.length+" uploaded files found"); return files[0]; } }
@Override public Collection<Part> getParts() throws IOException, ServletException { if (!RequestUtils.isMultipartRequest(this)) { return null; } return super.getParts(); }
@Override public Part getPart(final String name) throws IOException, ServletException { if (parts == null) { loadParts(); } for (Part part : parts) { if (part.getName().equals(name)) { return part; } } return null; }
public String getMimeType(SectionInfo info) { Part file = getMultipartFile(info); if( file != null ) { return file.getContentType(); } return null; }
@Override public InputStream getInputStream(final String name) { try { final Part part = values.get(name); return part == null ? null : part.getInputStream(); } catch (final IOException ex) { throw ExceptionUtils.toWebAppException(ex); } }
@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); } }
public static byte[] getBuffer(Part file) throws IOException { InputStream fileInStream = file.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); byte[] bytes = new byte[512]; int readBytes; while ((readBytes = fileInStream.read(bytes)) > 0) { outputStream.write(bytes, 0, readBytes); } return outputStream.toByteArray(); }
public static boolean isEmpty(Part file) { if(file==null){ return true; } return !(file.getSize()>0); }
protected String upload(HttpServletRequest request, StringManager smClient) { String message = ""; try { while (true) { Part warPart = request.getPart("deployWar"); if (warPart == null) { message = smClient.getString("htmlManagerServlet.deployUploadNoFile"); break; } String filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString("htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(deployed, filename); if (file.exists()) { message = smClient.getString("htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename, true); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString("htmlManagerServlet.deployUploadInServerXml", filename); break; } if (isServiced(name)) { message = smClient.getString("managerServlet.inService", name); } else { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch (Exception e) { message = smClient.getString("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } return message; }
@Override public Part getPart(String name) throws IOException, ServletException { return null; }