Search in sources :

Example 1 with ByteBufferList

use of com.koushikdutta.async.ByteBufferList in project AndroidAsync by koush.

the class HeaderReader method readHeader.

public List<Header> readHeader(ByteBufferList bb, int length) throws IOException {
    byte[] bytes = new byte[length];
    bb.get(bytes);
    inflater.setInput(bytes);
    ByteBufferList source = new ByteBufferList().order(ByteOrder.BIG_ENDIAN);
    while (!inflater.needsInput()) {
        ByteBuffer b = ByteBufferList.obtain(8192);
        try {
            int read = inflater.inflate(b.array());
            b.limit(read);
            source.add(b);
        } catch (DataFormatException e) {
            throw new IOException(e);
        }
    }
    int numberOfPairs = source.getInt();
    List<Header> entries = new ArrayList<Header>(numberOfPairs);
    for (int i = 0; i < numberOfPairs; i++) {
        ByteString name = readByteString(source).toAsciiLowercase();
        ByteString values = readByteString(source);
        if (name.size() == 0)
            throw new IOException("name.size == 0");
        entries.add(new Header(name, values));
    }
    return entries;
}
Also used : DataFormatException(java.util.zip.DataFormatException) ByteBufferList(com.koushikdutta.async.ByteBufferList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 2 with ByteBufferList

use of com.koushikdutta.async.ByteBufferList in project AndroidAsync by koush.

the class AsyncHttpServerResponseImpl method end.

@Override
public void end() {
    if (ended)
        return;
    ended = true;
    if (headWritten && mSink == null) {
        // end will be called again after finished.
        return;
    }
    if (!headWritten) {
        // end was called, and no head or body was yet written,
        // so strip the transfer encoding as that is superfluous.
        mRawHeaders.remove("Transfer-Encoding");
    }
    if (mSink instanceof ChunkedOutputFilter) {
        ((ChunkedOutputFilter) mSink).setMaxBuffer(Integer.MAX_VALUE);
        mSink.write(new ByteBufferList());
        onEnd();
    } else if (!headWritten) {
        if (!mRequest.getMethod().equalsIgnoreCase(AsyncHttpHead.METHOD))
            send("text/html", "");
        else {
            writeHead();
            onEnd();
        }
    } else {
        onEnd();
    }
}
Also used : ByteBufferList(com.koushikdutta.async.ByteBufferList) ChunkedOutputFilter(com.koushikdutta.async.http.filter.ChunkedOutputFilter)

Example 3 with ByteBufferList

use of com.koushikdutta.async.ByteBufferList in project AndroidAsync by koush.

the class NetworkEventReporterWrapper method interpretResponseEmitter.

public DataEmitter interpretResponseEmitter(final String requestId, @Nullable DataEmitter body, final boolean b64Encode) {
    final NetworkPeerManager peerManager = getPeerManagerIfEnabled();
    if (peerManager == null)
        return null;
    final WritableByteChannel channel;
    try {
        if (b64Encode) {
            final Base64OutputStream b64out = new Base64OutputStream(peerManager.getResponseBodyFileManager().openResponseBodyFile(requestId, false), Base64.DEFAULT);
            channel = Channels.newChannel(b64out);
        } else {
            channel = ((FileOutputStream) peerManager.getResponseBodyFileManager().openResponseBodyFile(requestId, false)).getChannel();
        }
    } catch (IOException e) {
        return null;
    }
    FilteredDataEmitter ret = new FilteredDataEmitter() {

        ByteBufferList pending = new ByteBufferList();

        @Override
        protected void report(Exception e) {
            super.report(e);
            StreamUtility.closeQuietly(channel);
            if (e == null)
                responseReadFinished(requestId);
            else
                responseReadFailed(requestId, e.toString());
        }

        @Override
        public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
            int amount = bb.remaining();
            ByteBuffer[] original = bb.getAllArray();
            ByteBuffer[] copy = new ByteBuffer[original.length];
            for (int i = 0; i < original.length; i++) {
                copy[i] = original[i].duplicate();
            }
            try {
                for (ByteBuffer c : copy) {
                    channel.write(c);
                }
            } catch (IOException ignored) {
                StreamUtility.closeQuietly(channel);
            }
            pending.addAll(original);
            dataReceived(requestId, amount, amount);
            super.onDataAvailable(emitter, pending);
        }
    };
    ret.setDataEmitter(body);
    return ret;
}
Also used : FilteredDataEmitter(com.koushikdutta.async.FilteredDataEmitter) ByteBufferList(com.koushikdutta.async.ByteBufferList) NetworkPeerManager(com.facebook.stetho.inspector.network.NetworkPeerManager) DataEmitter(com.koushikdutta.async.DataEmitter) FilteredDataEmitter(com.koushikdutta.async.FilteredDataEmitter) WritableByteChannel(java.nio.channels.WritableByteChannel) IOException(java.io.IOException) Base64OutputStream(android.util.Base64OutputStream) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException)

