List of usage examples for org.apache.commons.fileupload FileItemIterator next
FileItemStream next() throws FileUploadException, IOException;
From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] filecontent = null; ServletFileUpload upload = new ServletFileUpload(); InputStream inputStream = null; ByteArrayOutputStream outputStream = null; boolean isFirstLineHeader = false; String delimiter = ","; writeUploadInfo(request);/*from ww w . ja va2s. c o m*/ log(request.getHeader("User-Agent")); response.setContentType("text/html"); PrintWriter out = response.getWriter(); 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(); } if (FORM_PARAMETER_DELIMITER.equals(item.getFieldName())) { delimiter = outputStream.toString(); } else if (FORM_PARAMETER_ISFIRSTLINEHEADER.equals(item.getFieldName())) { if ("on".equals(outputStream.toString())) { isFirstLineHeader = true; } } } inputStream.close(); outputStream.close(); } catch (FileUploadException e) { ExceptionHelper.printStackTrace(e); } catch (RuntimeException e) { out.print("Conversion failed. Please check the file. Message :" + e.getMessage()); } DocumentParameter dp = new DocumentParameter(); dp.setDelimiter(delimiter); dp.setFirstFieldHeader(isFirstLineHeader); dp.setData(filecontent); try { DocumentOutput dout = documentService.processExcelUpload(dp); String uploadUUID = DataStore.KEY_LOOKUP_DATA + dout.getUuid(); ApplicationLocalStore.getInstance().store(uploadUUID, uploadUUID, dout.getData()); out.print("UUID=" + uploadUUID); } catch (Exception e) { out.print("Conversion failed. Please check the file (" + e.getMessage() + ")"); } }
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;//from ww w . jav a2 s .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 ww w . j ava2 s .c o 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: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. * //from www .j a va 2s . 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:controllers.UploadController.java
/** * //w w w . j a v a2 s . c o m * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * @param context * @return * @throws Exception */ public Result uploadFinish(Context context) throws Exception { // we are using a renderable inner class to stream the input again to // the user Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { try { // make sure the context really is a multipart context... if (context.isMultipart()) { // This is the iterator we can use to iterate over the // contents // of the request. FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); String contentType = item.getContentType(); if (contentType != null) { result.contentType(contentType); } else { contentType = mimeTypes.getMimeType(name); } ResponseStreams responseStreams = context.finalizeHeaders(result); if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println( "File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream ByteStreams.copy(stream, responseStreams.getOutputStream()); } } } } catch (IOException | FileUploadException exception) { throw new InternalServerErrorException(exception); } } }; return new Result(200).render(renderable); }
From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST/*from ww w . j av a 2s. c om*/ @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.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;//from w w w. j a v a2 s .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.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 w ww .j av a 2s .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; }
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. // www . j a v a 2 s. co 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: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/* ww w . j a va 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; }