Java Code Examples for javax.servlet.http.Part#getInputStream()

The following examples show how to use javax.servlet.http.Part#getInputStream() . 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 File: OneClickUnsubscription.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private static final boolean isCorrectParameterValue(final Part part) throws IOException {
	try(final InputStreamReader reader = new InputStreamReader(part.getInputStream())) {
		try(final BufferedReader in = new BufferedReader(reader)) {
			// Check if "List-Unsubscribe" contains "One-Click"
			if(!UNSUBSCRIBE_PARAMTER_VALUE.equals(in.readLine())) {
				if(LOGGER.isInfoEnabled()) {
					LOGGER.info("Content of multipart parameters does not denote One-Click unsubscription");
				}
				
				return false;
			}
			
			// Check if "List-Unsubscribe" does not contain more lines
			if(in.readLine() != null) {
				if(LOGGER.isInfoEnabled()) {
					LOGGER.info("Content of multipart parameters does not denote One-Click unsubscription");
				}
				
				return false;
			}
			
			return true;
		}
	}
	
}
 
Example 2
Source File: ModifyFoodInfoAction.java    From mealOrdering with MIT License 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
	
	Part image = request.getPart("image");
	
	InputStream imageInputStream = null;
	if(image.getSize() != 0)
		imageInputStream = image.getInputStream();
	
	SellerService service = new SellerServiceImpl();
	boolean success = service.modifyFoodInfo(request, imageInputStream);
	
	if(success){
		response.sendRedirect(request.getContextPath() + "/pages/profiles/seller_behind.jsp");	
	}else{
		response.setCharacterEncoding("utf-8");
		response.getWriter().print("修改失败!请稍后再试...");
	}
}
 
Example 3
Source File: MockMultiPartServlet.java    From requests with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);

    Collection<Part> parts = request.getParts();

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    OutputStream out = response.getOutputStream();
    for (Part part : parts) {
        out.write(part.getName().getBytes(StandardCharsets.UTF_8));
        out.write('\n');
        if (part.getContentType() != null) {
            out.write(part.getContentType().getBytes(StandardCharsets.UTF_8));
            out.write('\n');
        }
        try (InputStream in = part.getInputStream()) {
            InputStreams.transferTo(in, out);
        }
        out.write('\n');
    }
}
 
Example 4
Source File: TestVertxServerResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void sendPart_openInputStreamFailed(@Mocked Part part)
    throws IOException, InterruptedException, ExecutionException {
  IOException ioException = new IOException("forbid open stream");
  new Expectations() {
    {
      part.getInputStream();
      result = ioException;
    }
  };

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

  expectedException.expect(ExecutionException.class);
  expectedException.expectCause(Matchers.sameInstance(ioException));

  future.get();
}
 
Example 5
Source File: GraphicImportServlet.java    From BotLibre with 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;
	}
	GraphicBean bean = loginBean.getBean(GraphicBean.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.importGraphic(bytes);
			count++;
		}
		if (count == 0) {
			throw new BotException("Please select the graphic files to import");
		}
		response.sendRedirect("graphic?id=" + bean.getInstanceId());
	} catch (Throwable failed) {
		loginBean.error(failed);
		response.sendRedirect("browse-graphic.jsp");
	}
}
 
