List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:fi.helsinki.lib.simplerest.CommunitiesResource.java
@Post public Representation addCommunity(InputRepresentation rep) { Context c = null;/*from w w w . ja v a 2 s . c o m*/ 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:lucee.runtime.type.scope.FormImpl.java
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory(); Resource tempFile;/* w ww .java 2 s . c om*/ // Create a new file upload handler final String encoding = getEncoding(); FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list = new ArrayList<URLItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); is = IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false)); } else { tempFile = tempDir.getRealResource(getFileName()); fileItems.put(item.getFieldName().toLowerCase(), new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName())); String value = tempFile.toString(); IOUtil.copy(is, tempFile, true); list.add(new URLItem(item.getFieldName(), value, false)); } } raw = list.toArray(new URLItem[list.size()]); fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException = e; } }
From source file:br.com.ifpb.bdnc.projeto.geo.system.MultipartData.java
public boolean saveImage(String path, FileItemStream item, String nameToSave) { try {/*from w w w . j a va2 s . com*/ File f = new File(path + File.separator + folder); File parent = new File(f.getParent()); if (!parent.exists()) parent.mkdir(); if (!f.exists()) f.mkdir(); System.out.println(f.getAbsolutePath()); File savedFile = new File(f.getAbsoluteFile() + File.separator + nameToSave); FileOutputStream fos = new FileOutputStream(savedFile); InputStream is = item.openStream(); int x = 0; byte[] b = new byte[1024]; while ((x = is.read(b)) != -1) { fos.write(b, 0, x); } fos.flush(); fos.close(); return true; } catch (Exception ex) { ex.printStackTrace(); } return false; }
From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java
public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { ServletFileUpload upload = null;/*from ww w .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); } }
From source file:fi.helsinki.lib.simplerest.CollectionsResource.java
@Post public Representation addCollection(InputRepresentation rep) { Context c = null;/* w w w. ja v a 2 s .c o m*/ 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:edu.ucla.loni.pipeline.server.Upload.Uploaders.FileUploadServlet.java
/** * Determines XML Data type and stores file on server. * // w ww . ja va 2 s . c o m * @param item * @param respBuilder */ private void handleUploadedFile(FileItemStream item, ResponseBuilder respBuilder) { try { // process only file upload - discard other form item types if (item.isFormField()) { return; } // Validate DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document document = dBuilder.parse(item.openStream()); // Normalize document.getDocumentElement().normalize(); // Determine Root Tag String rootTag = document.getDocumentElement().getNodeName(); if (rootTag.equalsIgnoreCase("LONIConfigurationData")) { // Write to Blobstore DatastoreUtils.writeXMLFileToBlobStore(document, xmlConfigurationKey, respBuilder); // reset respBuilder (no need to have verbose messages because // upload was successful) respBuilder.resetRespMessage(); respBuilder.appendRespMessage("LONI Configuration Data was uploaded successfully."); } else if (rootTag.equalsIgnoreCase("LONIResourceData")) { // Write to Blobstore DatastoreUtils.writeXMLFileToBlobStore(document, xmlResourceKey, respBuilder); // reset respBuilder (no need to have verbose messages because // upload was successful) respBuilder.resetRespMessage(); respBuilder.appendRespMessage("LONI Resource Data was uploaded successfully."); } else { respBuilder.appendRespMessage("ERROR: Please upload either LONI Configuration or Resource Data."); } } catch (ParserConfigurationException e) { respBuilder.appendRespMessage("ERROR: File uploaded is not a valid XML file. Please try again."); } catch (SAXException e) { respBuilder.appendRespMessage("ERROR: File uploaded is not a valid XML file. Please try again."); } catch (IOException e) { respBuilder.appendRespMessage("ERROR: Could not parse file. Please upload a text-based XML file."); } }
From source file:etc.CloudStorage.java
/** * * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * * @return//from ww w. j a va 2s. com * @throws Exception * @param context */ public Mp3 uploadMp3(Context context) throws Exception { // make sure the context really is a multipart context... Mp3 mp3 = null; if (context.isMultipart()) { // This is the iterator we can use to iterate over the contents of the request. try { FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getName(); // Store audio file GcsFilename filename = new GcsFilename("musaemachine.com", name); // Store generated waveform image GcsFilename waveImageFile = new GcsFilename("musaemachine.com", removeExtension(name).concat(".png")); InputStream stream = item.openStream(); String contentType = item.getContentType(); System.out.println("--- " + contentType); GcsFileOptions options = new GcsFileOptions.Builder().acl("public-read").mimeType(contentType) .build(); byte[] audioBuffer = getByteFromStream(stream); GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, options); outputChannel.write(ByteBuffer.wrap(audioBuffer)); outputChannel.close(); // AudioWaveformCreator awc = new AudioWaveformCreator(); // byte[]waveform= awc.createWavForm(stream); // System.out.println("Buff Image---- "+waveform); // Saving waveform image // GcsOutputChannel waveFormOutputChannel = // gcsService.createOrReplace(waveImageFile, options); // waveFormOutputChannel.write(ByteBuffer.wrap(audioBuffer)); // waveFormOutputChannel.close(); // BodyContentHandler handler = new BodyContentHandler(); ParseContext pcontext = new ParseContext(); Metadata metadata = new Metadata(); mp3Parser.parse(stream, handler, metadata, pcontext); Double duration = Double.parseDouble(metadata.get("xmpDM:duration")); mp3 = new Mp3(name, duration); } } catch (Exception e) { e.printStackTrace(); } } return mp3; }
From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResourceTest.java
@Test public void uploadFileItem() throws Exception { final Map<String, Object> requestAttributes = new HashMap<>(); final VOSURI parentURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub")); final VOSURI expectedURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub/MYUPLOADFILE.txt")); final DataNode expectedDataNode = new DataNode(expectedURI); final String data = "MYUPLOADDATA"; final byte[] dataBytes = data.getBytes(); final InputStream inputStream = new ByteArrayInputStream(dataBytes); final List<NodeProperty> propertyList = new ArrayList<>(); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#length", "" + dataBytes.length)); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#MD5", new String(MessageDigest.getInstance("MD5").digest(dataBytes)))); expectedDataNode.setProperties(propertyList); requestAttributes.put("path", "my/file.txt"); expect(mockRequest.getEntity()).andReturn(new EmptyRepresentation()).once(); expect(mockServletContext.getContextPath()).andReturn("/teststorage").once(); replay(mockServletContext);//from w w w. java 2 s . com testSubject = new FileItemServerResource(null, mockVOSpaceClient, new UploadVerifier(), new FileValidator()) { @Override public Response getResponse() { return mockResponse; } @Override ServletContext getServletContext() { return mockServletContext; } @Override public Request getRequest() { return mockRequest; } /** * Returns the request attributes. * * @return The request attributes. * @see Request#getAttributes() */ @Override public Map<String, Object> getRequestAttributes() { return requestAttributes; } @Override VOSURI getCurrentItemURI() { return parentURI; } /** * Abstract away the Transfer stuff. It's cumbersome. * * @param outputStreamWrapper The OutputStream wrapper. * @param dataNode The node to upload. * @throws Exception To capture transfer and upload failures. */ @Override void upload(UploadOutputStreamWrapper outputStreamWrapper, DataNode dataNode) throws Exception { // Do nothing. } @Override <T> T executeSecurely(PrivilegedExceptionAction<T> runnable) throws IOException { try { return runnable.run(); } catch (Exception e) { throw new RuntimeException(e); } } }; final FileItemStream mockFileItemStream = createMock(FileItemStream.class); expect(mockVOSpaceClient.getNode("/parent/sub/MYUPLOADFILE.txt")) .andThrow(new NodeNotFoundException("No such node.")).once(); expect(mockVOSpaceClient.createNode(expectedDataNode, false)).andReturn(expectedDataNode).once(); expect(mockFileItemStream.getName()).andReturn("MYUPLOADFILE.txt").once(); expect(mockFileItemStream.openStream()).andReturn(inputStream).once(); expect(mockFileItemStream.getContentType()).andReturn("text/plain").once(); replay(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream); final VOSURI resultURI = testSubject.upload(mockFileItemStream); assertEquals("End URI is wrong.", expectedURI, resultURI); verify(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream, mockServletContext); }
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
private static DSOEditRequest extractDSOEditRequest(FileItemIterator fileItemIterator) throws FileUploadException, IOException, UnsupportedEncodingException { DSOEditRequest dsoEditRequest = null; Gson gson = new Gson(); FileItemStream headerJSONItemStream = fileItemIterator.next(); InputStream headerJSONStream = headerJSONItemStream.openStream(); InputStreamReader isr = null; BufferedReader br = null;//from w w w. j a va 2 s .co m try { isr = new InputStreamReader(headerJSONStream, "UTF-8"); br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n"); } String json = sb.toString(); log.info("DSOEditRequest:" + json); dsoEditRequest = gson.fromJson(json, DSOEditRequest.class); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); } return dsoEditRequest; }
From source file:es.eucm.mokap.backend.controller.insert.MokapInsertController.java
/** * Stores an uploaded file with a temporal file name. * // ww w .ja va 2 s. c o m * @param fis * Stream with the file * @return Name of the created temporal file * @throws IOException * if the file name is null, or if it has no zip extension */ private String storeUploadedTempFile(FileItemStream fis) throws IOException { String tempFileName; // Let's process the file String fileName = fis.getName(); if (fileName != null) { fileName = FilenameUtils.getName(fileName); } else { throw new IOException(ServerReturnMessages.INVALID_UPLOAD_FILENAMEISNULL); } if (!fileName.toLowerCase().endsWith(UploadZipStructure.ZIP_EXTENSION)) { throw new IOException(ServerReturnMessages.INVALID_UPLOAD_EXTENSION); } else { InputStream is = fis.openStream(); // Calculate fileName tempFileName = Utils.generateTempFileName(fileName); // Actually store the general temporal file st.storeFile(is, tempFileName); is.close(); } return tempFileName; }