List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext
boolean hasNext() throws FileUploadException, IOException;
From source file:kg12.Ex12_1.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w ww . j ava2 s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_1</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:com.github.terma.gigaspacewebconsole.server.ImportServlet.java
private void safeDoPost(final HttpServletRequest request) throws Exception { final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iterator = upload.getItemIterator(request); ImportRequest importRequest = null;// w w w.j av a 2s.c o m String inputFile = null; InputStream inputStream = null; while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { if ("json".equals(name)) { importRequest = gson.fromJson(Streams.asString(stream), ImportRequest.class); } } else { inputFile = item.getName(); inputStream = stream; break; } } if (importRequest == null) throw new IOException("Expect 'json' parameter!"); if (inputStream == null) throw new IOException("Expect file to import!"); importRequest.file = inputFile; ProviderResolver.getProvider(importRequest.driver).import1(importRequest, inputStream); }
From source file:com.google.publicalerts.cap.validator.CapValidatorServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String input = null;//from w w w . j a va 2 s.co m String fileInput = null; String example = null; Set<CapProfile> profiles = Sets.newHashSet(); try { FileItemIterator itemItr = upload.getItemIterator(req); while (itemItr.hasNext()) { FileItemStream item = itemItr.next(); if ("input".equals(item.getFieldName())) { input = ValidatorUtil.readFully(item.openStream()); } else if (item.getFieldName().startsWith("inputfile")) { fileInput = ValidatorUtil.readFully(item.openStream()); } else if ("example".equals(item.getFieldName())) { example = ValidatorUtil.readFully(item.openStream()); } else if ("profile".equals(item.getFieldName())) { String profileCode = ValidatorUtil.readFully(item.openStream()); profiles.addAll(ValidatorUtil.parseProfiles(profileCode)); } } } catch (FileUploadException e) { throw new ServletException(e); } if (!CapUtil.isEmptyOrWhitespace(example)) { log.info("ExampleRequest: " + example); input = loadExample(example); profiles = ImmutableSet.of(); } else if (!CapUtil.isEmptyOrWhitespace(fileInput)) { log.info("FileInput"); input = fileInput; } input = (input == null) ? "" : input.trim(); if ("".equals(input)) { log.info("EmptyRequest"); doGet(req, resp); return; } ValidationResult result = capValidator.validate(input, profiles); req.setAttribute("input", input); req.setAttribute("profiles", ValidatorUtil.getProfilesJsp(profiles)); req.setAttribute("validationResult", result); req.setAttribute("lines", Arrays.asList(result.getInput().split("\n"))); req.setAttribute("timing", result.getTiming()); JSONArray alertsJs = new MapVisualizer(result.getValidAlerts()).getAlertsJs(); if (alertsJs != null) { req.setAttribute("alertsJs", alertsJs.toString()); } render(req, resp); }
From source file:etc.CloudStorage.java
/** * * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * * @return//from w w w.ja v a 2 s.c o m * @throws Exception * @param context */ public Mp3 uploadMp3(Context context) throws Exception { // make sure the context really is a multipart context... Mp3 mp3 = null; if (context.isMultipart()) { // This is the iterator we can use to iterate over the contents of the request. try { FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getName(); // Store audio file GcsFilename filename = new GcsFilename("musaemachine.com", name); // Store generated waveform image GcsFilename waveImageFile = new GcsFilename("musaemachine.com", removeExtension(name).concat(".png")); InputStream stream = item.openStream(); String contentType = item.getContentType(); System.out.println("--- " + contentType); GcsFileOptions options = new GcsFileOptions.Builder().acl("public-read").mimeType(contentType) .build(); byte[] audioBuffer = getByteFromStream(stream); GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, options); outputChannel.write(ByteBuffer.wrap(audioBuffer)); outputChannel.close(); // AudioWaveformCreator awc = new AudioWaveformCreator(); // byte[]waveform= awc.createWavForm(stream); // System.out.println("Buff Image---- "+waveform); // Saving waveform image // GcsOutputChannel waveFormOutputChannel = // gcsService.createOrReplace(waveImageFile, options); // waveFormOutputChannel.write(ByteBuffer.wrap(audioBuffer)); // waveFormOutputChannel.close(); // BodyContentHandler handler = new BodyContentHandler(); ParseContext pcontext = new ParseContext(); Metadata metadata = new Metadata(); mp3Parser.parse(stream, handler, metadata, pcontext); Double duration = Double.parseDouble(metadata.get("xmpDM:duration")); mp3 = new Mp3(name, duration); } } catch (Exception e) { e.printStackTrace(); } } return mp3; }
From source file:com.lemania.sis.server.servlet.GcsServlet.java
/** * Writes the payload of the incoming post as the contents of a file to GCS. * If the request path is /gcs/Foo/Bar this will be interpreted as a request * to create a GCS file named Bar in bucket Foo. * /*ww w . j av a 2 s . c o m*/ * @throws ServletException */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // GcsOutputChannel outputChannel = gcsService.createOrReplace(getFileName(req), GcsFileOptions.getDefaultInstance()); ServletFileUpload upload = new ServletFileUpload(); resp.setContentType("text/plain"); // InputStream fileContent = null; FileItemIterator iterator; try { iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // } else { fileContent = stream; break; } } } catch (FileUploadException e) { // e.printStackTrace(); } // copy(fileContent, Channels.newOutputStream(outputChannel)); }
From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST// w w w . jav a 2 s . com @Path("/upload") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process(@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 bookId = 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()) { // BookId if (item.getFieldName().equals("bookId")) { bookId = 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(); // fileItem.get(); size = bytes.length; // data = Base64.encodeBytes(bytes); } } } // Add the logo Book book = bookDAO.getBookById(bookId); // Update the front cover BookCategory cat = holder.getCategoryByName(book.getCategory()); BookCover cover = holder.getCoverByName(book.getCoverName()); String authorName = bookDAO.getAuthorName(book.getAuthorId()); //String frontBookCoverEncoded = imgService // .createDefaultFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes, authorName); //String smallFrontBookCoverEncoded = imgService // .createDefaultSmallFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes, authorName); // Save it // Add the logo book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size, frontBookCoverBytes, frontBookCoverSmallBytes); } 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:com.bristle.javalib.net.http.MultiPartFormDataParamMap.java
/************************************************************************** * Parse the specified HTTP request, initializing the map, and calling * the specified callback (if not null) for each file (if any) in the * streamed HTTP request. /*from w w w. j a v a 2 s . c o m*/ * *@param request The HTTP request *@param callback The callback class *@throws FileUploadException When the request is badly formed. *@throws IOException When an I/O error occurs reading the request. *@throws Throwable When thrown by the callback. **************************************************************************/ public void parseRequestStream(HttpServletRequest request, FileItemStreamCallBack callback) throws FileUploadException, IOException, Throwable { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String strParamName = fileItemStream.getFieldName(); InputStream streamIn = fileItemStream.openStream(); String strParamValue = Streams.asString(streamIn); put(strParamName, strParamValue); // Note: Can't do the following usefully. The Parameter // Map of the HTTP Request is effectively readonly. // This does not report an error, but is a no-op. // request.getParameterMap().put(strParamName, strParamValue); } else { if (callback != null) { callback.fullyProcessAFileItemStream(fileItemStream); } } } } else { putAll(request.getParameterMap()); } }
From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.fine("FeedServlet: doPost(...)"); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); PrintWriter out = null;/* w ww .j a va2s. c o m*/ try { out = response.getWriter(); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); String datasource = null; String feedtype = null; FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); //Disabled to allow easier update from HTML forms //if (item.isFormField()) { if (item.getFieldName().equals(FeedParser.XML_DATASOURCE)) { InputStream itemStream = null; try { itemStream = item.openStream(); datasource = IOUtils.toString(itemStream); } finally { IOUtils.closeQuietly(itemStream); } } else if (item.getFieldName().equals(FeedParser.XML_FEEDTYPE)) { InputStream itemStream = null; try { itemStream = item.openStream(); feedtype = IOUtils.toString(itemStream); } finally { IOUtils.closeQuietly(itemStream); } } else if (item.getFieldName().equals(FeedParser.XML_DATA)) { try { if (StringUtils.isBlank(datasource)) { throw new IllegalArgumentException("Datasource is blank"); } if (StringUtils.isBlank(feedtype)) { throw new IllegalArgumentException("Feedtype is blank"); } InputStream contentStream = null; try { contentStream = item.openStream(); final Feed feed = new FeedStaxParser().parse(datasource, feedtype, contentStream); Callable<Object> processFeedTask = new Callable<Object>() { @Override public Object call() throws Exception { FeedProcessor feedProcessor = new FeedProcessor(feed); feedProcessor.processFeed(); return null; } }; threadPoolExecutor.submit(processFeedTask); out.append(GsaFeedConnection.SUCCESS_RESPONSE); return; } catch (Exception e) { LOG.log(Level.SEVERE, "Exception while processing contentStream", e); } finally { IOUtils.closeQuietly(contentStream); } } finally { IOUtils.closeQuietly(out); } } //} } } } catch (Throwable e) { LOG.log(Level.SEVERE, "Exception while uploading", e); } finally { IOUtils.closeQuietly(out); } out.append(GsaFeedConnection.INTERNAL_ERROR_RESPONSE); }
From source file:com.qualogy.qafe.web.UploadService.java
public String uploadFile(HttpServletRequest request) { ServletFileUpload upload = new ServletFileUpload(); String errorMessage = ""; byte[] filecontent = null; String appUUID = null;//from ww w. j a va 2 s. c o m String windowId = null; String filename = null; String mimeType = null; InputStream inputStream = null; ByteArrayOutputStream outputStream = null; try { FileItemIterator fileItemIterator = upload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); inputStream = item.openStream(); // Read the file into a byte array. outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int len = 0; while (-1 != (len = inputStream.read(buffer))) { outputStream.write(buffer, 0, len); } if (filecontent == null) { filecontent = outputStream.toByteArray(); filename = item.getName(); mimeType = item.getContentType(); } if (item.getFieldName().indexOf(APP_UUID) > -1) { appUUID = item.getFieldName() .substring(item.getFieldName().indexOf(APP_UUID) + APP_UUID.length() + 1); } if (item.getFieldName().indexOf(APP_WINDOWID) > -1) { windowId = item.getFieldName() .substring(item.getFieldName().indexOf(APP_WINDOWID) + APP_WINDOWID.length() + 1); } } if ((appUUID != null) && (windowId != null)) { if (filecontent != null) { int maxFileSize = 0; if (ApplicationCluster.getInstance() .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE) != null) { String maxUploadFileSzie = ApplicationCluster.getInstance() .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE); if (StringUtils.isNumeric(maxUploadFileSzie)) { maxFileSize = Integer.parseInt(maxUploadFileSzie); } } if ((maxFileSize == 0) || (filecontent.length <= maxFileSize)) { Map<String, Object> fileData = new HashMap<String, Object>(); fileData.put(FILE_MIME_TYPE, mimeType); fileData.put(FILE_NAME, filename); fileData.put(FILE_CONTENT, filecontent); String uploadUUID = DataStore.KEY_LOOKUP_DATA + UniqueIdentifier.nextSeed().toString(); appUUID = concat(appUUID, windowId); ApplicationLocalStore.getInstance().store(appUUID, uploadUUID, fileData); return filename + "#" + UPLOAD_COMPLETE + "=" + uploadUUID; } else { errorMessage = "The maxmimum filesize in bytes is " + maxFileSize; } } } else { errorMessage = "Application UUID not specified"; } inputStream.close(); outputStream.close(); } catch (Exception e) { errorMessage = e.getMessage(); } return UPLOAD_ERROR + "=" + "File can not be uploaded: " + errorMessage; }
From source file:com.sifiso.dvs.util.DocFileUtil.java
public ResponseDTO downloadPDF(HttpServletRequest request, PlatformUtil platformUtil) throws FileUploadException { logger.log(Level.INFO, "######### starting PDF DOWNLOAD process\n\n"); ResponseDTO resp = new ResponseDTO(); InputStream stream = null;//from www.j a va 2 s. c om File rootDir; try { rootDir = dvsProperties.getDocumentDir(); 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; } PatientfileDTO dto = null; Gson gson = new Gson(); File clientDir = null, surgeryDir = null, doctorDir = 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, PatientfileDTO.class); if (dto != null) { surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getDoctor().getSurgeryID()); if (dto.getDoctorID() != null) { doctorDir = createDoctorDirectory(surgeryDir, doctorDir, dto.getDoctorID()); if (dto.getClientID() != null) { clientDir = createClientDirectory(doctorDir, clientDir); } } } } 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.getClientID() != null) { fileName = "client" + dto.getClientID() + ".pdf"; } imageFile = new File(clientDir, fileName); writeFile(stream, imageFile); resp.setStatusCode(0); resp.setMessage("Photo downloaded from mobile app "); //add database System.out.println("filepath: " + imageFile.getAbsolutePath()); } } } catch (FileUploadException | IOException | JsonSyntaxException ex) { logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex); throw new FileUploadException(); } return resp; }