Example usage for org.apache.commons.fileupload MultipartStream readBoundary

List of usage examples for org.apache.commons.fileupload MultipartStream readBoundary

Introduction

In this page you can find the example usage for org.apache.commons.fileupload MultipartStream readBoundary.

Prototype

public boolean readBoundary() throws MalformedStreamException 

Source Link

Document

Skips a boundary token, and checks whether more encapsulations are contained in the stream.

Usage

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.//  w ww  .ja  v  a 2s  .  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  w  w w  . j  av a2  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();
    }
}