Example 6
Source File: TestInspectorImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void testViewHtmlById(String schemaId) throws IOException {
  Response response = inspector.getSchemaContentById(schemaId, SchemaFormat.HTML, false);

  Part part = response.getResult();
  Assert.assertEquals(schemaId + ".html", part.getSubmittedFileName());
  Assert.assertEquals("inline", 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 7
Source File: TestInspectorImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void getStaticResource() throws IOException {
  Response response = inspector.getStaticResource("index.html");

  Part part = response.getResult();
  Assert.assertEquals("inline", 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 8
Source File: TestInspectorImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void testViewSwaggerById(String schemaId, SchemaFormat format) throws IOException {
  Response response = inspector.getSchemaContentById(schemaId, format, false);

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

  try (InputStream is = part.getInputStream()) {
    Assert.assertEquals(schemas.get(schemaId), IOUtils.toString(is, StandardCharsets.UTF_8));
  }
}
 
Example 9
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean handleStream(VaadinSession session,
        StreamReceiver streamReceiver, StateNode owner, Part part)
        throws IOException {
    String name = part.getSubmittedFileName();
    InputStream stream = part.getInputStream();
    try {
        return handleFileUploadValidationAndData(session, stream,
                streamReceiver, name, part.getContentType(), part.getSize(),
                owner);
    } catch (UploadException e) {
        session.getErrorHandler().error(new ErrorEvent(e));
    }
    return false;
}
 
Example 10
Source File: TestClassPathStaticResourceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void normal() throws IOException {
  Response response = handler.handle("index.html");
  Part part = response.getResult();

  try (InputStream is = part.getInputStream()) {
    Assert.assertTrue(IOUtils.toString(is, StandardCharsets.UTF_8).endsWith("<html></html>"));
  }
  Assert.assertEquals("text/html", part.getContentType());
  Assert.assertEquals("text/html", response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE));
  Assert.assertEquals("inline", response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION));
}
 
Example 11
Source File: ImportTranslationsServlet.java    From BotLibre with 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;
	}
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		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();
				loginBean.importTranslations(stream);
				count++;
			}
		}
		if (count == 0) {
			throw new BotException("Please select the XML file");
		}
	} catch (Throwable failed) {
		loginBean.error(failed);
	}
	response.sendRedirect("translation.jsp");		
}
 
Example 12
Source File: CodeFirstJaxrs.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Path("/upload2")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String fileUpload2(@FormParam("file1") Part file1, @FormParam("message") String message) throws IOException {
  try (InputStream is1 = file1.getInputStream()) {
    String content1 = IOUtils.toString(is1, StandardCharsets.UTF_8);
    return String.format("%s:%s:%s:%s",
        file1.getSubmittedFileName(),
        file1.getContentType(),
        content1,
        message);
  }
}
 
Example 13
Source File: AvatarImportServlet.java    From BotLibre with 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 14
Source File: RestServlet.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T parse(Class<T> type) throws IOException, ServletException
{
    T providedObject;
    final ObjectMapper mapper = new ObjectMapper();

    if (_headers.containsKey("Content-Type") && _request.getHeader("Content-Type")
                                                        .startsWith("multipart/form-data"))
    {
        Map<String, Object> items = new LinkedHashMap<>();
        Map<String, String> fileUploads = new HashMap<>();
        Collection<Part> parts = _request.getParts();
        for (Part part : parts)
        {
            if ("data".equals(part.getName()) && "application/json".equals(part.getContentType()))
            {
                items = mapper.readValue(part.getInputStream(), LinkedHashMap.class);
            }
            else
            {
                byte[] data = new byte[(int) part.getSize()];
                try (InputStream inputStream = part.getInputStream())
                {
                    inputStream.read(data);
                }
                fileUploads.put(part.getName(), DataUrlUtils.getDataUrlForBytes(data));
            }
        }
        items.putAll(fileUploads);

        providedObject = (T) items;
    }
    else
    {
        providedObject = mapper.readValue(_request.getInputStream(), type);
    }
    return providedObject;
}
 
Example 15
Source File: PostResource.java    From fenixedu-cms with 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 16
Source File: RemoteAccess.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Map<String, byte[]> getPostMap(HttpServletRequest request) throws IOException {
    Map<String, byte[]> map = new HashMap<>();
    Map<String, String[]> pm = request.getParameterMap();
    if (pm != null && pm.size() > 0) {
        for (Map.Entry<String, String[]> entry: pm.entrySet()) {
            String[] v = entry.getValue();
            if (v != null && v.length > 0) map.put(entry.getKey(), v[0].getBytes(StandardCharsets.UTF_8));
        }
    } else try {
        request.setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement); // without that we get a IllegalStateException in getParts()
        final byte[] b = new byte[1024];
        for (Part part: request.getParts()) {
            String name = part.getName();
            InputStream is = part.getInputStream();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int c;
            try {while ((c = is.read(b, 0, b.length)) > 0) {
                baos.write(b, 0, c);
            }} finally {is.close();}
            map.put(name, baos.toByteArray());
        }
    } catch (IOException | ServletException | IllegalStateException e) {
        Data.logger.debug("Parsing of POST multipart failed", e);
        throw new IOException(e.getMessage());
    }
    return map;
}
 
