List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:com.google.sampling.experiential.server.EventServlet.java
private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) { PrintWriter out = null;//from w ww . j a va2 s . c o m try { out = resp.getWriter(); } catch (IOException e1) { log.log(Level.SEVERE, "Cannot get an output PrintWriter!"); } try { boolean isDevInstance = isDevInstance(req); ServletFileUpload fileUploadTool = new ServletFileUpload(); fileUploadTool.setSizeMax(50000); resp.setContentType("text/html;charset=UTF-8"); FileItemIterator iterator = fileUploadTool.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = null; try { in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); String fileContents = null; fileContents = IOUtils.toString(in); out.println("length: " + fileContents.length()); out.println(fileContents); saveCSV(fileContents, isDevInstance); } } catch (ParseException e) { log.info("Parse Exception: " + e.getMessage()); out.println("Could not parse your csv upload: " + e.getMessage()); } finally { in.close(); } } } catch (SizeLimitExceededException e) { log.info("SizeLimitExceededException: " + e.getMessage()); out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); return; } catch (IOException e) { log.severe("IOException: " + e.getMessage()); out.println("Error in receiving file."); } catch (FileUploadException e) { log.severe("FileUploadException: " + e.getMessage()); out.println("Error in receiving file."); } }
From source file:com.zimbra.cs.service.UserServletContext.java
public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException { String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM; String filename = null;// w w w .j a v a2 s .c om InputStream is = null; final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024; if (limit == 0) { if (req.getParameter("lbfums") != null) { limit = Provisioning.getInstance().getLocalServer() .getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE); } else { limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE); } } boolean doCsrfCheck = false; if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) { doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload sfu = new ServletFileUpload(); try { FileItemIterator iter = sfu.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); if (fis.isFormField()) { is = fis.openStream(); params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8")); if (doCsrfCheck && !this.csrfAuthSucceeded) { String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN); if (UserServlet.log.isDebugEnabled()) { String paramValue = req.getParameter(UserServlet.QP_AUTH); UserServlet.log.debug( "CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue); } if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) { setCsrfAuthSucceeded(Boolean.FALSE); UserServlet.log.debug( "CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken); throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate)); } else { setCsrfAuthSucceeded(Boolean.TRUE); } } is.close(); is = null; } else { is = new UploadInputStream(fis.openStream(), limit); break; } } } catch (UserServletException e) { throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e); } catch (Exception e) { throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString()); } if (is == null) throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content"); } else { ContentType ctype = new ContentType(req.getContentType()); String contentEncoding = req.getHeader("Content-Encoding"); contentType = ctype.getContentType(); filename = ctype.getParameter("name"); if (filename == null || filename.trim().equals("")) filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit); } if (filename == null || filename.trim().equals("")) filename = "unknown"; else params.put(UserServlet.UPLOAD_NAME, filename); params.put(UserServlet.UPLOAD_TYPE, contentType); ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength()); return is; }
From source file:n3phele.service.nShell.NParser.java
public NParser(org.apache.commons.fileupload.FileItemStream item) throws IOException { this(new BlockStreamer(item.openStream())); }
From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java
public void doSetRequest(RequestContext ctx) { /*/*from w w w. j ava 2 s.c o m*/ * The result of the upload request, returned * to the requestor; note, that the result must * be a text response */ boolean result = false; HttpServletRequest request = ctx.getRequest(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { /* * Create new file upload handler */ ServletFileUpload upload = new ServletFileUpload(); /* * Parse the request */ FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItem = iter.next(); if (fileItem.isFormField()) { // not supported } else { /* * Hook into the upload request to some virus scanning * using the scanner factory of this application */ byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream()); boolean checked = MalwareScanner.scanForViruses(bytes); if (checked) { String item = this.method.getAttribute(MethodConstants.ATTR_ITEM); String type = this.method.getAttribute(MethodConstants.ATTR_TYPE); if ((item == null) || (type == null)) { this.sendNotImplemented(ctx); } else { String fileName = FilenameUtils.getName(fileItem.getName()); String mimeType = fileItem.getContentType(); try { result = upload(item, type, fileName, mimeType, bytes); } catch (Exception e) { sendBadRequest(ctx, e); } } } } } } /* * Send html response */ if (result == true) { this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse()); } else { this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse()); } } catch (Exception e) { this.sendBadRequest(ctx, e); } finally { } }
From source file:com.oprisnik.semdroid.SemdroidServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("doPost"); StringBuilder sb = new StringBuilder(); try {//from ww w . j av a2 s . c o m ServletFileUpload upload = new ServletFileUpload(); // set max size (-1 for unlimited size) upload.setSizeMax(1024 * 1024 * 30); // 30MB upload.setHeaderEncoding("UTF-8"); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { // Process regular form fields // String fieldname = item.getFieldName(); // String fieldvalue = item.getString(); // log.info("Got form field: " + fieldname + " " + fieldvalue); } else { // Process form file field (input type="file"). String fieldname = item.getFieldName(); String filename = FilenameUtils.getBaseName(item.getName()); log.info("Got file: " + filename); InputStream filecontent = null; try { filecontent = item.openStream(); // analyze String txt = analyzeApk(filecontent); if (txt != null) { sb.append(txt); } else { sb.append("Error. Could not analyze ").append(filename); } log.info("Analysis done!"); } finally { if (filecontent != null) { filecontent.close(); } } } } response.getWriter().print(sb.toString()); } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request.", e); } catch (Exception ex) { log.warning("Exception: " + ex.getMessage()); log.throwing(this.getClass().getName(), "doPost", ex); } }
From source file:com.netflix.zuul.scriptManager.FilterScriptManagerServlet.java
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); org.apache.commons.fileupload.FileItemIterator it = null; try {/*from w w w .j av a 2s . c om*/ it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream stream = it.next(); InputStream input = stream.openStream(); // NOTE: we are going to pull the entire stream into memory // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger byte[] uploadedBytes = getBytesFromInputStream(input); input.close(); if (uploadedBytes.length == 0) { setUsageError(400, "ERROR: Body contained no data.", response); return null; } return new String(uploadedBytes); } } catch (FileUploadException e) { throw new IOException(e.getMessage()); } return null; }
From source file:edu.umn.msi.tropix.webgui.server.UploadController.java
@ServiceMethod(secure = true) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { LOG.debug("In UploadController.handleRequest"); //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId")); //Preconditions.checkState(userId != null); final String userId = userSession.getGridId(); LOG.debug("Upload by user with id " + userId); String clientId = request.getParameter("clientId"); if (!StringUtils.hasText(clientId)) { clientId = UUID.randomUUID().toString(); }//from ww w. ja v a 2 s. c om final String endStr = request.getParameter("end"); final String startStr = request.getParameter("start"); final String zipStr = request.getParameter("zip"); final String lastUploadStr = request.getParameter("lastUpload"); final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false; final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true; LOG.trace("Upload request with startStr " + startStr); final StringWriter rawJsonWriter = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter); final FileItemFactory factory = new DiskFileItemFactory(); final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr) : request.getContentLength(); long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L; final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Deal with international file names final FileItemIterator iter = upload.getItemIterator(request); // Setup message conditionalSampleComponent to track upload progress... final ProgressMessageSupplier supplier = new ProgressMessageSupplier(); supplier.setId(userId + "/" + clientId); supplier.setName("Upload File(s) to Web Application"); final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl(); progressTracker.setUserGridId(userId); progressTracker.setCometPusher(cometPusher); progressTracker.setProgressMessageSupplier(supplier); jsonWriter.object(); jsonWriter.key("result"); jsonWriter.array(); while (iter.hasNext()) { final FileItemStream item = iter.next(); if (item.isFormField()) { continue; } File destination; InputStream inputStream = null; OutputStream outputStream = null; if (!isZip) { final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName(); LOG.debug("Handling upload of file with name " + fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(fileName); recordJsonInfo(jsonWriter, info); destination = info.getTempLocation(); } else { destination = FILE_UTILS.createTempFile(); } try { inputStream = item.openStream(); outputStream = FILE_UTILS.getFileOutputStream(destination); bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength, progressTracker); if (isZip) { ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() { public File apply(final String fileName) { final String cleanedUpFileName = FilenameUtils.getName(fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName); recordJsonInfo(jsonWriter, info); return info.getTempLocation(); } }); } } finally { IO_UTILS.closeQuietly(inputStream); IO_UTILS.closeQuietly(outputStream); if (isZip) { FILE_UTILS.deleteQuietly(destination); } } } if (lastUploads) { progressTracker.complete(); } jsonWriter.endArray(); jsonWriter.endObject(); // response.setStatus(200); final String json = rawJsonWriter.getBuffer().toString(); LOG.debug("Upload json response " + json); response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this response.getOutputStream().println(json); return null; }
From source file:fi.iki.elonen.SimpleWebServer.java
private Response getUploadMsgAndExec(IHTTPSession session) throws FileUploadException, IOException { uploader = new NanoFileUpload(new DiskFileItemFactory()); files = new HashMap<String, List<FileItem>>(); FileItemIterator iter = uploader.getItemIterator(session); String fileName = "", newFileName = ""; try {//from w w w.j a v a 2s .c om while (iter.hasNext()) { FileItemStream item = iter.next(); fileName = item.getName(); newFileName = rootDirs.get(0) + "/".concat(fileName); FileItem fileItem = uploader.getFileItemFactory().createItem(item.getFieldName(), item.getContentType(), item.isFormField(), newFileName); files.put(fileItem.getFieldName(), Arrays.asList(new FileItem[] { fileItem })); try { Streams.copy(item.openStream(), (new FileOutputStream(newFileName)), true); } catch (Exception e) { System.err.println(e.getMessage()); } fileItem.setHeaders(item.getHeaders()); } } catch (FileUploadException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return newFixedLengthResponse( "<html><body> \n File: " + fileName + " upload to " + newFileName + "! \n </body></html>\n"); }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * API endpoint to import a file or list of files as a new layer or layers into into an existing * store inGeoServer. //from ww w. ja v a 2 s . co m * Files are provided as MediaType.MULTIPART_FORM_DATA_VALUE in the request * @param wsName The workspace to import the files into * @param storeName The store to import the layers into. If null, tries to import into a new * store. * @param request The HTTP request * @return a JSON object describing the result of the import. See {@link #get(String, Long) get}. * @throws Exception if the request is invalid, or the file upload fails. */ @RequestMapping(value = "/{wsName:.+}/{storeName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseBody JSONObj importFile(@PathVariable String wsName, @PathVariable String storeName, HttpServletRequest request) throws Exception { // grab the workspace Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); // get the uploaded files FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain one or more files"); } // create a new temp directory for the uploaded file File uploadDir = Files.createTempDirectory("importFile").toFile(); if (!uploadDir.exists()) { throw new RuntimeException("Unable to create directory for file upload"); } uploadDir.deleteOnExit(); // pass off the uploaded file(s) to the importer Directory dir = new Directory(uploadDir); while (files.hasNext()) { FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { String name = item.getName(); dir.accept(name, stream); } } Long id; if (storeName == null) { id = importer.createContextAsync(dir, ws, null); } else { StoreInfo store = findStore(wsName, storeName, geoServer.getCatalog()); id = importer.createContextAsync(dir, ws, store); } return get(wsName, createImport(importer.getTask(id)), request); }
From source file:n3phele.service.rest.impl.CommandResource.java
@Consumes(MediaType.MULTIPART_FORM_DATA) @POST//from w w w . ja va 2s . co m @Produces(MediaType.TEXT_PLAIN) @Path("import") @RolesAllowed("authenticated") public Response importer(@Context HttpServletRequest request) { try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); // JAXBContext jc = JAXBContext.newInstance(CommandDefinitions.class); // Unmarshaller u = jc.createUnmarshaller(); // CommandDefinitions a = (CommandDefinitions) u.unmarshal(stream); JSONJAXBContext jc = new JSONJAXBContext(CommandDefinitions.class); JSONUnmarshaller u = jc.createJSONUnmarshaller(); CommandDefinitions a = u.unmarshalFromJSON(stream, CommandDefinitions.class); StringBuilder response = new StringBuilder( "Processing " + a.getCommand().size() + " commands\n"); URI requestor = UserResource.toUser(securityContext).getUri(); for (CommandDefinition cd : a.getCommand()) { response.append(cd.getName()); response.append("....."); Command existing = null; try { if (cd.getUri() != null && cd.getUri().toString().length() != 0) { try { existing = dao.command().get(cd.getUri()); } catch (NotFoundException e1) { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; } else { if (c.isPreferred() && cd.isPreferred()) { c.setPreferred(false); dao.command().update(c); } } } } catch (Exception e) { // not found } } } else { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; break; } } } catch (Exception e) { // not found } } } catch (NotFoundException e) { } if (existing == null) { response.append(addCommand(cd)); } else { // update or illegal operation boolean isOwner = requestor.equals(existing.getOwner()); boolean mismatchedUri = (cd.getUri() != null && cd.getUri().toString().length() != 0) && !cd.getUri().equals(existing.getUri()); log.info("requestor is " + requestor + " owner is " + existing.getOwner() + " isOwner " + isOwner); log.info("URI in definition is " + cd.getUri() + " existing is " + existing.getUri() + " mismatchedUri " + mismatchedUri); if (!isOwner || mismatchedUri) { response.append("ignored: already exists"); } else { response.append(updateCommand(cd, existing)); response.append("\nupdated uri " + existing.getUri()); } } response.append("\n"); //response.append("</li>"); } //response.append("</ol>"); return Response.ok(response.toString()).build(); } } } catch (JAXBException e) { log.log(Level.WARNING, "JAXBException", e); } catch (FileUploadException e) { log.log(Level.WARNING, "FileUploadException", e); } catch (IOException e) { log.log(Level.WARNING, "IOException", e); } return Response.notModified().build(); }