List of usage examples for org.apache.commons.fileupload MultipartStream readBodyData
public int readBodyData(OutputStream output) throws MalformedStreamException, IOException
Reads body-data
from the current encapsulation
and writes its contents into the output Stream
.
From source file:lucee.runtime.net.http.MultiPartResponseUtils.java
private static Struct getPartData(MultipartStream stream) throws IOException, PageException { Struct headers = extractHeaders(stream.readHeaders()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); stream.readBodyData(baos); Struct fileStruct = new StructImpl(); fileStruct.set(KeyConstants._content, baos.toByteArray()); fileStruct.set(KeyConstants._headers, headers); IOUtil.closeEL(baos);//w ww . j av a 2 s . co m return fileStruct; }
From source file:ch.sportchef.business.event.boundary.EventImageResource.java
@PUT @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadImage(@Context HttpServletRequest request) throws IOException, ServletException { final String contentType = request.getContentType(); final byte[] boundary = contentType.substring(contentType.indexOf("boundary=") + 9).getBytes(); try (final BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream(), 8192)) { final MultipartStream multipartStream = new MultipartStream(inputStream, boundary, 8192, null); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { multipartStream.readHeaders(); // don't remove, strips headers off try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8192)) { multipartStream.readBodyData(outputStream); nextPart = multipartStream.readBoundary(); final byte[] image = outputStream.toByteArray(); eventImageService.uploadImage(eventId, image); return Response.ok().build(); }/*from w w w . j a v a 2s . co m*/ } } return Response.status(BAD_REQUEST).build(); }
From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java
@SuppressWarnings("deprecation") private HashMap<String, Part> split(Message message, String boundary) throws IOException, EndOfStreamException, MalformedStreamException { HashMap<String, Part> parts = new HashMap<String, Part>(); MultipartStream multipartStream = new MultipartStream(MessageUtil.getContentAsStream(message), boundary.getBytes(Constants.UTF_8_CHARSET)); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { Header header = new Header(multipartStream.readHeaders()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipartStream.readBodyData(baos); // see http://www.iana.org/assignments/transfer-encodings/transfer-encodings.xml String cte = header.getFirstValue("Content-Transfer-Encoding"); if (cte != null && !cte.equals("binary") && !cte.equals("8bit") && !cte.equals("7bit")) throw new RuntimeException("Content-Transfer-Encoding '" + cte + "' not implemented."); Part part = new Part(header, baos.toByteArray()); String id = part.getContentID(); if (id != null) { parts.put(id, part);/* w w w. j ava2 s. c o m*/ } nextPart = multipartStream.readBoundary(); } return parts; }
From source file:io.selendroid.testapp.webdrivertestserver.handler.UploadFileHandler.java
public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control) throws Exception { response.header("Content-Type", "text/html; charset=" + Charsets.UTF_8.name()); String contentTypeHeader = request.header("Content-Type"); Map<String, String> contentTypeHeaderFields = extractFields(contentTypeHeader); ByteArrayInputStream input = new ByteArrayInputStream(request.bodyAsBytes()); MultipartStream multipartStream = new MultipartStream(input, contentTypeHeaderFields.get("boundary").getBytes()); boolean hasNext = multipartStream.skipPreamble(); while (hasNext) { Map<String, String> allHeaders = splitHeaders(multipartStream.readHeaders()); String inputFieldName = extractFields(allHeaders.get("Content-Disposition")).get("name"); if (UPLOAD_NAMES.contains(inputFieldName)) { ByteArrayOutputStream data = new ByteArrayOutputStream(); multipartStream.readBodyData(data); response.content(data.toByteArray()); } else {/* w w w . j a va2s . c o m*/ multipartStream.discardBodyData(); } hasNext = multipartStream.readBoundary(); } response.content("<script>window.top.window.onUploadDone();</script>").end(); }
From source file:com.intuit.tank.http.multipart.MultiPartRequest.java
@Override public void setBody(String bodyEncoded) { String s = new String(Base64.decodeBase64(bodyEncoded)); String boundary = StringUtils.substringBefore(s, "\r\n").substring(2); super.setBody(s); try {// w ww . j ava 2 s.c o m // s = getBody(); @SuppressWarnings("deprecation") MultipartStream multipartStream = new MultipartStream( new ByteArrayInputStream(Base64.decodeBase64(bodyEncoded)), boundary.getBytes()); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); // process headers // create some output stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); multipartStream.readBodyData(bos); PartHolder p = new PartHolder(bos.toByteArray(), header); parameters.add(p); nextPart = multipartStream.readBoundary(); } } catch (MultipartStream.MalformedStreamException e) { LOG.error(e.toString(), e); // the stream failed to follow required syntax } catch (IOException e) { LOG.error(e.toString(), e); // a read or write error occurred } }
From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Retrieves the wanted data described in the {@link StorageDescriptor} from the desired * {@link CmrRepositoryDefinition}. This method will try to invoke as less as possible HTTP * requests for all descriptors./*from w w w .j av a 2 s. c o m*/ * <p> * The method will execute the HTTP requests sequentially. * <p> * It is not guaranteed that amount of returned objects in the list is same as the amount of * provided descriptors. If some of the descriptors are pointing to the wrong files or files * positions, it can happen that this influences the rest of the descriptor that point to the * same file. Thus, a special care needs to be taken that the data in descriptors is correct. * * @param <E> * Type of the objects are wanted. * @param cmrRepositoryDefinition * {@link CmrRepositoryDefinition}. * @param storageData * {@link StorageData} that points to the wanted storage. * @param descriptors * Descriptors. * @return List of objects in the supplied generic type. Note that if the data described in the * descriptor is not of a supplied generic type, there will be a casting exception * thrown. * @throws SerializationException * If {@link SerializationException} occurs. * @throws IOException * If {@link IOException} occurs. */ @SuppressWarnings("unchecked") public <E extends DefaultData> List<E> getDataViaHttp(CmrRepositoryDefinition cmrRepositoryDefinition, IStorageData storageData, List<IStorageDescriptor> descriptors) throws IOException, SerializationException { Map<Integer, List<IStorageDescriptor>> separateFilesGroup = createFilesGroup(descriptors); List<E> receivedData = new ArrayList<E>(); String serverUri = getServerUri(cmrRepositoryDefinition); HttpClient httpClient = new DefaultHttpClient(); for (Map.Entry<Integer, List<IStorageDescriptor>> entry : separateFilesGroup.entrySet()) { HttpGet httpGet = new HttpGet( serverUri + storageManager.getHttpFileLocation(storageData, entry.getKey())); StringBuilder rangeHeader = new StringBuilder("bytes="); RangeDescriptor rangeDescriptor = null; for (IStorageDescriptor descriptor : entry.getValue()) { if (null == rangeDescriptor) { rangeDescriptor = new RangeDescriptor(descriptor); } else { if (rangeDescriptor.getEnd() + 1 == descriptor.getPosition()) { rangeDescriptor.setEnd(descriptor.getPosition() + descriptor.getSize() - 1); } else { rangeHeader.append(rangeDescriptor.toString()); rangeHeader.append(','); rangeDescriptor = new RangeDescriptor(descriptor); } } } rangeHeader.append(rangeDescriptor); httpGet.addHeader("Range", rangeHeader.toString()); ISerializer serializer = null; try { serializer = serializerQueue.take(); } catch (InterruptedException e) { Thread.interrupted(); } InputStream inputStream = null; Input input = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (MultipartEntityUtil.isMultipart(entity)) { inputStream = entity.getContent(); @SuppressWarnings("deprecation") // all non-deprecated constructors have default modifier MultipartStream multipartStream = new MultipartStream(inputStream, MultipartEntityUtil.getBoundary(entity).getBytes()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { multipartStream.readHeaders(); multipartStream.readBodyData(byteArrayOutputStream); input = new Input(byteArrayOutputStream.toByteArray()); while (KryoUtil.hasMoreBytes(input)) { Object object = serializer.deserialize(input); E element = (E) object; receivedData.add(element); } nextPart = multipartStream.readBoundary(); } } else { // when kryo changes the visibility of optional() method, we can really stream input = new Input(EntityUtils.toByteArray(entity)); while (KryoUtil.hasMoreBytes(input)) { Object object = serializer.deserialize(input); E element = (E) object; receivedData.add(element); } } } finally { if (null != inputStream) { inputStream.close(); } if (null != input) { input.close(); } serializerQueue.add(serializer); } } return receivedData; }
From source file:com.navjagpal.fileshare.WebServer.java
@SuppressWarnings("deprecation") public void processUpload(String folderId, HttpRequest request, DefaultHttpServerConnection serverConnection) throws IOException, HttpException { /* Find the boundary and the content length. */ String contentType = request.getFirstHeader("Content-Type").getValue(); String boundary = contentType.substring(contentType.indexOf("boundary=") + "boundary=".length()); BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest( request.getRequestLine());/* w ww.j ava 2s . c om*/ serverConnection.receiveRequestEntity(enclosingRequest); InputStream input = enclosingRequest.getEntity().getContent(); MultipartStream multipartStream = new MultipartStream(input, boundary.getBytes()); String headers = multipartStream.readHeaders(); /* Get the filename. */ StringTokenizer tokens = new StringTokenizer(headers, ";", false); String filename = null; while (tokens.hasMoreTokens() && filename == null) { String token = tokens.nextToken().trim(); if (token.startsWith("filename=")) { filename = URLDecoder.decode(token.substring("filename=\"".length(), token.lastIndexOf("\"")), "utf8"); } } File uploadDirectory = new File("/sdcard/fileshare/uploads"); if (!uploadDirectory.exists()) { uploadDirectory.mkdirs(); } /* Write the file and add it to the shared folder. */ File uploadFile = new File(uploadDirectory, filename); FileOutputStream output = new FileOutputStream(uploadFile); multipartStream.readBodyData(output); output.close(); Uri fileUri = Uri.withAppendedPath(FileProvider.CONTENT_URI, uploadFile.getAbsolutePath()); Uri folderUri = Uri.withAppendedPath(FileSharingProvider.Folders.CONTENT_URI, folderId); FileSharingProvider.addFileToFolder(mContext.getContentResolver(), fileUri, folderUri); }
From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java
protected void prepareMultiPartFile(DragDropMimeHandlerRequest mimeRequest, File f, HttpServletResponse response) throws IOException { logger.logTrace("process multipart"); mimeRequest.setFiles(new ArrayList<DragDropMimeFile>()); PrintWriter out = response.getWriter(); FileInputStream fin = new FileInputStream(f); int partcount = 0; try {// w ww.j a v a2s .c o m MultipartStream multipartStream = new MultipartStream(fin, mimeRequest.getMimeBoundary().getBytes(), 1000, null); boolean nextPart = multipartStream.skipPreamble(); int filecount = 0; while (nextPart) { partcount++; String header = multipartStream.readHeaders(); logger.logTrace("PART HEADER:" + header); if (header.startsWith("Content-Disposition: form-data")) { filecount++; //params Map<String, String> params = utils.getFilePartParams(header); //also save request params to .inf file for (String key : mimeRequest.getRequestParams().keySet()) { params.put(key, mimeRequest.getRequestParams().get(key)); } params.put("user", mimeRequest.getCtx().getUser()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(params.toString().getBytes()); File f2 = new File(cfg.getFolder(), f.getName() + "." + filecount + ".inf"); FileOutputStream output = new FileOutputStream(f2); output.write(bout.toByteArray()); output.close(); //file File f3 = new File(cfg.getFolder(), f.getName() + "." + filecount + ".dat"); FileOutputStream output3 = new FileOutputStream(f3); multipartStream.readBodyData(output3); output3.close(); String hash = utils.getHash(f3); logger.logTrace("hash:" + hash + ":" + params.get("md5") + ", equals:" + hash.trim().equalsIgnoreCase(params.get("md5").trim())); if (cfg.checkHash()) { if (!hash.trim().equalsIgnoreCase(params.get("md5").trim())) { logger.logError("Invalid hash:" + params.get("md5"), null); throw new IllegalArgumentException("Invalid hash:" + params.get("md5")); } } if (cfg.getMaxFileSizePerFile() > 0 && f3.length() > cfg.getMaxFileSizePerFile()) { logger.logError("File too big hash:" + f3.length(), null); } else { DragDropMimeFile tf = new DragDropMimeFile(); tf.setFile(f3); tf.setHash(hash); tf.setPrepareParams(params); tf.setFileName(params.get("filename")); mimeRequest.getFiles().add(tf); } } else { System.err.println("skipping part:" + header); multipartStream.readBodyData(new ByteArrayOutputStream()); } nextPart = multipartStream.readBoundary(); } // f.delete();//delete multipart upload file since already splitted in info and data } catch (MultipartStream.MalformedStreamException e) { logger.logError(e.getMessage(), e); e.printStackTrace(); throw new IllegalArgumentException(e); } catch (IOException e) { logger.logError(e.getMessage(), e); e.printStackTrace(); throw new IllegalArgumentException(e); } if (cfg.getHandler() != null) { DragDropMimeHandlerResponse mimeResponse = cfg.getHandler().prepare(mimeRequest); if (mimeResponse.getResponseContent() != null) { logger.logTrace("setting html response content..."); response.setContentType(mimeResponse.getResponseContentType().getMimeType()); out.println(mimeResponse.getResponseContent()); } else { //TODO check redirects } //handler.handleFile(f2,params,reqparams,reqheaders); } }
From source file:com.rhfung.P2PDictionary.DataConnection.java
private void HandleReadPost(String contentLocation, String contentType, String accepts, ListInt senders, byte[] payload) { if (contentLocation.equals(ADDENTRY_NS_API) || contentLocation.equals(ADDENTRY_NS_BYTES_API) || contentLocation.equals(ADDENTRY_NS_MIME_API)) { boolean sendMime = contentLocation.equals(ADDENTRY_NS_MIME_API); String boundary = getBoundaryFromContentType(contentType); if (boundary == null) { WriteDebug("Cannot identify boundary from POST"); return; }//from w ww.jav a2 s . c o m String filename = "content"; try { MultipartStream multipartStream = new MultipartStream(new ByteArrayInputStream(payload), boundary.getBytes()); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); Hashtable<String, String> hdr = ReadHeaders( new InputStreamReader(new ByteArrayInputStream(header.getBytes()))); String val = hdr.get("Content-Disposition"); if (val != null) { final String FILENAME = "filename=\""; int filenameIdx = val.indexOf(FILENAME); filename = val.substring(filenameIdx + FILENAME.length(), val.indexOf("\"", filenameIdx + FILENAME.length())); } // process headers // create some output stream ByteArrayOutputStream output = new ByteArrayOutputStream(); multipartStream.readBodyData(output); if (sendMime) { String valType = hdr.get("Content-Type"); controller.put(filename, new MIMEByteObject(valType, output.toByteArray())); } else { controller.put(filename, output.toByteArray()); } nextPart = multipartStream.readBoundary(); } // only reply back with ONE file uploaded MemoryStream bufferedOutput = new MemoryStream(); String key = controller.getFullKey(filename); dataLock.readLock().lock(); try { DataEntry entry = data.get(key); WriteResponseInfo(bufferedOutput.createStreamWriter(), ADDENTRY_NS_API, entry); synchronized (sendBuffer) { sendBuffer.add(bufferedOutput); } } finally { dataLock.readLock().unlock(); } } catch (Exception e) { MemoryStream bufferedOutput = new MemoryStream(); WriteErrorNotFound(bufferedOutput.createStreamWriter(), "GET", contentLocation, 500); synchronized (sendBuffer) { sendBuffer.add(bufferedOutput); } } } else { MemoryStream bufferedOutput = new MemoryStream(); WriteErrorNotFound(bufferedOutput.createStreamWriter(), "GET", contentLocation, 501); synchronized (sendBuffer) { sendBuffer.add(bufferedOutput); } } }
From source file:com.oneis.appserver.FileUploads.java
/** * Handle the incoming stream, processing files. *///www. ja v a 2s .c om public void performUploads(HttpServletRequest request) throws IOException, UserReportableFileUploadException { instructionsRequired = false; // Need a parser for parameters ParameterParser paramParser = new ParameterParser(); paramParser.setLowerCaseNames(true); // Thread ID is used for temporary filenames long threadId = Thread.currentThread().getId(); int fileId = 0; InputStream requestBody = request.getInputStream(); MultipartStream multipart = new MultipartStream(requestBody, boundary); multipart.setHeaderEncoding("UTF-8"); boolean nextPart = multipart.skipPreamble(); while (nextPart) { String headerPart = multipart.readHeaders(); // Parse headers, splitting out the bits we're interested in String name = null; String filename = null; Map<String, String> itemHeaders = HeaderParser.parse(headerPart, true /* keys to lower case */); String mimeType = itemHeaders.get("content-type"); String disposition = itemHeaders.get("content-disposition"); if (disposition != null) { Map disp = paramParser.parse(disposition, PARAMPARSER_SEPERATORS); name = (String) disp.get("name"); filename = (String) disp.get("filename"); } // Set a default MIME type if none is given (Safari may omit it) if (mimeType == null) { mimeType = "application/octet-stream"; } // Remove the path prefix from IE (before the length check) if (filename != null) { int slash1 = filename.lastIndexOf('/'); int slash2 = filename.lastIndexOf('\\'); int slash = (slash1 > slash2) ? slash1 : slash2; if (slash != -1) { filename = filename.substring(slash + 1); } } boolean isFile = (filename != null && filename.length() > 0); if (isFile) { // File - did the app server give instructions about it? Upload upload = files.get(name); if (upload == null) { // Looks like a file, but the app server didn't say it should be. Give up. throw new UserReportableFileUploadException( "A file was uploaded, but it was not expected by the application. Field name: '" + name + "'"); } String dir = upload.getSaveDirectory(); if (dir == null) { // Ooops. throw new IOException("app server didn't specify dir"); } // Generate a temporary filename File outFile = null; do { outFile = new File(String.format("%1$s/u%2$d.%3$d", dir, threadId, fileId++)); } while (!outFile.createNewFile()); OutputStream outStream = new FileOutputStream(outFile); // Decorate with a digest? MessageDigest digest = null; if (upload.getDigestName() != null) { try { digest = MessageDigest.getInstance(upload.getDigestName()); } catch (java.security.NoSuchAlgorithmException e) { digest = null; } if (digest != null) { outStream = new DigestOutputStream(outStream, digest); } } // Decorate with a decompressor? String filterName = upload.getFilterName(); if (filterName != null && filterName.equals("inflate")) { outStream = new InflaterOutputStream(outStream); } multipart.readBodyData(outStream); outStream.close(); String digestAsString = null; if (digest != null) { String.format("%1$s_digest", name); digestAsString = StringUtils.bytesToHex(digest.digest()); } upload.setUploadDetails(outFile.getPath(), digestAsString, mimeType, filename, outFile.length()); } else { // Normal field - just absorb a few k max of it, turn it into a field ByteArrayOutputStream value = new ByteArrayOutputStream(); // TODO: Limit request size as a whole, not on a per-parameter basis. multipart.readBodyData(new LimitedFilterOutputStream(value, MAX_TEXT_PARAMETER_LENGTH)); params.put(name, value.toString("UTF-8")); } nextPart = multipart.readBoundary(); } }