Example 4 with ByteBufferList

use of com.koushikdutta.async.ByteBufferList in project FileTransfer by CPPAlien.

the class WebService method startServer.

private void startServer() {
    server.get("/images/.*", this::sendResources);
    server.get("/scripts/.*", this::sendResources);
    server.get("/css/.*", this::sendResources);
    // index page
    server.get("/", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        try {
            response.send(getIndexContent());
        } catch (IOException e) {
            e.printStackTrace();
            response.code(500).end();
        }
    });
    // query upload list
    server.get("/files", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        JSONArray array = new JSONArray();
        File dir = Constants.DIR;
        if (dir.exists() && dir.isDirectory()) {
            String[] fileNames = dir.list();
            if (fileNames != null) {
                for (String fileName : fileNames) {
                    File file = new File(dir, fileName);
                    if (file.exists() && file.isFile()) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("name", fileName);
                            long fileLen = file.length();
                            DecimalFormat df = new DecimalFormat("0.00");
                            if (fileLen > 1024 * 1024) {
                                jsonObject.put("size", df.format(fileLen * 1f / 1024 / 1024) + "MB");
                            } else if (fileLen > 1024) {
                                jsonObject.put("size", df.format(fileLen * 1f / 1024) + "KB");
                            } else {
                                jsonObject.put("size", fileLen + "B");
                            }
                            array.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        response.send(array.toString());
    });
    // delete
    server.post("/files/.*", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        final UrlEncodedFormBody body = (UrlEncodedFormBody) request.getBody();
        if ("delete".equalsIgnoreCase(body.get().getString("_method"))) {
            String path = request.getPath().replace("/files/", "");
            try {
                path = URLDecoder.decode(path, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File file = new File(Constants.DIR, path);
            if (file.exists() && file.isFile() && file.delete()) {
                RxBus.get().post(Constants.RxBusEventType.LOAD_BOOK_LIST, 0);
            }
        }
        response.end();
    });
    // download
    server.get("/files/.*", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        String path = request.getPath().replace("/files/", "");
        try {
            path = URLDecoder.decode(path, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file = new File(Constants.DIR, path);
        if (file.exists() && file.isFile()) {
            try {
                response.getHeaders().add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.sendFile(file);
            return;
        }
        response.code(404).send("Not found!");
    });
    // upload
    server.post("/files", (AsyncHttpServerRequest request, AsyncHttpServerResponse response) -> {
        final MultipartFormDataBody body = (MultipartFormDataBody) request.getBody();
        body.setMultipartCallback((Part part) -> {
            if (part.isFile()) {
                body.setDataCallback((DataEmitter emitter, ByteBufferList bb) -> {
                    fileUploadHolder.write(bb.getAllByteArray());
                    bb.recycle();
                });
            } else {
                if (body.getDataCallback() == null) {
                    body.setDataCallback((DataEmitter emitter, ByteBufferList bb) -> {
                        try {
                            String fileName = URLDecoder.decode(new String(bb.getAllByteArray()), "UTF-8");
                            fileUploadHolder.setFileName(fileName);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        bb.recycle();
                    });
                }
            }
        });
        request.setEndCallback((Exception e) -> {
            fileUploadHolder.reset();
            response.end();
            RxBus.get().post(Constants.RxBusEventType.LOAD_BOOK_LIST, 0);
        });
    });
    server.get("/progress/.*", (final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) -> {
        JSONObject res = new JSONObject();
        String path = request.getPath().replace("/progress/", "");
        if (path.equals(fileUploadHolder.fileName)) {
            try {
                res.put("fileName", fileUploadHolder.fileName);
                res.put("size", fileUploadHolder.totalSize);
                res.put("progress", fileUploadHolder.fileOutPutStream == null ? 1 : 0.1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        response.send(res);
    });
    server.listen(mAsyncServer, Constants.HTTP_PORT);
}
Also used : ByteBufferList(com.koushikdutta.async.ByteBufferList) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) DecimalFormat(java.text.DecimalFormat) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) JSONException(org.json.JSONException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(org.json.JSONObject) Part(com.koushikdutta.async.http.body.Part) DataEmitter(com.koushikdutta.async.DataEmitter) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody) File(java.io.File) MultipartFormDataBody(com.koushikdutta.async.http.body.MultipartFormDataBody)

Example 5 with ByteBufferList

use of com.koushikdutta.async.ByteBufferList in project AndroidAsync by koush.

the class DnsResponse method parse.

public static DnsResponse parse(ByteBufferList bb) {
    ByteBuffer b = bb.getAll();
    bb.add(b.duplicate());
    // naive parsing...
    bb.order(ByteOrder.BIG_ENDIAN);
    // id
    bb.getShort();
    // flags
    bb.getShort();
    // number questions
    int questions = bb.getShort();
    // number answer rr
    int answers = bb.getShort();
    // number authority rr
    int authorities = bb.getShort();
    // number additional rr
    int additionals = bb.getShort();
    for (int i = 0; i < questions; i++) {
        parseName(bb, b);
        // type
        bb.getShort();
        // class
        bb.getShort();
    }
    DnsResponse response = new DnsResponse();
    for (int i = 0; i < answers; i++) {
        String name = parseName(bb, b);
        // type
        int type = bb.getShort();
        // class
        int clazz = bb.getShort();
        // ttl
        int ttl = bb.getInt();
        // length of address
        int length = bb.getShort();
        try {
            if (type == 1) {
                // data
                byte[] data = new byte[length];
                bb.get(data);
                response.addresses.add(InetAddress.getByAddress(data));
            } else if (type == 0x000c) {
                response.names.add(parseName(bb, b));
            } else if (type == 16) {
                ByteBufferList txt = new ByteBufferList();
                bb.get(txt, length);
                response.parseTxt(txt);
            } else {
                bb.get(new byte[length]);
            }
        } catch (Exception e) {
        // e.printStackTrace();
        }
    }
    // authorities
    for (int i = 0; i < authorities; i++) {
        String name = parseName(bb, b);
        // type
        int type = bb.getShort();
        // class
        int clazz = bb.getShort();
        // ttl
        int ttl = bb.getInt();
        // length of address
        int length = bb.getShort();
        try {
            bb.get(new byte[length]);
        } catch (Exception e) {
        // e.printStackTrace();
        }
    }
    // additionals
    for (int i = 0; i < additionals; i++) {
        String name = parseName(bb, b);
        // type
        int type = bb.getShort();
        // class
        int clazz = bb.getShort();
        // ttl
        int ttl = bb.getInt();
        // length of address
        int length = bb.getShort();
        try {
            if (type == 16) {
                ByteBufferList txt = new ByteBufferList();
                bb.get(txt, length);
                response.parseTxt(txt);
            } else {
                bb.get(new byte[length]);
            }
        } catch (Exception e) {
        // e.printStackTrace();
        }
    }
    return response;
}
Also used : ByteBufferList(com.koushikdutta.async.ByteBufferList) ByteBuffer(java.nio.ByteBuffer)

Aggregations

ByteBufferList (com.koushikdutta.async.ByteBufferList)42 DataEmitter (com.koushikdutta.async.DataEmitter)15 DataCallback (com.koushikdutta.async.callback.DataCallback)14 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)11 FilteredDataEmitter (com.koushikdutta.async.FilteredDataEmitter)10 ByteBuffer (java.nio.ByteBuffer)10 IOException (java.io.IOException)7 Semaphore (java.util.concurrent.Semaphore)5 PushParser (com.koushikdutta.async.PushParser)4 ExecutionException (java.util.concurrent.ExecutionException)4 JsonObject (com.google.gson.JsonObject)3 SimpleFuture (com.koushikdutta.async.future.SimpleFuture)3 AsyncHttpGet (com.koushikdutta.async.http.AsyncHttpGet)3 AsyncHttpResponse (com.koushikdutta.async.http.AsyncHttpResponse)3 HttpConnectCallback (com.koushikdutta.async.http.callback.HttpConnectCallback)3 AsyncHttpServer (com.koushikdutta.async.http.server.AsyncHttpServer)3 AsyncHttpServerRequest (com.koushikdutta.async.http.server.AsyncHttpServerRequest)3 AsyncHttpServerResponse (com.koushikdutta.async.http.server.AsyncHttpServerResponse)3 BEncodedDictionary (org.cyanogenmod.pushsms.bencode.BEncodedDictionary)3 Test (org.junit.Test)3