Example 17
Source File: WebCampaign.java    From bidder with Apache License 2.0 5 votes vote down vote up
public String multiPart(Request baseRequest, HttpServletRequest request, MultipartConfigElement config)
		throws Exception {

	HttpSession session = request.getSession(false);
	String user = (String) session.getAttribute("user");

	baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, config);
	Collection<Part> parts = request.getParts();
	for (Part part : parts) {
		System.out.println("" + part.getName());
	}

	Part filePart = request.getPart("file");

	InputStream imageStream = filePart.getInputStream();
	byte[] resultBuff = new byte[0];
	byte[] buff = new byte[1024];
	int k = -1;
	while ((k = imageStream.read(buff, 0, buff.length)) > -1) {
		byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size
														// = bytes already
														// read + bytes last
														// read
		System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy
																		// previous
																		// bytes
		System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy
																// current
																// lot
		resultBuff = tbuff; // call the temp buffer as your result buff
	}

	Map response = new HashMap();
	return getString(response);

}
 
Example 18
Source File: SdkEndpoint.java    From sepia-assist-server with MIT License 5 votes vote down vote up
/**
 * Receive a file with proper service data.
 * @param req - request
 * @param reqParams - request parameters from form body
 * @param userId - ID of user
 * @throws IOException 
 * @throws ServletException 
 * @return file name
 */
private static String receiveServiceFile(Request req, RequestParameters reqParams, String userId) throws IOException, ServletException{
	Part filePart = req.raw().getPart(UPLOAD_FILE_KEY);		//getPart needs to use same "name" as input field in form
       String fileName = getFileName(filePart);
       
       //Class file
       if (fileName.endsWith(".class")){
       	//Get right folder and make sure it exists
       	File uploadDir = new File(ConfigServices.getCustomServicesBaseFolder() + userId);
           uploadDir.mkdirs();

           //Path tempFile = Files.createTempFile(uploadDir.toPath(), "", "");
           Path tempFile = Paths.get(uploadDir.toString(), fileName);
           Debugger.println("upload-service - Downloading file to: " + uploadDir.getPath(), 3);

           try (InputStream input = filePart.getInputStream()){
           	//Simply store file
               Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
           }
           Debugger.println("upload-service - File '" + fileName + "' stored.", 3);
       
       //Java file
       }else if (fileName.endsWith(".java")){
       	//Get source code
       	String sourceCode;
           try (InputStream input = filePart.getInputStream()){
       		sourceCode = FilesAndStreams.getStringFromStream(input, StandardCharsets.UTF_8, "\n");
       	}
           String classNameSimple = fileName.replace(".java", "");
           
       	//Compile code (or throw exception)
           compileServiceSourceCode(userId, classNameSimple, sourceCode);
       	
       //Wrong or not supported file
       }else{
       	throw new RuntimeException("File '" + fileName + "' is NOT A VALID (or supported) SERVICE FILE!");
       }
       
       return fileName;
}
 
