List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:fi.helsinki.lib.simplerest.ItemsResource.java
@Post public Representation addItem(InputRepresentation rep) throws AuthorizeException, SQLException, IdentifierException { Collection collection = null; Context addItemContext = null; try {/*from ww w . j av a2s . com*/ //Get Context and make sure the user has the rights to add items. addItemContext = getAuthenticatedContext(); collection = Collection.find(addItemContext, this.collectionId); if (collection == null) { addItemContext.abort(); return errorNotFound(addItemContext, "Could not find the collection."); } } catch (SQLException e) { log.log(Priority.ERROR, e); return errorInternal(addItemContext, "SQLException"); } catch (NullPointerException e) { log.log(Priority.ERROR, e); return errorInternal(addItemContext, "NullPointerException"); } String title = null; String lang = null; try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("title")) { title = value; } else if (key.equals("lang")) { lang = value; } else if (key.equals("in_archive")) { ; } else if (key.equals("withdrawn")) { ; } else { return error(addItemContext, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } } } catch (FileUploadException e) { return errorInternal(addItemContext, e.toString()); } catch (NullPointerException e) { log.log(Priority.INFO, e); return errorInternal(context, e.toString()); } catch (IOException e) { return errorInternal(context, e.toString()); } if (title == null) { return error(addItemContext, "There was no title given.", Status.CLIENT_ERROR_BAD_REQUEST); } Item item = null; try { WorkspaceItem wsi = WorkspaceItem.create(addItemContext, collection, false); item = InstallItem.installItem(addItemContext, wsi); item.addMetadata("dc", "title", null, lang, title); item.update(); } catch (AuthorizeException ae) { return error(addItemContext, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (SQLException e) { log.log(Priority.FATAL, e, e); return errorInternal(addItemContext, e.toString()); } catch (IOException e) { log.log(Priority.FATAL, e, e); return errorInternal(addItemContext, e.toString()); } finally { if (addItemContext != null) { addItemContext.complete(); } } return successCreated("Created a new item.", baseUrl() + ItemResource.relativeUrl(item.getID())); }
From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java
private void parseReq(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w. j av a 2 s . co m*/ MF mf = MF.getFactory(); req.setCharacterEncoding("UTF-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); HashMap<String, String> map = new HashMap<String, String>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String field = item.getFieldName(); String value = Streams.asString(stream); map.put(field, value); stream.close(); } else { String filename = item.getName(); String[] extension = filename.split("\\."); String mail = map.get("mail"); if (mail != null) { filename = mail + "_" + String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } else { filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } map.put("filename", filename); byte[] buffer = IOUtils.toByteArray(stream); mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer, filename); stream.close(); } } String email = map.get("mail"); String firstName = map.get("firstName"); String lastName = map.get("lastName"); String dayS = map.get("day"); String monthS = map.get("month"); String yearS = map.get("year"); String password = map.get("password"); String filename = map.get("filename"); String date = yearS + "-" + monthS + "-" + dayS; char gender = map.get("gender").charAt(0); RequestDispatcher disp; Connection c = mf.getSQLService().getConnection(); String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')"; Statement statement = c.createStatement(); statement.executeUpdate(stm); statement.close(); c.close(); req.getSession(true).setAttribute("actualUser", email); req.getSession(true).setAttribute("edit", "false"); disp = req.getRequestDispatcher("SelectTopic.jsp"); disp.forward(req, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java
/** * Pseudo-constructor that allows the class to perform any initialization necessary. * * @param request an HttpServletRequest that has a content-type of multipart. * @param tempDir a File representing the temporary directory that can be used to store * file parts as they are uploaded if this is desirable * @param maxPostSize the size in bytes beyond which the request should not be read, and a * FileUploadLimitExceeded exception should be thrown * @throws IOException if a problem occurs processing the request of storing temporary * files//from w ww.j a va 2s . co m * @throws FileUploadLimitExceededException if the POST content is longer than the * maxPostSize supplied. */ @SuppressWarnings("unchecked") public void build(HttpServletRequest request, File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException { try { this.charset = request.getCharacterEncoding(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); FileItemIterator iterator = upload.getItemIterator(request); Map<String, List<String>> params = new HashMap<String, List<String>>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); // If it's a form field, add the string value to the list if (item.isFormField()) { List<String> values = params.get(item.getFieldName()); if (values == null) { values = new ArrayList<String>(); params.put(item.getFieldName(), values); } values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset)); } // Else store the file param else { TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(), item.getName()); int size = IOUtils.copy(stream, tempFile.getOutputStream()); FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size); files.put(item.getFieldName(), fileItem); } } // Now convert them down into the usual map of String->String[] for (Map.Entry<String, List<String>> entry : params.entrySet()) { List<String> values = entry.getValue(); this.parameters.put(entry.getKey(), values.toArray(new String[values.size()])); } } catch (FileUploadBase.SizeLimitExceededException slee) { throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize()); } catch (FileUploadException fue) { IOException ioe = new IOException("Could not parse and cache file upload data."); ioe.initCause(fue); throw ioe; } }
From source file:fi.helsinki.lib.simplerest.BundleResource.java
@Post public Representation addBitstream(InputRepresentation rep) { Context c = null;// w w w . j av a 2s. c om Bundle bundle = null; Bitstream bitstream = null; try { c = getAuthenticatedContext(); bundle = Bundle.find(c, this.bundleId); if (bundle == null) { return errorNotFound(c, "Could not find the bundle."); } Item[] items = bundle.getItems(); RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); String description = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("description")) { description = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (bitstream != null) { return error(c, "Only one file can added in one request.", Status.CLIENT_ERROR_BAD_REQUEST); } String name = fileItemStream.getName(); bitstream = bundle.createBitstream(fileItemStream.openStream()); bitstream.setName(name); bitstream.setSource(name); BitstreamFormat bf = FormatIdentifier.guessFormat(c, bitstream); bitstream.setFormat(bf); } } if (bitstream == null) { return error(c, "Request does not contain file(?)", Status.CLIENT_ERROR_BAD_REQUEST); } if (description != null) { bitstream.setDescription(description); } bitstream.update(); items[0].update(); // This updates at least the // sequence ID of the bitstream. c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Bitstream created.", baseUrl() + BitstreamResource.relativeUrl(bitstream.getID())); }
From source file:fi.helsinki.lib.simplerest.CommunitiesResource.java
@Post public Representation addCommunity(InputRepresentation rep) { Context c = null;/*w w w .j a v a 2s .com*/ Community community; try { c = getAuthenticatedContext(); community = Community.find(c, this.communityId); if (community == null) { return errorNotFound(c, "Could not find the community."); } } catch (SQLException e) { return errorInternal(c, "SQLException"); } String msg = null; String url = baseUrl(); try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); // Logo String bitstreamMimeType = null; byte[] logoBytes = null; // Community String name = null; String shortDescription = null; String introductoryText = null; String copyrightText = null; String sideBarText = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("name")) { name = value; } else if (key.equals("short_description")) { shortDescription = value; } else if (key.equals("introductory_text")) { introductoryText = value; } else if (key.equals("copyright_text")) { copyrightText = value; } else if (key.equals("side_bar_text")) { sideBarText = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (logoBytes != null) { return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST); } // TODO: Refer to comments in.... String fileName = fileItemStream.getName(); if (fileName.length() == 0) { continue; } int lastDot = fileName.lastIndexOf('.'); if (lastDot != -1) { String extension = fileName.substring(lastDot + 1); extension = extension.toLowerCase(); if (extension.equals("jpg") || extension.equals("jpeg")) { bitstreamMimeType = "image/jpeg"; } else if (extension.equals("png")) { bitstreamMimeType = "image/png"; } else if (extension.equals("gif")) { bitstreamMimeType = "image/gif"; } } if (bitstreamMimeType == null) { String err = "The logo filename extension was not recognised."; return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST); } InputStream inputStream = fileItemStream.openStream(); logoBytes = IOUtils.toByteArray(inputStream); } } msg = "Community created."; Community subCommunity = community.createSubcommunity(); subCommunity.setMetadata("name", name); subCommunity.setMetadata("short_description", shortDescription); subCommunity.setMetadata("introductory_text", introductoryText); subCommunity.setMetadata("copyright_text", copyrightText); subCommunity.setMetadata("side_bar_text", sideBarText); if (logoBytes != null) { ByteArrayInputStream byteStream; byteStream = new ByteArrayInputStream(logoBytes); subCommunity.setLogo(byteStream); } subCommunity.update(); Bitstream logo = subCommunity.getLogo(); if (logo != null) { BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType); logo.setFormat(bf); logo.update(); } url += CommunityResource.relativeUrl(subCommunity.getID()); c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated(msg, url); }
From source file:com.medallia.spider.api.DynamicInputImpl.java
/** * Creates a new {@link DynamicInputImpl} * @param request from which to read the request parameters *///from w w w . j av a2 s .c om public DynamicInputImpl(HttpServletRequest request) { @SuppressWarnings("unchecked") Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap()); this.inputParams = reqParams; if (ServletFileUpload.isMultipartContent(request)) { this.fileUploads = Maps.newHashMap(); Multimap<String, String> inputParamsWithList = ArrayListMultimap.create(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name())); } else { final String filename = item.getName(); final byte[] bytes = ByteStreams.toByteArray(stream); fileUploads.put(fieldName, new UploadedFile() { @Override public String getFilename() { return filename; } @Override public byte[] getBytes() { return bytes; } @Override public int getSize() { return bytes.length; } }); } } for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) { inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0])); } } catch (IOException | FileUploadException e) { throw new IllegalArgumentException("Failed to parse multipart", e); } } else { this.fileUploads = Collections.emptyMap(); } }
From source file:ca.nrc.cadc.rest.SyncInput.java
private void processMultiPart(FileItemIterator itemIterator) throws FileUploadException, IOException, ResourceNotFoundException { while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) processParameter(name, new String[] { Streams.asString(stream) }); else// ww w. ja v a 2 s . c o m processStream(name, item.getContentType(), stream); } }
From source file:controllers.PictureController.java
@FilterWith(SecureFilter.class) public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception { String fileLocation = ""; // Make sure the context really is a multipart context... if (context.isMultipart()) { Picture pic = new Picture(); // 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 (item.isFormField()) { String value = Streams.asString(stream); switch (name) { case "name": pic.setName(value);/*from w ww . j a va2s . co m*/ break; case "about": pic.setAbout(value); break; } } else { OutputStream outputStream = null; try { fileLocation = "public/pictures/" + item.getName(); outputStream = new FileOutputStream(new File(fileLocation)); int read = 0; byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } pic.setFile(item.getName()); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { // outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } pictureDao.postArticlePicture(username, pic); } reziseImage(fileLocation); // We always return ok. You don't want to do that in production ;) return Results.redirect("/picture/all"); }
From source file:fi.helsinki.lib.simplerest.CollectionsResource.java
@Post public Representation addCollection(InputRepresentation rep) { Context c = null;/* w w w . j av a 2 s .c om*/ Community community; try { c = getAuthenticatedContext(); community = Community.find(c, this.communityId); if (community == null) { return errorNotFound(c, "Could not find the community."); } } catch (SQLException e) { return errorInternal(c, "SQLException"); } String msg = null; String url = baseUrl(); try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); // Logo String bitstreamMimeType = null; byte[] logoBytes = null; // Collection String name = null; String shortDescription = null; String introductoryText = null; String copyrightText = null; String sideBarText = null; String provenanceDescription = null; String license = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("name")) { name = value; } else if (key.equals("short_description")) { shortDescription = value; } else if (key.equals("introductory_text")) { introductoryText = value; } else if (key.equals("copyright_text")) { copyrightText = value; } else if (key.equals("side_bar_text")) { sideBarText = value; } else if (key.equals("provenance_description")) { provenanceDescription = value; } else if (key.equals("license")) { license = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (logoBytes != null) { return error(c, "The collection can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST); } // TODO: Refer to comments in.... String fileName = fileItemStream.getName(); if (fileName.length() == 0) { continue; } int lastDot = fileName.lastIndexOf('.'); if (lastDot != -1) { String extension = fileName.substring(lastDot + 1); extension = extension.toLowerCase(); if (extension.equals("jpg") || extension.equals("jpeg")) { bitstreamMimeType = "image/jpeg"; } else if (extension.equals("png")) { bitstreamMimeType = "image/png"; } else if (extension.equals("gif")) { bitstreamMimeType = "image/gif"; } } if (bitstreamMimeType == null) { String err = "The logo filename extension was not recognised."; return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST); } InputStream inputStream = fileItemStream.openStream(); logoBytes = IOUtils.toByteArray(inputStream); } } Collection collection = community.createCollection(); collection.setMetadata("name", name); collection.setMetadata("short_description", shortDescription); collection.setMetadata("introductory_text", introductoryText); collection.setMetadata("copyright_text", copyrightText); collection.setMetadata("side_bar_text", sideBarText); collection.setMetadata("provenance_description", provenanceDescription); collection.setMetadata("license", license); if (logoBytes != null) { ByteArrayInputStream byteStream; byteStream = new ByteArrayInputStream(logoBytes); collection.setLogo(byteStream); } collection.update(); Bitstream logo = collection.getLogo(); if (logo != null) { BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType); logo.setFormat(bf); logo.update(); } url += CollectionResource.relativeUrl(collection.getID()); c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Collection created.", url); }
From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java
public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { ServletFileUpload upload = null;//from www. j av a2s.c o m WebTopSession.UploadedFile uploadedFile = null; HashMap<String, String> multipartParams = new HashMap<>(); try { String service = ServletUtils.getStringParameter(request, "service", true); String cntx = ServletUtils.getStringParameter(request, "context", true); String tag = ServletUtils.getStringParameter(request, "tag", null); if (!ServletFileUpload.isMultipartContent(request)) throw new Exception("No upload request"); IServiceUploadStreamListener istream = getUploadStreamListener(cntx); if (istream != null) { try { MapItem data = new MapItem(); // Empty response data // Defines the upload object upload = new ServletFileUpload(); FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { InputStream is = null; try { is = fis.openStream(); String key = fis.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(), tag, fis.getName(), -1, findMediaType(fis)); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("editable", isFileEditableInDocEditor(fis.getName())); // Handle listener, its implementation can stop // file upload throwing a UploadException. InputStream is = null; try { getEnv().getSession().addUploadedFile(uploadedFile); is = fis.openStream(); istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data); } finally { IOUtils.closeQuietly(is); getEnv().getSession().removeUploadedFile(uploadedFile, false); } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(false, ex1.getMessage()).printTo(out); } catch (Exception ex1) { throw ex1; } } else { try { MapItem data = new MapItem(); // Empty response data IServiceUploadListener iupload = getUploadListener(cntx); // Defines the upload object DiskFileItemFactory factory = new DiskFileItemFactory(); //TODO: valutare come imporre i limiti //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); upload = new ServletFileUpload(factory); List<FileItem> files = upload.parseRequest(request); // Plupload component (client-side) will upload multiple file // each in its own request. So we can skip loop on files. Iterator it = files.iterator(); while (it.hasNext()) { FileItem fi = (FileItem) it.next(); if (fi.isFormField()) { InputStream is = null; try { is = fi.getInputStream(); String key = fi.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Writes content into a temp file File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX); fi.write(file); // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag, fi.getName(), fi.getSize(), findMediaType(fi)); getEnv().getSession().addUploadedFile(uploadedFile); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("uploadId", uploadedFile.getUploadId()); data.add("editable", isFileEditableInDocEditor(fi.getName())); // Handle listener (if present), its implementation can stop // file upload throwing a UploadException. if (iupload != null) { try { iupload.onUpload(cntx, request, multipartParams, uploadedFile, data); } catch (UploadException ex2) { getEnv().getSession().removeUploadedFile(uploadedFile, true); throw ex2; } } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(ex1).printTo(out); } } } catch (Exception ex) { WebTopApp.logger.error("Error uploading", ex); new JsonResult(ex).printTo(out); } }