All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ithit.webdav.integration.android.AndroidInputStream Maven / Gradle / Ivy

The newest version!
package com.ithit.webdav.integration.android;

import com.ithit.webdav.server.util.StringUtil;
import fi.iki.elonen.NanoHTTPD;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class AndroidInputStream extends InputStream {

    private NanoHTTPD.IHTTPSession session;
    private FileInputStream dataStream;

    AndroidInputStream(NanoHTTPD.IHTTPSession session) {
        this.session = session;
    }

    public int read() throws IOException {
        return session.getInputStream().read();
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if ("POST".equalsIgnoreCase(session.getMethod().toString()) || "PUT".equalsIgnoreCase(session.getMethod().toString())) {
            if (dataStream == null) {
                Map files = new HashMap();
                try {
                    session.parseBody(files);
                    for (String file : files.values()) {
                        if (!StringUtil.isNullOrEmpty(file)) {
                            dataStream = new FileInputStream(file);
                            break;
                        }
                    }
                    if (dataStream == null) {
                        return -1;
                    }
                } catch (NanoHTTPD.ResponseException e) {
                    System.err.println("Failed parsing body. " + e.getLocalizedMessage());
                    throw new IOException(e);
                }
            }
            return dataStream.read(b, off, len);
        } else {
            String cl = session.getHeaders().get("content-length");
            if (cl == null) {
                return -1;
            }
            if (b[len - 1] == '\u0000' && b[0] != '\u0000') {
                return -1;
            }
            Integer contentLength = Integer.parseInt(cl);
            if (contentLength == 0) {
                return -1;
            }
            byte[] buffer = new byte[contentLength];
            int position = session.getInputStream().read(buffer, 0, contentLength);
            System.arraycopy(buffer, 0, b, 0, buffer.length);
            return position;
        }
    }

    @Override
    public void close() throws IOException {
        super.close();
        if (dataStream != null) {
            try {
                dataStream.close();
            } catch (Exception ignored) {
            }
            dataStream = null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy