List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:org.apache.jackrabbit.demo.mu.servlets.PackageUploadServlet.java
private void importQuestionPackage(FileItem fileItem) throws IOException, RepositoryException { InputStream inputStream = fileItem.getInputStream(); session.getWorkspace().importXML("/mu-root/question-packages", inputStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW); inputStream.close();//from w w w . java2 s . c o m }
From source file:org.apache.jackrabbit.server.util.HttpMultipartPost.java
/** * Returns an array of input streams for uploaded file parameters. * * @param name the name of the file parameter(s) * @return an array of input streams or <code>null</code> if no file params * with the given name exist.//from w w w . j av a2s . c o m * @throws IOException if an I/O error occurs */ InputStream[] getFileParameterValues(String name) throws IOException { checkInitialized(); InputStream[] values = null; if (fileParamNames.contains(name)) { List<FileItem> l = nameToItems.get(name); if (l != null && !l.isEmpty()) { List<InputStream> ins = new ArrayList<InputStream>(l.size()); for (FileItem item : l) { if (!item.isFormField()) { ins.add(item.getInputStream()); } } values = ins.toArray(new InputStream[ins.size()]); } } return values; }
From source file:org.apache.manifoldcf.ui.multipart.MultipartWrapper.java
/** Get a file parameter, as a binary input. *//*from w w w. j av a2 s . c o m*/ @Override public BinaryInput getBinaryStream(String name) throws ManifoldCFException { if (request != null) return null; ArrayList list = (ArrayList) variableMap.get(name); if (list == null) return null; Object x = list.get(0); if (x instanceof String) return null; FileItem item = (FileItem) x; if (item.isFormField()) return null; try { InputStream uploadedStream = item.getInputStream(); try { return new TempFileInput(uploadedStream); } finally { uploadedStream.close(); } } catch (IOException e) { throw new ManifoldCFException("Error creating file binary stream", e); } }
From source file:org.apache.myfaces.custom.fileupload.HtmlFileUploadRendererTest.java
public void testUploadedFileDefaultMemoryImplSerializable() throws Exception { String fieldName = "inputFile"; String contentType = "someType"; MockControl control = MockControl.createControl(FileItem.class); FileItem item = (FileItem) control.getMock(); item.getName();//from w ww . j a v a 2s . co m control.setReturnValue(fieldName, 1); item.getContentType(); control.setReturnValue(contentType, 1); item.getSize(); control.setReturnValue(0, 1); item.getInputStream(); control.setReturnValue(new InputStream() { public int read() throws IOException { return -1; } }, 1); item.delete(); control.setVoidCallable(1); control.replay(); UploadedFileDefaultMemoryImpl original = new UploadedFileDefaultMemoryImpl(item); ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(original); oos.close(); byte[] serializedArray = out.toByteArray(); InputStream in = new ByteArrayInputStream(serializedArray); ObjectInputStream ois = new ObjectInputStream(in); UploadedFileDefaultMemoryImpl copy = (UploadedFileDefaultMemoryImpl) ois.readObject(); assertEquals(original.getName(), copy.getName()); assertEquals(original.getContentType(), copy.getContentType()); assertEquals(copy.getSize(), 0); copy.getStorageStrategy().deleteFileContents(); }
From source file:org.apache.myfaces.custom.fileupload.UploadedFileDefaultMemoryImpl.java
public UploadedFileDefaultMemoryImpl(final FileItem fileItem) throws IOException { super(fileItem.getName(), fileItem.getContentType()); int sizeInBytes = (int) fileItem.getSize(); bytes = new byte[sizeInBytes]; this.fileItem = fileItem; fileItem.getInputStream().read(bytes); this.storageStrategy = new DefaultMemoryStorageStrategy(); }
From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // check whether dumping the repository is requested if (req.getRequestURI().endsWith("/repository.zip")) { this.dumpRepository(req.getParameterValues("bundle"), resp); resp.sendRedirect(req.getRequestURI()); return;/*from www . j a v a 2 s . co m*/ } if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) { resp.sendRedirect(req.getRequestURI()); return; } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(256000); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); // Parse the request boolean noRedirect = false; String bundleLocation = null; InputStream bundleStream = null; try { List /* FileItem */ items = upload.parseRequest(req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { bundleStream = item.getInputStream(); bundleLocation = item.getName(); } else { noRedirect |= "_noredir_".equals(item.getFieldName()); } } if (bundleStream != null && bundleLocation != null) { try { this.repository.addResource(bundleStream); } catch (IOException ioe) { resp.sendError(500, "Cannot register file " + bundleLocation + ". Reason: " + ioe.getMessage()); } } } catch (FileUploadException fue) { throw new ServletException(fue.getMessage(), fue); } finally { if (bundleStream != null) { try { bundleStream.close(); } catch (IOException ignore) { } } } // only redirect if not instructed otherwise if (noRedirect) { resp.setContentType("text/plain"); if (bundleLocation != null) { resp.getWriter().print("Bundle " + bundleLocation + " uploaded"); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().print("No Bundle uploaded"); } } else { resp.sendRedirect(req.getRequestURI()); } }
From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java
private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException { InstallationResult result = null;/*from w w w . j av a 2s . c o m*/ try { DiskFileItemFactory factory = new DiskFileItemFactory(); // try to hold even largish bundles in memory to potentially improve performance factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); if (items.size() != 1) { logAndWriteError( "Found " + items.size() + " items to process, but only updating 1 bundle is supported", resp); return; } FileItem item = items.get(0); JarInputStream jar = null; InputStream rawInput = null; try { jar = new JarInputStream(item.getInputStream()); Manifest manifest = jar.getManifest(); if (manifest == null) { logAndWriteError("Uploaded jar file does not contain a manifest", resp); return; } final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (symbolicName == null) { logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp); return; } final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION); // the JarInputStream is used only for validation, we need a fresh input stream for updating rawInput = item.getInputStream(); Bundle found = getBundle(symbolicName); try { installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar"); result = new InstallationResult(true, null); resp.setStatus(200); result.render(resp.getWriter()); return; } catch (BundleException e) { logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp); return; } } finally { IOUtils.closeQuietly(jar); IOUtils.closeQuietly(rawInput); } } catch (FileUploadException e) { logAndWriteError("Failed parsing uploaded bundle", e, resp); return; } }
From source file:org.apache.tapestry5.upload.internal.services.UploadedFileItemTest.java
@Test public void streamIsFileItemStream() throws Exception { FileItem item = newMock(FileItem.class); InputStream stream = new NullInputStream(3); UploadedFileItem uploadedFile = new UploadedFileItem(item); expect(item.getInputStream()).andReturn(stream); replay();/*from w ww . ja va 2 s .c o m*/ assertSame(uploadedFile.getStream(), stream); verify(); }
From source file:org.artificer.ui.server.servlets.ArtifactUploadServlet.java
/** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// www . j av a 2 s.c om @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { // Extract the relevant content from the POST'd form if (ServletFileUpload.isMultipartContent(req)) { Map<String, String> responseMap; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request String artifactType = null; String fileName = null; InputStream artifactContent = null; try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("artifactType")) { artifactType = item.getString(); } } else { fileName = item.getName(); if (fileName != null) fileName = FilenameUtils.getName(fileName); artifactContent = item.getInputStream(); } } // Now that the content has been extracted, process it (upload the artifact to the s-ramp repo). responseMap = uploadArtifact(artifactType, fileName, artifactContent); } catch (ArtificerAtomException e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); responseMap.put("exception-message", e.getMessage()); responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); } catch (Throwable e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); responseMap.put("exception-message", e.getMessage()); responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); } finally { IOUtils.closeQuietly(artifactContent); } writeToResponse(responseMap, response); } else { response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, Messages.i18n.format("UploadServlet.ContentTypeNotSupported")); } }
From source file:org.artificer.ui.server.servlets.OntologyUploadServlet.java
/** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w .j ava 2 s .co m @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { // Extract the relevant content from the POST'd form if (ServletFileUpload.isMultipartContent(req)) { Map<String, String> responseMap; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request String fileName = null; InputStream ontologyContent = null; try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { // No form fields to process. } else { fileName = item.getName(); if (fileName != null) fileName = FilenameUtils.getName(fileName); ontologyContent = item.getInputStream(); } } // Now that the content has been extracted, process it (upload the ontology to the s-ramp repo). responseMap = uploadOntology(ontologyContent); } catch (ArtificerAtomException e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); responseMap.put("exception-message", e.getMessage()); responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); } catch (Throwable e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); responseMap.put("exception-message", e.getMessage()); responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); } finally { IOUtils.closeQuietly(ontologyContent); } writeToResponse(responseMap, response); } else { response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, Messages.i18n.format("UploadServlet.ContentTypeNotSupported")); } }