List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:org.owasp.esapi.waf.internal.InterceptingHTTPServletRequest.java
public InterceptingHTTPServletRequest(HttpServletRequest request) throws FileUploadException, IOException { super(request); allParameters = new Vector<Parameter>(); allParameterNames = new Vector<String>(); /*//w w w. ja v a 2 s . c o m * Get all the regular parameters. */ Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String param = (String) e.nextElement(); allParameters.add(new Parameter(param, request.getParameter(param), false)); allParameterNames.add(param); } /* * Get all the multipart fields. */ isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { requestBody = new RandomAccessFile(File.createTempFile("oew", "mpc"), "rw"); byte buffer[] = new byte[CHUNKED_BUFFER_SIZE]; long size = 0; int len = 0; while (len != -1 && size <= Integer.MAX_VALUE) { len = request.getInputStream().read(buffer, 0, CHUNKED_BUFFER_SIZE); if (len != -1) { size += len; requestBody.write(buffer, 0, len); } } is = new RAFInputStream(requestBody); ServletFileUpload sfu = new ServletFileUpload(); FileItemIterator iter = sfu.getItemIterator(this); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); /* * If this is a regular form field, add it to our * parameter collection. */ if (item.isFormField()) { String value = Streams.asString(stream); allParameters.add(new Parameter(name, value, true)); allParameterNames.add(name); } else { /* * This is a multipart content that is not a * regular form field. Nothing to do here. */ } } requestBody.seek(0); } }
From source file:org.plista.kornakapi.web.servlets.BatchAddCandidatesServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator fileItems;// w ww . java2 s .c om InputStream in = null; boolean fileProcessed = false; Storage storage = this.getDomainIndependetStorage(); try { fileItems = upload.getItemIterator(request); while (fileItems.hasNext()) { FileItemStream item = fileItems.next(); if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) { in = item.openStream(); Iterator<Candidate> candidates = new CSVCandidateFileIterator(in); storage.batchAddCandidates(candidates, batchSize); fileProcessed = true; break; } } } catch (FileUploadException e) { throw new IOException(e); } finally { Closeables.closeQuietly(in); } if (!fileProcessed) { throw new IllegalStateException("Unable to find supplied data file!"); } }
From source file:org.plista.kornakapi.web.servlets.BatchDeleteCandidatesServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator fileItems;// w ww . j ava 2 s . c o m InputStream in = null; boolean fileProcessed = false; Storage storage = this.getDomainIndependetStorage(); try { fileItems = upload.getItemIterator(request); while (fileItems.hasNext()) { FileItemStream item = fileItems.next(); if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) { in = item.openStream(); Iterator<Candidate> candidates = new CSVCandidateFileIterator(in); storage.batchDeleteCandidates(candidates, batchSize); fileProcessed = true; break; } } } catch (FileUploadException e) { throw new IOException(e); } finally { Closeables.closeQuietly(in); } if (!fileProcessed) { throw new IllegalStateException("Unable to find supplied data file!"); } }
From source file:org.plista.kornakapi.web.servlets.BatchSetPreferencesServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator fileItems;// ww w . ja va2s .c o m InputStream in = null; boolean fileProcessed = false; Storage storage = this.getDomainIndependetStorage(); try { fileItems = upload.getItemIterator(request); while (fileItems.hasNext()) { FileItemStream item = fileItems.next(); if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) { in = item.openStream(); Iterator<Preference> preferences = new CSVPreferenceFileIterator(in); storage.batchSetPreferences(preferences, batchSize); fileProcessed = true; break; } } } catch (FileUploadException e) { throw new IOException(e); } finally { Closeables.closeQuietly(in); } if (!fileProcessed) { throw new IllegalStateException("Unable to find supplied data file!"); } }
From source file:org.polymap.rap.updownload.upload.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w ww . j a v a2s .c o m*/ FileItemIterator it = fileUpload.getItemIterator(req); while (it.hasNext()) { FileItemStream item = it.next(); String name = item.getFieldName(); InputStream in = item.openStream(); try { if (item.isFormField()) { log.info("Form field " + name + " with value " + Streams.asString(in) + " detected."); } else { log.info("File field " + name + " with file name " + item.getName() + " detected."); String key = req.getParameter("handler"); assert key != null; IUploadHandler handler = handlers.get(key); // for the upload field we always get just one item (which has the length of the request!?) int length = req.getContentLength(); handler.uploadStarted(item.getName(), item.getContentType(), length, in); } } finally { IOUtils.closeQuietly(in); } } } catch (Exception e) { log.warn("", e); throw new RuntimeException(e); } }
From source file:org.polymap.rap.updownload.upload.UploadService.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try {// www .ja va 2 s. co m FileItemIterator it = fileUpload.getItemIterator(request); while (it.hasNext()) { FileItemStream item = it.next(); try (InputStream in = item.openStream()) { if (item.isFormField()) { log.info("Form field " + item.getFieldName() + " with value " + Streams.asString(in) + " detected."); } else { log.info("File field " + item.getFieldName() + " with file name " + item.getName() + " detected."); String handlerId = request.getParameter(ID_REQUEST_PARAM); assert handlerId != null; IUploadHandler handler = handlers.get(handlerId); ClientFile clientFile = new ClientFile() { @Override public String getName() { return item.getName(); } @Override public String getType() { return item.getContentType(); } @Override public long getSize() { // for the upload field we always get just one item (which has the length of the request!?) return request.getContentLength(); } }; handler.uploadStarted(clientFile, in); } } } } catch (Exception e) { log.warn("", e); throw new RuntimeException(e); } }
From source file:org.rapidcontext.core.web.Request.java
/** * Returns the next available file item stream in the request. * If the request is not a file upload request or no further * files are available, null will be returned. Note that file * upload requests must be handled differently from ordinary * requests, since the normal request parameter access is * limited to query parameters. Also, the file items returned * from this method are controlled to be actual files, and any * other request parameters are simply ignored.<p> * * The recommended way to implement file uploads is by sending * them as the sole request parameter in a form and storing the * file content for later processing. Preferably the form * posting is also performed from an IFRAME in order to process * in the background./*w w w. j a v a 2 s . c o m*/ * * @return the next file item stream, or * null if none is available * * @throws IOException if the file upload */ public FileItemStream getNextFile() throws IOException { if (isFileUpload() && fileIter == null) { try { fileIter = new ServletFileUpload().getItemIterator(request); } catch (FileUploadException e) { throw new IOException("failed to parse file upload: " + e.getMessage()); } } if (fileIter != null) { try { while (fileIter.hasNext()) { FileItemStream item = fileIter.next(); if (!item.isFormField()) { return item; } } } catch (FileUploadException e) { throw new IOException("failed to parse file upload: " + e.getMessage()); } } return null; }
From source file:org.sigmah.server.endpoint.export.sigmah.ExportModelServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { final Authentication authentication = retrieveAuthentication(req); boolean hasPermission = false; if (authentication != null) { final User user = authentication.getUser(); ProfileDTO profile = SigmahAuthDictionaryServlet.aggregateProfiles(user, null, injector); hasPermission = ProfileUtils.isGranted(profile, GlobalPermissionEnum.VIEW_ADMIN); }// w w w.jav a2s.c o m if (hasPermission) { final ServletFileUpload fileUpload = new ServletFileUpload(); final HashMap<String, String> properties = new HashMap<String, String>(); byte[] data = null; try { final FileItemIterator iterator = fileUpload.getItemIterator(req); // Iterating on the fields sent into the request while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); LOG.debug("field '" + name + "' = '" + value + '\''); // The current field is a property properties.put(name, value); } else { // The current field is a file LOG.debug("field '" + name + "' (FILE)"); final ByteArrayOutputStream serializedData = new ByteArrayOutputStream(); long dataSize = 0L; int b = stream.read(); while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) { serializedData.write(b); dataSize++; b = stream.read(); } stream.close(); data = serializedData.toByteArray(); } } } catch (FileUploadException ex) { LOG.warn("Error while receiving a serialized model.", ex); } if (data != null) { // A file has been received final String type = properties.get("type"); final ModelHandler handler = handlers.get(type); if (handler != null) { if (handler instanceof ProjectModelHandler) { final String projectModelTypeAsString = properties.get("project-model-type"); try { final ProjectModelType projectModelType = ProjectModelType .valueOf(projectModelTypeAsString); ((ProjectModelHandler) handler).setProjectModelType(projectModelType); } catch (IllegalArgumentException e) { LOG.debug("Bad value for project model type: " + projectModelTypeAsString, e); } } final ByteArrayInputStream inputStream = new ByteArrayInputStream(data); try { handler.importModel(inputStream, injector.getInstance(EntityManager.class), authentication); } catch (ExportException ex) { LOG.error("Model import error, type: " + type, ex); resp.sendError(500); } } else { LOG.warn("The asked model type (" + type + ") doesn't have any handler registered."); resp.sendError(501); } } else { LOG.warn("No file has been received."); resp.sendError(400); } } else { LOG.warn("Unauthorized access to the import service from user " + authentication); resp.sendError(401); } } else { LOG.warn("The request doesn't have the correct enctype."); resp.sendError(400); } }
From source file:org.sigmah.server.file.util.MultipartRequest.java
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException { if (!ServletFileUpload.isMultipartContent(request)) { LOGGER.error("Request content is not multipart."); throw new StatusServletException(Response.SC_PRECONDITION_FAILED); }//from ww w.j av a 2 s .co m final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request); while (iterator.hasNext()) { // Gets the first HTTP request element. final FileItemStream item = iterator.next(); if (item.isFormField()) { final String value = Streams.asString(item.openStream(), "UTF-8"); properties.put(item.getFieldName(), value); } else if (callback != null) { callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType()); } } }
From source file:org.sigmah.server.servlet.ImportServlet.java
private byte[] readFileAndProperties(final HttpServletRequest request, final Map<String, String> properties) throws FileUploadException, IOException { byte[] data = null; final ServletFileUpload fileUpload = new ServletFileUpload(); final FileItemIterator iterator = fileUpload.getItemIterator(request); // Iterating on the fields sent into the request while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); LOG.debug("field '" + name + "' = '" + value + '\''); // The current field is a property properties.put(name, value); } else {// w ww . j ava 2s.com // The current field is a file LOG.debug("field '" + name + "' (FILE)"); final ByteArrayOutputStream serializedData = new ByteArrayOutputStream(); long dataSize = 0L; int b = stream.read(); while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) { serializedData.write(b); dataSize++; b = stream.read(); } stream.close(); data = serializedData.toByteArray(); } } return data; }