/*
* Created by Andrey Cherkashin (acherkashin)
* http://acherkashin.me
*
* License
* Copyright (c) 2015 Andrey Cherkashin
* The project released under the MIT license: http://opensource.org/licenses/MIT
*/
package ragefist.core.network;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/**
*
* @author acherkashin
*/
public class PacketBufferHTTP extends PacketBuffer
{
private final ByteBuffer _buffer;
private static final Charset _charset = Charset.defaultCharset();
private String _method = null;
private String _url = null;
private String _version = null;
private byte[] _body = null;
private int _contentLength = 0;
private boolean _isBody = false;
private int _contentRead = 0;
public PacketBufferHTTP(Integer bufferSize) {
super(bufferSize);
_buffer = ByteBuffer.allocate(bufferSize);
}
public void put(byte[] bytes) {
_buffer.put(bytes);
if (_isBody) {
_contentRead += bytes.length;
}
}
public byte[] getBody() {
return _body;
}
public boolean readBody() {
_body = new byte[_contentLength];
_buffer.flip();
_buffer.get(_body, 0, _contentLength);
_buffer.compact();
return true;
}
public boolean isBodyReady() {
return _contentLength <= _contentRead;
}
public boolean readLine() throws IOException {
_buffer.flip();
byte[] in = _buffer.array();
int size = _buffer.remaining();
for(int i = 0; i < size; i++) {
if (in[i] == '\r' &&
in[i + 1] == '\n'
) {
byte[] bytes = new byte[i];
_buffer.get(bytes, 0, i);
_buffer.position(_buffer.position() + 2);
_buffer.compact();
ByteBuffer lineBuffer = ByteBuffer.wrap(bytes);
String data = _charset.decode(lineBuffer).toString();
this.processLine(data);
return true;
}
}
_buffer.flip();
return false;
}
public boolean isBody() {
return _isBody;
}
private void processLine(String line) throws IOException {
if ("".equals(line)) {
_isBody = true;
_contentRead = _buffer.position();
return;
}
String[] param = line.split(" ");
if (_method == null) {
if (param.length < 3) {
throw new IOException("HTTP Header is not defined");
}
_method = param[0];
_url = param[1];
_version = param[2];
return;
}
switch(param[0]) {
case "Content-Length:":
_contentLength = Integer.parseInt(param[1]);
break;
}
}
}