Example 19
Source File: SellerServiceImpl.java    From OnlineShoppingSystem with MIT License 4 votes vote down vote up
public boolean addGoodsImage(HttpServletRequest request, int goodsId) {
    boolean flag = false;
    int count = -1;
    ArrayList<Part> images;
    try {
        images = (ArrayList<Part>) request.getParts();
        count = images.size();
        for (Part image : images) {
            if (image.getContentType() == null) {
                continue;
            }
            // System.out.println(image.getContentType());
            InputStream imageInputStream = null;

            if (image != null && image.getSize() != 0) {
                try {
                    imageInputStream = image.getInputStream();

                    if (imageInputStream != null) {
                        String imagedir = request.getServletContext()
                                .getInitParameter("imagedir")
                                + File.separator;
                        // 图片名格式:20161123204206613375.jpg。
                        // 代表 2016-11-23 20:42:06.613 + 3 位 0 - 9 间随机数字
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                        StringBuilder imageName = new StringBuilder(
                                dateFormat.format(new Date()));
                        Random random = new Random();
                        for (int i = 0; i < 3; ++i) {
                            imageName.append(random.nextInt(10));
                        }
                        imageName.append(".jpg");

                        String targetFile = imagedir + imageName;
                        try {
                            FileUtils.copyInputStreamToFile(imageInputStream,
                                    new File(targetFile));
                            count--;

                            dao.addGoodsImage("/images/goods/" + imageName, goodsId);   // 更新数据库

                            // System.out.println(imagedir);
                            // System.out.println(imageName);
                            // System.out.println(count);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally {
                    imageInputStream.close();
                }
            }
        }
    } catch (IOException | ServletException e3) {
        e3.printStackTrace();
    }
    if (count == 0) {
        flag = true;
    } else {
        flag = false;
    }

    return flag;
}
 
Example 20
Source File: MultipartPortlet.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@ActionMethod(portletName = "MultipartPortlet")
public void handleDialog(ActionRequest req, ActionResponse resp) throws IOException, PortletException {
   List<String> lines = new ArrayList<String>();
   req.getPortletSession().setAttribute("lines", lines);

   lines.add("handling dialog");
   StringBuilder txt = new StringBuilder(128);

   String clr = req.getActionParameters().getValue("color");
   txt.append("Color: ").append(clr);
   lines.add(txt.toString());
   logger.debug(txt.toString());

   resp.getRenderParameters().setValue("color", clr);

   txt.setLength(0);
   Part part = null;
   try {
      part = req.getPart("file");
   } catch (Throwable t) {}
   
   if ((part != null) && (part.getSubmittedFileName() != null) && 
         (part.getSubmittedFileName().length() > 0)) {
      txt.append("Uploaded file name: ").append(part.getSubmittedFileName());
      txt.append(", part name: ").append(part.getName());
      txt.append(", size: ").append(part.getSize());
      txt.append(", content type: ").append(part.getContentType());
      lines.add(txt.toString());
      logger.debug(txt.toString());
      txt.setLength(0);
      txt.append("Headers: ");
      String sep = "";
      for (String hdrname : part.getHeaderNames()) {
         txt.append(sep).append(hdrname).append("=").append(part.getHeaders(hdrname));
         sep = ", ";
      }
      lines.add(txt.toString());
      logger.debug(txt.toString());

      // Store the file in a temporary location in the webapp where it can be served. 

      try {
         String fn = part.getSubmittedFileName();
         String ct = part.getContentType();
         
         if (ct != null && (ct.equals("text/plain") || ct.matches("image/(?:png|gif|jpg|jpeg)"))) {
            
            String ext = ct.replaceAll("\\w+/", "");
            lines.add("determined extension " + ext + " from content type " + ct);
            File img = getFile();
            if (img.exists()) {
               lines.add("deleting existing temp file: " + img.getCanonicalPath());
               img.delete();
            }
            InputStream is = part.getInputStream();
            Files.copy(is, img.toPath(), StandardCopyOption.REPLACE_EXISTING);
            
         } else {
            lines.add("Bad file type. Must be plain text or image (gif, jpeg, png).");
         }

         resp.getRenderParameters().setValue("fn", fn);
         resp.getRenderParameters().setValue("ct", ct);

      } catch (Exception e) {
         lines.add("Exception doing I/O: " + e.toString());
         
         txt.setLength(0);
         txt.append("Problem getting temp file: " + e.getMessage() + "\n");
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         pw.flush();
         txt.append(sw.toString());
         logger.warn(txt.toString());
      }
   } else {
      lines.add("file part was null");
   }

}