List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext
boolean hasNext() throws FileUploadException, IOException;
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; InputStream in = null;//from www . j a va 2 s .c om 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; InputStream in = null;/*from w w w .j av a 2 s . c o m*/ 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 {//from w w w . j a v a 2 s. 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 {/* w ww.j a v a 2 s .c o 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.restlet.example.ext.fileupload.FileUploadServerResource.java
@Post public Representation accept(Representation entity) throws Exception { Representation result = null;/* ww w. j a v a2 s .c om*/ if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); // 3/ Request is parsed by the handler which generates a // list of FileItems FileItemIterator fileIterator = upload.getItemIterator(entity); // Process only the uploaded item called "fileToUpload" // and return back boolean found = false; while (fileIterator.hasNext() && !found) { FileItemStream fi = fileIterator.next(); if (fi.getFieldName().equals("fileToUpload")) { // For the matter of sample code, it filters the multo // part form according to the field name. found = true; // consume the stream immediately, otherwise the stream // will be closed. StringBuilder sb = new StringBuilder("media type: "); sb.append(fi.getContentType()).append("\n"); sb.append("file name : "); sb.append(fi.getName()).append("\n"); BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream())); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } sb.append("\n"); result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN); } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return result; }
From source file:org.retrostore.request.RequestDataImpl.java
/** * Parses a multipart request and gets its files and parameters. *///w w w . j av a 2 s.c o m private static void parseMultipartContent(HttpServletRequest request, Map<String, String> formParams, List<UploadFile> uploadFiles) { if (!ServletFileUpload.isMultipartContent(request)) { return; } ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itemIterator = upload.getItemIterator(request); while (itemIterator.hasNext()) { FileItemStream file = itemIterator.next(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteStreams.copy(file.openStream(), bytesOut); byte[] bytes = bytesOut.toByteArray(); // If an item has a name, we think it's a file, otherwise we treat it as a regular string // parameter. if (!Strings.isNullOrEmpty(file.getName())) { uploadFiles.add(new UploadFile(file.getFieldName(), file.getName(), bytes)); } else { String str = new String(bytes, StandardCharsets.UTF_8); formParams.put(file.getFieldName(), str); } } } catch (FileUploadException | IOException e) { LOG.log(Level.WARNING, "Cannot parse request for filename.", e); } }
From source file:org.sharegov.cirm.utils.PhotoUploadResource.java
/** * Accepts and processes a representation posted to the resource. As * response, the content of the uploaded file is sent back the client. *//*from w w w.j a v a2s. c om*/ @Post public Representation accept(Representation entity) { // NOTE: the return media type here is TEXT_HTML because IE opens up a file download box // if it's APPLICATION_JSON as we'd want it. Representation rep = new StringRepresentation(GenUtils.ko("Unable to upload, bad request.").toString(), MediaType.TEXT_HTML); if (entity != null) { if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items // DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(); // List<FileItem> items; // // // 3/ Request is parsed by the handler which generates a // // list of FileItems InputStream is = null; Graphics2D g = null; FileOutputStream fos = null; ByteArrayOutputStream baos = null; try { FileItemIterator fit = upload.getItemIterator(entity); while (fit.hasNext()) { FileItemStream stream = fit.next(); if (stream.getFieldName().equals("uploadImage")) { String contentType = stream.getContentType(); if (contentType.startsWith("image")) { String extn = contentType.substring(contentType.indexOf("/") + 1); byte[] data = GenUtils.getBytesFromStream(stream.openStream(), true); String filename = "image_" + Refs.idFactory.resolve().newId(null) + "." + extn; //String filename = "srphoto_123" + "."+extn; // + OWLRefs.idFactory.resolve().newId("Photo"); // may add Photo class to ontology File f = new File(StartUp.config.at("workingDir").asString() + "/src/uploaded", filename); StringBuilder sb = new StringBuilder(""); String hostname = java.net.InetAddress.getLocalHost().getHostName(); boolean ssl = StartUp.config.is("ssl", true); int port = ssl ? StartUp.config.at("ssl-port").asInteger() : StartUp.config.at("port").asInteger(); if (ssl) sb.append("https://"); else sb.append("http://"); sb.append(hostname); if ((ssl && port != 443) || (!ssl && port != 80)) sb.append(":").append(port); sb.append("/uploaded/"); sb.append(filename); //Start : resize Image int rw = 400; int rh = 300; is = new ByteArrayInputStream(data); BufferedImage image = ImageIO.read(is); int w = image.getWidth(); int h = image.getHeight(); if (w > rw) { BufferedImage bi = new BufferedImage(rw, rh, image.getType()); g = bi.createGraphics(); g.drawImage(image, 0, 0, rw, rh, null); baos = new ByteArrayOutputStream(); ImageIO.write(bi, extn, baos); data = baos.toByteArray(); } //End: resize Image fos = new FileOutputStream(f); fos.write(data); Json j = GenUtils.ok().set("image", sb.toString()); //Json j = GenUtils.ok().set("image", filename); rep = new StringRepresentation(j.toString(), (MediaType) MediaType.TEXT_HTML); } else { rep = new StringRepresentation(GenUtils.ko("Please upload only Images.").toString(), MediaType.TEXT_HTML); } } } } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } if (baos != null) { try { baos.flush(); baos.close(); } catch (IOException e) { } } if (g != null) { g.dispose(); } } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return rep; }
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 ww . j av a 2 s . c om*/ 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); }// w w w.ja v a2s . c o 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 {/*from ww w . j ava 2s . c o m*/ // 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; }