List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext
boolean hasNext() throws FileUploadException, IOException;
From source file:com.sifiso.dvs.util.PhotoUtil.java
public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil) throws FileUploadException { logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n"); ResponseDTO resp = new ResponseDTO(); InputStream stream = null;//from w ww. j a v a 2 s. c o m File rootDir; try { rootDir = dvsProperties.getImageDir(); logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath()); if (!rootDir.exists()) { rootDir.mkdir(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Properties file problem", ex); resp.setMessage("Server file unavailable. Please try later"); resp.setStatusCode(114); return resp; } PhotoUploadDTO dto = null; Gson gson = new Gson(); File doctorFileDir = null, surgeryDir = null; try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); stream = item.openStream(); if (item.isFormField()) { if (name.equalsIgnoreCase("JSON")) { String json = Streams.asString(stream); if (json != null) { logger.log(Level.INFO, "picture with associated json: {0}", json); dto = gson.fromJson(json, PhotoUploadDTO.class); if (dto != null) { surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getSurgeryID()); if (dto.getDoctorID() > 0) { doctorFileDir = createDoctorDirectory(surgeryDir, doctorFileDir, dto.getDoctorID()); } } } else { logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL.."); } } } else { File imageFile = null; if (dto == null) { continue; } DateTime dt = new DateTime(); String fileName = ""; if (dto.isIsFullPicture()) { fileName = "f" + dt.getMillis() + ".jpg"; } else { fileName = "t" + dt.getMillis() + ".jpg"; } if (dto.getPatientfileID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getPatientfileID() + ".jpg"; } else { fileName = "t" + dto.getPatientfileID() + ".jpg"; } } // switch (dto.getPictureType()) { case PhotoUploadDTO.FILES_DOCTOR: imageFile = new File(doctorFileDir, fileName); break; case PhotoUploadDTO.FILES_SURGERY: imageFile = new File(surgeryDir, fileName); } writeFile(stream, imageFile); resp.setStatusCode(0); resp.setMessage("Photo downloaded from mobile app "); //add database System.out.println("filepath: " + imageFile.getAbsolutePath()); //create uri /*int index = imageFile.getAbsolutePath().indexOf("monitor_images"); if (index > -1) { String uri = imageFile.getAbsolutePath().substring(index); System.out.println("uri: " + uri); dto.setUri(uri); } dto.setDateUploaded(new Date()); if (dto.isIsFullPicture()) { dto.setThumbFlag(null); } else { dto.setThumbFlag(1); } dataUtil.addPhotoUpload(dto);*/ } } } catch (FileUploadException | IOException | JsonSyntaxException ex) { logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex); throw new FileUploadException(); } return resp; }
From source file:de.mpg.imeji.presentation.upload.UploadServlet.java
/** * Download the file on the disk in a tmp file * * @param req/*from ww w. j ava2s .co m*/ * @return * @throws FileUploadException * @throws IOException */ private UploadItem doUpload(HttpServletRequest req) { try { final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iter = upload.getItemIterator(req); UploadItem uploadItem = new UploadItem(); while (iter.hasNext()) { final FileItemStream fis = iter.next(); if (!fis.isFormField()) { uploadItem.setFilename(fis.getName()); final File tmp = TempFileUtil.createTempFile("upload", null); StorageUtils.writeInOut(fis.openStream(), new FileOutputStream(tmp), true); uploadItem.setFile(tmp); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); StorageUtils.writeInOut(fis.openStream(), out, true); uploadItem.getParams().put(fis.getFieldName(), out.toString("UTF-8")); } } return uploadItem; } catch (final Exception e) { LOGGER.error("Error file upload", e); } return new UploadItem(); }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
@Test public void testMaxSizeLimitUnknownContentLength() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1);//w w w . ja v a2s. c o m upload.setSizeMax(300); // the first item should be within the max size limit // set the read limit to 10 to simulate a "real" stream // otherwise the buffer would be immediately filled MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); req.setContentLength(-1); req.setReadLimit(10); FileItemIterator it = upload.getItemIterator(req); assertTrue(it.hasNext()); FileItemStream item = it.next(); assertFalse(item.isFormField()); assertEquals("file1", item.getFieldName()); assertEquals("foo1.tab", item.getName()); { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); } // the second item is over the size max, thus we expect an error try { // the header is still within size max -> this shall still succeed assertTrue(it.hasNext()); } catch (Exception e) { // FileUploadBase.SizeException has protected access: if (e.getClass().getSimpleName().equals("SizeException")) { fail(); } else { throw e; } } item = it.next(); try { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); fail(); } catch (FileUploadIOException e) { // expected } }
From source file:de.egore911.reader.servlets.OpmlImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = getUserOrRedirect(resp); if (user == null) { return;/*from w w w . j a v a 2 s . c om*/ } boolean success = false; String reason = null; ServletFileUpload upload = new ServletFileUpload(); CategoryDao categoryDao = new CategoryDao(); FeedUserDao feedUserDao = new FeedUserDao(); FeedDao feedDao = new FeedDao(); try { FileItemIterator iter = upload.getItemIterator(req); // Parse the request while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if ("subscriptions".equals(name) && !item.isFormField() && "text/xml".equals(item.getContentType())) { try (InputStream stream = item.openStream()) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(stream); document.getDocumentElement().normalize(); Element opml = document.getDocumentElement(); if (!"opml".equals(opml.getTagName())) { throw new ServletException("Invalid XML"); } NodeList nodes = opml.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if ("body".equals(element.getTagName())) { if (countFeeds(element.getChildNodes()) < 20) { importRecursive(categoryDao, feedUserDao, feedDao, user, Category.ROOT, element.getChildNodes()); success = true; } else { reason = "to_many_feeds"; } } } } } catch (ParserConfigurationException | SAXException e) { throw new ServletException(e.getMessage(), e); } } } } catch (FileUploadException e) { throw new ServletException(e.getMessage(), e); } if (success) { resp.sendRedirect("/reader"); } else { String redirectTo = "/import?msg=import_failed"; if (reason != null) { redirectTo += "&reason=" + reason; } resp.sendRedirect(redirectTo); } }
From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java
/** * Receive an upload book assest//from www .j ava 2 s. co m * * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest) */ @Override @POST @Path("/upload2") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process2(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String description = null; String descriptionDetail = null; String hoursOfWorkStr = null; String bookId = null; String action = null; String dataType = null; String contentType = null; //String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // description if (item.getFieldName().equals("description")) { description = Streams.asString(stream); } // detail if (item.getFieldName().equals("descriptionDetail")) { descriptionDetail = Streams.asString(stream); } // Work hours if (item.getFieldName().equals("hoursOfWork")) { hoursOfWorkStr = Streams.asString(stream); } // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } // action if (item.getFieldName().equals("action")) { action = Streams.asString(stream); } // datatype if (item.getFieldName().equals("dataType")) { dataType = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); size = bytes.length; } } } // convert the hoursOfWork int hoursOfWork = 0; if (hoursOfWorkStr != null) { try { hoursOfWork = Integer.parseInt(hoursOfWorkStr); } catch (Exception e) { log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr + " to an int in BookAssetUploadServiceImpl. Converting to 0."); hoursOfWork = 0; } } // Verify that the session user is the author or co-author of // the book. They would be the only ones who could add to the // book. String userId = userToken.getUserId(); boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId); if (isAuthor == false) { throw new Exception("The user " + userId + " is not the author or co-author of the book."); } // Add to the database bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType, BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size, hoursOfWork, userId); // Tell Solr about the update queueBookEvent.fire(new QueueBookEvent(bookId, userId)); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:edu.isi.wings.portal.servlets.HandleUpload.java
/** * Handle an HTTP POST request from Plupload. *///from w ww . j ava 2 s.c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Config config = new Config(request); if (!config.checkDomain(request, response)) return; Domain dom = config.getDomain(); String name = null; String id = null; String storageDir = dom.getDomainDirectory() + "/"; int chunk = 0; int chunks = 0; boolean isComponent = false; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try { InputStream input = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); String value = Streams.asString(input); if ("name".equals(fieldName)) name = value.replaceAll("[^\\w\\.\\-_]+", "_"); else if ("id".equals(fieldName)) id = value; else if ("type".equals(fieldName)) { if ("data".equals(value)) storageDir += dom.getDataLibrary().getStorageDirectory(); else if ("component".equals(value)) { storageDir += dom.getConcreteComponentLibrary().getStorageDirectory(); isComponent = true; } else { storageDir = System.getProperty("java.io.tmpdir"); } } else if ("chunk".equals(fieldName)) chunk = Integer.parseInt(value); else if ("chunks".equals(fieldName)) chunks = Integer.parseInt(value); } else if (name != null) { File storageDirFile = new File(storageDir); if (!storageDirFile.exists()) storageDirFile.mkdirs(); File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part"); saveUploadFile(input, uploadFile, chunk); } } catch (Exception e) { this.printError(out, e.getMessage()); e.printStackTrace(); } } } catch (FileUploadException e1) { this.printError(out, e1.getMessage()); e1.printStackTrace(); } } else { this.printError(out, "Not multipart data"); } if (chunks == 0 || chunk == chunks - 1) { // Done upload File partUpload = new File(storageDir + File.separator + name + ".part"); File finalUpload = new File(storageDir + File.separator + name); partUpload.renameTo(finalUpload); String mime = new Tika().detect(finalUpload); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload)); // Check if this is a zip file and unzip if needed String location = finalUpload.getAbsolutePath(); if (isComponent && mime.equals("application/zip")) { String dirname = new URI(id).getFragment(); location = StorageHandler.unzipFile(finalUpload, dirname, storageDir); finalUpload.delete(); } this.printOk(out, location); } }
From source file:com.google.dotorg.translation_workflow.servlet.UploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, MalformedURLException { String rawProjectId = request.getParameter("projectId"); try {/*from w ww. ja v a 2 s. com*/ ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(1048576); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); Cloud cloud = Cloud.open(); int projectId = Integer.parseInt(rawProjectId); Project project = cloud.getProjectById(projectId); TextValidator nameValidator = TextValidator.BRIEF_STRING; String invalidRows = ""; int validRows = 0; try { FileItemIterator iterator = upload.getItemIterator(request); int articlesLength = 0; while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); String fileContents = null; if (!contentType.equalsIgnoreCase("text/csv")) { logger.warning("Invalid filetype upload " + contentType); response.sendRedirect( "/project_overview?project=" + rawProjectId + "&msg=invalid_type"); } try { fileContents = IOUtils.toString(in); PersistenceManager pm = cloud.getPersistenceManager(); Transaction tx = pm.currentTransaction(); tx.begin(); String[] lines = fileContents.split("\n"); List<Translation> newTranslations = new ArrayList<Translation>(); articlesLength = lines.length; validRows = articlesLength; int lineNo = 0; for (String line : lines) { lineNo++; line = line.replaceAll("\",", "\";"); line = line.replaceAll("\"", ""); String[] fields = line.split(";"); String articleName = fields[0].replace("_", " "); articleName = nameValidator.filter(URLDecoder.decode(articleName)); try { URL url = new URL(fields[1]); String category = ""; String difficulty = ""; if (fields.length > 2) { category = nameValidator.filter(fields[2]); } if (fields.length > 3) { difficulty = nameValidator.filter(fields[3]); } Translation translation = project.createTranslation(articleName, url.toString(), category, difficulty); newTranslations.add(translation); } catch (MalformedURLException e) { validRows--; invalidRows = invalidRows + "," + lineNo; logger.warning("Invalid URL : " + fields[1]); } } pm.makePersistentAll(newTranslations); tx.commit(); } finally { IOUtils.closeQuietly(in); } } } cloud.close(); logger.info(validRows + " of " + articlesLength + " articles uploaded from csv to the project " + project.getId() + " by User :" + user.getUserId()); if (invalidRows.length() > 0) { response.sendRedirect( "/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1)); } else { response.sendRedirect("/project_overview?project=" + rawProjectId); } /*response.sendRedirect("/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1));*/ } catch (SizeLimitExceededException e) { logger.warning("Exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); response.sendRedirect("/project_overview?project=" + rawProjectId + "&msg=size_exceeded"); } } catch (Exception ex) { logger.info("String " + ex.toString()); throw new ServletException(ex); } }
From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // text/html IE?? response.setContentType("text/plain;charset=utf-8"); StringBuffer responseMessage = new StringBuffer("<?xml version=\"1.0\" encoding=\"GB2312\"?>"); responseMessage.append("<root>"); StringBuffer errorMsg = new StringBuffer(responseMessage).append("<result>").append("FAILED") .append("</result>"); String info = ""; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = null; try {/*from www . ja v a2s .c o m*/ iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { info = "Form field " + name + " with value " + Streams.asString(stream) + " detected."; responseMessage = new StringBuffer(responseMessage).append(errorMsg).append("<info>") .append(info).append("</info>"); finishPrintResponseMsg(response, responseMessage); return; } else { BufferedInputStream inputStream = new BufferedInputStream(stream);// ? String uploadPath = getUploadPath(request, "upload"); if (uploadPath != null) { String fileName = getOutputFileName(item); String outputFilePath = getOutputFilePath(uploadPath, fileName); int widthdist = 72; int heightdist = 72; widthdist = 200; heightdist = 200; BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File(outputFilePath)));// ? Streams.copy(inputStream, outputStream, true); // // stream.close(); reduceImg(inputStream, outputFilePath, outputFilePath, widthdist, heightdist, 0); stream.close(); responseMessage.append("<result>").append("SUCCESS").append("</result>"); responseMessage.append("<info>"); responseMessage.append(fileName); responseMessage.append(info).append("</info>"); } else { responseMessage = errorMsg.append("<info>").append("") .append("</info>"); } } } } catch (Exception e) { e.printStackTrace(); responseMessage = errorMsg.append("<info>").append(":" + e.getMessage()) .append("</info>"); } finishPrintResponseMsg(response, responseMessage); }
From source file:com.medallia.spider.api.DynamicInputImpl.java
/** * Creates a new {@link DynamicInputImpl} * @param request from which to read the request parameters *//*from w w w . j ava2 s.c om*/ public DynamicInputImpl(HttpServletRequest request) { @SuppressWarnings("unchecked") Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap()); this.inputParams = reqParams; if (ServletFileUpload.isMultipartContent(request)) { this.fileUploads = Maps.newHashMap(); Multimap<String, String> inputParamsWithList = ArrayListMultimap.create(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name())); } else { final String filename = item.getName(); final byte[] bytes = ByteStreams.toByteArray(stream); fileUploads.put(fieldName, new UploadedFile() { @Override public String getFilename() { return filename; } @Override public byte[] getBytes() { return bytes; } @Override public int getSize() { return bytes.length; } }); } } for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) { inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0])); } } catch (IOException | FileUploadException e) { throw new IllegalArgumentException("Failed to parse multipart", e); } } else { this.fileUploads = Collections.emptyMap(); } }
From source file:com.google.phonenumbers.PhoneNumberParserServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String phoneNumber = null;//from w w w . j a va2 s . com String defaultCountry = null; String languageCode = "en"; // Default languageCode to English if nothing is entered. String regionCode = ""; String fileContents = null; ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(50000); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName.equals("phoneNumber")) { phoneNumber = Streams.asString(in, "UTF-8"); } else if (fieldName.equals("defaultCountry")) { defaultCountry = Streams.asString(in).toUpperCase(); } else if (fieldName.equals("languageCode")) { String languageEntered = Streams.asString(in).toLowerCase(); if (languageEntered.length() > 0) { languageCode = languageEntered; } } else if (fieldName.equals("regionCode")) { regionCode = Streams.asString(in).toUpperCase(); } } else { try { fileContents = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } StringBuilder output; if (fileContents.length() == 0) { output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode); resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().println("<html><head>"); resp.getWriter() .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />"); resp.getWriter().println("</head>"); resp.getWriter().println("<body>"); resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>"); resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>"); resp.getWriter().println("Language entered: " + languageCode + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>")); } else { output = getOutputForFile(defaultCountry, fileContents); resp.setContentType("text/html"); } resp.getWriter().println(output); resp.getWriter().println("</body></html>"); }