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:project.cs.lisa.netinf.node.resolution.NameResolutionService.java
private InformationObject readIoAndFile(Identifier identifier, HttpResponse response) throws InvalidResponseException { Log.d(TAG, "readIoAndFile()"); if (response == null) { throw new InvalidResponseException("Response is null."); } else if (response.getEntity() == null) { throw new InvalidResponseException("Entity is null."); } else if (response.getEntity().getContentType() == null) { throw new InvalidResponseException("Content-Type is null."); } else if (!response.getEntity().getContentType().getValue().startsWith("multipart/form-data")) { throw new InvalidResponseException("Content-Type is " + response.getEntity().getContentType().getValue() + ", expected to start with \"multipart/form-data\""); }/*from ww w .j a va2 s .c om*/ try { // Create IO InformationObject io = mDatamodelFactory.createInformationObject(); io.setIdentifier(identifier); Log.d(TAG, "name: " + response.getHeaders("Content-Type")[0].getName()); Log.d(TAG, "value: " + response.getHeaders("Content-Type")[0].getValue()); String contentType = response.getHeaders("Content-Type")[0].getValue(); byte[] boundary = (contentType.substring(contentType.indexOf("boundary=") + 9)).getBytes(); Log.d(TAG, "boundary = " + Arrays.toString(boundary)); @SuppressWarnings("deprecation") MultipartStream multipartStream = new MultipartStream(response.getEntity().getContent(), boundary); multipartStream.skipPreamble(); // TODO Dependant on order used by NRS // Read JSON ByteArrayOutputStream jsonStream = new ByteArrayOutputStream(); multipartStream.readHeaders(); multipartStream.readBodyData(jsonStream); multipartStream.readBoundary(); JSONObject jsonObject = parseJson(jsonStream.toString()); jsonStream.close(); addContentType(io.getIdentifier(), jsonObject); addMetadata(io.getIdentifier(), jsonObject); addLocators(io, jsonObject); File file = new File( Environment.getExternalStorageDirectory() + "/DCIM/Shared/" + getHash(io.getIdentifier())); FileOutputStream fos = new FileOutputStream(file); multipartStream.readHeaders(); multipartStream.readBodyData(fos); fos.flush(); fos.close(); // Add file path locator Attribute locator = mDatamodelFactory.createAttribute(); locator.setAttributePurpose(DefinedAttributePurpose.LOCATOR_ATTRIBUTE.toString()); locator.setIdentification(SailDefinedAttributeIdentification.FILE_PATH.getURI()); locator.setValue(file.getAbsoluteFile()); io.addAttribute(locator); return io; } catch (IOException e) { throw new InvalidResponseException("Failed to read InformationObject from response", e); } }
From source file:project.cs.netinfservice.netinf.node.resolution.NameResolutionService.java
/** * Creates an Information Object and file from a previous HTTP request. * * @param identifier/*from ww w .ja va2s. com*/ * The identifier * @param response * HTTP response * @return * New Information Object created from the response. * <p>A side-effect is the new file created.</p> * @throws InvalidResponseException * Thrown if the response had an invalid information object. */ private InformationObject readIoAndFile(Identifier identifier, HttpResponse response) throws InvalidResponseException { // Sanity checks the response. if (response == null) { throw new InvalidResponseException("Response is null."); } else if (response.getEntity() == null) { throw new InvalidResponseException("Entity is null."); } else if (response.getEntity().getContentType() == null) { throw new InvalidResponseException("Content-Type is null."); } else if (!response.getEntity().getContentType().getValue().startsWith("multipart/form-data")) { throw new InvalidResponseException("Content-Type is " + response.getEntity().getContentType().getValue() + ", expected to start with \"multipart/form-data\""); } // Reads IO and File try { // Create IO InformationObject io = mDatamodelFactory.createInformationObject(); io.setIdentifier(identifier); // Extract Content-type from header String contentType = response.getHeaders("Content-Type")[0].getValue(); // Get boundary bytes byte[] boundary = (contentType.substring(contentType.indexOf("boundary=") + 9)).getBytes(); // Raises intent Intent intent = new Intent(NRS_TRANSMISSION); MainNetInfActivity.getActivity().sendBroadcast(intent); // Start multipart @SuppressWarnings("deprecation") MultipartStream multipartStream = new MultipartStream(response.getEntity().getContent(), boundary); // Skip multipart preamble multipartStream.skipPreamble(); // TODO Dependant on order used by NRS // Read JSON ByteArrayOutputStream jsonStream = new ByteArrayOutputStream(); // Move on multipart stream multipartStream.readHeaders(); multipartStream.readBodyData(jsonStream); multipartStream.readBoundary(); // Parse JSON Object JSONObject jsonObject = parseJson(jsonStream.toString()); // Close stream used to read JSON jsonStream.close(); // Add attributes to the new Information Object addContentType(io.getIdentifier(), jsonObject); addMetadata(io.getIdentifier(), jsonObject); addLocators(io, jsonObject); // Create the new file File file = new File( Environment.getExternalStorageDirectory() + "/DCIM/Shared/" + getHash(io.getIdentifier())); // Write file in disk FileOutputStream fos = new FileOutputStream(file); // move on Multipart multipartStream.readHeaders(); multipartStream.readBodyData(fos); // Close file stream fos.flush(); fos.close(); // Add file path locator Attribute locator = mDatamodelFactory.createAttribute(); locator.setAttributePurpose(DefinedAttributePurpose.LOCATOR_ATTRIBUTE.toString()); locator.setIdentification(SailDefinedAttributeIdentification.FILE_PATH.getURI()); locator.setValue(file.getAbsoluteFile()); // Add atributes io.addAttribute(locator); // Return new Information Object created return io; } catch (IOException e) { throw new InvalidResponseException("Failed to read InformationObject from response", e); } }
From source file:rocks.inspectit.ui.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 ww. j a v a2 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<>(); 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:uk.ac.cam.arb33.multipartformdecoder.Main.java
public static void main(String[] args) throws IOException { if (args.length == 0) { printUsage();/*from www .j a va 2 s . co m*/ return; } int outputFileIndex = 1; BufferedInputStream in = new BufferedInputStream(new FileInputStream(args[0])); byte[] boundary = getBoundary(in); MultipartStream multipartStream = new MultipartStream(in, boundary, 8192, null); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); Map<String, String> keyValuePairs = parseHeader(header); System.out.println(keyValuePairs.get("Content-Disposition")); if (keyValuePairs.containsKey("Content-Disposition") && keyValuePairs.get("Content-Disposition").contains("filename=\"")) { if (outputFileIndex < args.length) { System.out.println(" -> Saving data to " + args[outputFileIndex]); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(args[outputFileIndex])); multipartStream.readBodyData(out); outputFileIndex++; } else { System.out.println(" -> Cannot save file data: insufficent input files specified."); multipartStream.discardBodyData(); } } else { ByteArrayOutputStream out = (new ByteArrayOutputStream()); multipartStream.readBodyData(out); System.out.println(" -> " + new String(out.toByteArray())); } nextPart = multipartStream.readBoundary(); } }