List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:kg12.Ex12_2.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w. jav a2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_2</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); InputStream is = item.openStream(); String fileName = item.getName(); int len = 0; byte[] buffer = new byte[fileSizeMax]; FileOutputStream fos = new FileOutputStream( "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName); try { while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { fos.close(); } } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:ai.ilikeplaces.servlets.GenericFileGrabber.java
private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session) throws IOException, FileUploadException { String returnVal = "Sorry! No Items To Process"; final Map<String, String> parameterMap = new HashMap<String, String>(); final File tempFile = getTempFile(); String userFileExtension = null; while (iter.hasNext()) { final FileItemStream item = iter.next(); final String paramName = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) {//Parameter-Value final String paramValue = Streams.asString(stream); parameterMap.put(paramName, paramValue); }/*from ww w .j a v a 2s .c o m*/ if (!item.isFormField()) { final String usersFileName = item.getName(); final int extensionDotIndex = usersFileName.lastIndexOf("."); userFileExtension = usersFileName.substring(extensionDotIndex + 1); final FileOutputStream fos = new FileOutputStream(tempFile); int byteCount = 0; while (true) { final int dataByte = stream.read(); if (byteCount++ > UPLOAD_LIMIT) { fos.close(); tempFile.delete(); return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true); } if (dataByte != -1) { fos.write(dataByte); } else { break;//break loop } } fos.close(); } } final FileUploadListenerFace<File> fulf; /** * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be * created per request and added to the listener pool(list or array whatever). */ switch (Integer.parseInt(parameterMap.get("type"))) { case 1: fulf = CDNProfilePhoto.getProfilePhotoCDNLocal(); break; case 2: fulf = CDNAlbumPrivateEvent.getAlbumPhotoCDNLocal(); break; case 3: fulf = CDNAlbumTribe.getAlbumTribeCDNLocal(); break; default: return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true); } if (tempFile == null) { return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true); } return fulf.run(tempFile, parameterMap, userFileExtension, session); }
From source file:freedots.web.MusicXML2BrailleServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Score score = null;/*from www. j a v a 2 s.c o m*/ BrailleEncoding brailleEncoding = BrailleEncoding.UnicodeBraille; int width = 40, height = 25; InputStream stream = null; ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { final FileItemStream item = iterator.next(); if (item.getFieldName().compareTo("file.xml") == 0) { String extension = "xml"; if (item.getName().endsWith(".mxl")) extension = "mxl"; score = parseMusicXML(item.openStream(), extension); } else if (item.getFieldName().compareTo("encoding") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null) { try { brailleEncoding = Enum.valueOf(BrailleEncoding.class, line); } catch (IllegalArgumentException e) { LOG.info("Unknown encoding " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("width") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_COLUMNS_PER_LINE && value <= MAX_COLUMNS_PER_LINE) width = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("height") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_LINES_PER_PAGE && value <= MAX_LINES_PER_PAGE) height = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } } } catch (org.apache.commons.fileupload.FileUploadException e) { LOG.info("FileUploadException error"); resp.sendError(500); } if (score != null) { writeResult(score, width, height, Method.SectionBySection, brailleEncoding, resp); } else { resp.sendRedirect("/"); } }
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:fi.helsinki.lib.simplerest.RootCommunitiesResource.java
@Post public Representation addCommunity(InputRepresentation rep) { Context c = null;// w ww.j av a 2s . c o m Community community; try { c = getAuthenticatedContext(); community = Community.create(null, c); RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); String name = null; String shortDescription = null; String introductoryText = null; String copyrightText = null; String sideBarText = null; Bitstream bitstream = null; String bitstreamMimeType = 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 (bitstream != null) { return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST); } // I did not manage to use FormatIdentifier.guessFormat // here, so let's do it by ourselves... I would prefer to // use the actual file content and not its name, but let's // keep the code simple... 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); } bitstream = community.setLogo(fileItemStream.openStream()); // We don't set the format of the logo (bitstream) here, // it's done in the code below... } } community.setMetadata("name", name); community.setMetadata("short_description", shortDescription); community.setMetadata("introductory_text", introductoryText); community.setMetadata("copyright_text", copyrightText); community.setMetadata("side_bar_text", sideBarText); community.update(); // Set the format (jpeg, png, or gif) of logo: Bitstream logo = community.getLogo(); if (logo != null) { BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType); logo.setFormat(bf); logo.update(); } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Community created.", baseUrl() + CommunityResource.relativeUrl(community.getID())); }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
@Test public void testMaxSizeLimitUnknownContentLength() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1);// w ww . j a v a 2 s .c o m upload.setSizeMax(300); // the first item should be within the max size limit // set the read limit to 10 to simulate a "real" stream // otherwise the buffer would be immediately filled MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); req.setContentLength(-1); req.setReadLimit(10); FileItemIterator it = upload.getItemIterator(req); assertTrue(it.hasNext()); FileItemStream item = it.next(); assertFalse(item.isFormField()); assertEquals("file1", item.getFieldName()); assertEquals("foo1.tab", item.getName()); { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); } // the second item is over the size max, thus we expect an error try { // the header is still within size max -> this shall still succeed assertTrue(it.hasNext()); } catch (Exception e) { // FileUploadBase.SizeException has protected access: if (e.getClass().getSimpleName().equals("SizeException")) { fail(); } else { throw e; } } item = it.next(); try { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); fail(); } catch (FileUploadIOException e) { // expected } }
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 . ja v a2 s . co m //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:fi.helsinki.lib.simplerest.BundleResource.java
@Post public Representation addBitstream(InputRepresentation rep) { Context c = null;/* www. ja va2 s. com*/ 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:cn.webwheel.ActionSetter.java
@SuppressWarnings("unchecked") public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException { SetterConfig cfg = ai.getSetterConfig(); List<SetterInfo> setters; if (action != null) { Class cls = action.getClass(); setters = setterMap.get(cls);// w w w .j av a 2 s . c om if (setters == null) { synchronized (this) { setters = setterMap.get(cls); if (setters == null) { Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap); map.put(cls, setters = parseSetters(cls)); setterMap = map; } } } } else { setters = Collections.emptyList(); } List<SetterInfo> args = argMap.get(ai.actionMethod); if (args == null) { synchronized (this) { args = argMap.get(ai.actionMethod); if (args == null) { Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap); map.put(ai.actionMethod, args = parseArgs(ai.actionMethod)); argMap = map; } } } if (setters.isEmpty() && args.isEmpty()) return new Object[0]; Map<String, Object> params; try { if (cfg.getCharset() != null) { request.setCharacterEncoding(cfg.getCharset()); } } catch (UnsupportedEncodingException e) { // } if (ServletFileUpload.isMultipartContent(request)) { params = new HashMap<String, Object>(request.getParameterMap()); request.setAttribute(WRPName, params); ServletFileUpload fileUpload = new ServletFileUpload(); if (cfg.getCharset() != null) { fileUpload.setHeaderEncoding(cfg.getCharset()); } if (cfg.getFileUploadSizeMax() != 0) { fileUpload.setSizeMax(cfg.getFileUploadSizeMax()); } if (cfg.getFileUploadFileSizeMax() != 0) { fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax()); } boolean throwe = false; try { FileItemIterator it = fileUpload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { String s = Streams.asString(fis.openStream(), cfg.getCharset()); Object o = params.get(fis.getFieldName()); if (o == null) { params.put(fis.getFieldName(), new String[] { s }); } else if (o instanceof String[]) { String[] ss = (String[]) o; String[] nss = new String[ss.length + 1]; System.arraycopy(ss, 0, nss, 0, ss.length); nss[ss.length] = s; params.put(fis.getFieldName(), nss); } } else if (!fis.getName().isEmpty()) { File tempFile; try { tempFile = File.createTempFile("wfu", null); } catch (IOException e) { throwe = true; throw e; } FileExImpl fileEx = new FileExImpl(tempFile); Object o = params.get(fis.getFieldName()); if (o == null) { params.put(fis.getFieldName(), new FileEx[] { fileEx }); } else if (o instanceof FileEx[]) { FileEx[] ss = (FileEx[]) o; FileEx[] nss = new FileEx[ss.length + 1]; System.arraycopy(ss, 0, nss, 0, ss.length); nss[ss.length] = fileEx; params.put(fis.getFieldName(), nss); } Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true); fileEx.fileName = fis.getName(); fileEx.contentType = fis.getContentType(); } } } catch (FileUploadException e) { if (action instanceof FileUploadExceptionAware) { ((FileUploadExceptionAware) action).setFileUploadException(e); } } catch (IOException e) { if (throwe) { throw e; } } } else { params = request.getParameterMap(); } if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) { for (SetterInfo si : setters) { si.setter.set(action, si.member, params, si.paramName); } } Object[] as = new Object[args.size()]; for (int i = 0; i < as.length; i++) { SetterInfo si = args.get(i); as[i] = si.setter.set(action, null, params, si.paramName); } return as; }
From source file:com.serli.chell.framework.upload.FileUploadStatus.java
private void addFormFieldParameter(FileItemStream fis, String fieldName, String encoding) { List<String> parameters = fieldFormParameters.get(fieldName); if (parameters == null) { parameters = new ArrayList<String>(); fieldFormParameters.put(fieldName, parameters); }/*from ww w .j a v a 2 s . c om*/ try { String value = WebUtils.readInputAsString(fis.openStream(), encoding); parameters.add(value); } catch (IOException ex) { throw new ChellException(ex); } }