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;
}
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();
}
}
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;
}
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);
}
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;
}
Aggregations