use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project traccar by traccar.
the class PiligrimProtocolDecoder method sendResponse.
private void sendResponse(Channel channel, String message) {
if (channel != null) {
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.setContent(ChannelBuffers.copiedBuffer(ByteOrder.BIG_ENDIAN, message, StandardCharsets.US_ASCII));
channel.write(response);
}
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project traccar by traccar.
the class BaseHttpProtocolDecoder method sendResponse.
public void sendResponse(Channel channel, HttpResponseStatus status) {
if (channel != null) {
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
channel.write(response);
}
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project feeyo-hlsserver by variflight.
the class HlsLiveHandler method execute.
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpRequest request = (DefaultHttpRequest) e.getMessage();
String uri = request.getUri();
String path = uri.split("[?]")[0].trim();
String[] pathArray = path.split("/");
String alias = pathArray[2];
String requestFile = pathArray[3];
// 校验 alias & requestFile
if (alias == null || requestFile == null) {
HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
// 根据 alias 获取 live
HlsLiveStream liveStream = HlsLiveStreamMagr.INSTANCE().getHlsLiveStreamByAlias(alias);
if (liveStream == null) {
HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
// live.m3u8
if (requestFile.equals(LIVE_M3U8)) {
HlsClientSession clientSession = null;
// 提取 sid
QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
List<String> sessionId = decoder.getParameters().get("sid");
if (sessionId != null && !sessionId.isEmpty()) {
clientSession = liveStream.getClientSessionsById(sessionId.get(0));
}
LOGGER.info("request m3u8 file, uri={}, clientSession={}", uri, clientSession);
// 重定向, 解决标识问题
if (clientSession == null) {
clientSession = liveStream.newClientSession();
StringBuffer url = new StringBuffer(50);
url.append(path).append("?sid=").append(clientSession.getId());
LOGGER.info("response redirect, url={}", url.toString());
HttpResponse response = HttpUtil.redirectFound(url.toString());
e.getChannel().write(response);
return;
}
M3U8 m3u8 = clientSession.getM3u8File(requestFile);
DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
byte[] content = m3u8.getBuf();
long fileMTime = m3u8.getTime();
response.headers().add(HttpHeaders.Names.SERVER, Versions.SERVER_VERSION);
response.headers().add(HttpHeaders.Names.DATE, HttpUtil.getDateString(fileMTime));
response.headers().add(HttpHeaders.Names.CONTENT_TYPE, HttpUtil.getMimeType(requestFile));
response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, content.length);
//
response.headers().add(HttpHeaders.Names.CACHE_CONTROL, "private, max-age=5");
response.setContent(ChannelBuffers.copiedBuffer(content));
e.getChannel().write(response);
// 1...N.ts
} else {
LOGGER.info("request ts file, uri={} ", uri);
int tsIndex = Integer.valueOf(requestFile.substring(0, requestFile.indexOf(".ts"))).intValue();
//
String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HttpUtil.HTTP_DATE_FORMAT, Locale.US);
Date mdate = dateFormatter.parse(ifModifiedSince);
int mdateSec = (int) (mdate.getTime() / 1000L);
TsSegment tsSegment = liveStream.fetchTsSegment(tsIndex);
int fileMTimeSec = tsSegment != null ? (int) (tsSegment.getCtime() / 1000L) : 0;
if (mdateSec == fileMTimeSec) {
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
response.headers().add(HttpHeaders.Names.CACHE_CONTROL, "max-age=1");
HttpUtil.sendNotModified(ctx, response);
return;
}
}
TsSegment tsSegment = liveStream.fetchTsSegment(tsIndex);
if (tsSegment == null) {
HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
byte[] content = tsSegment.getData();
long fileMTime = tsSegment.getCtime();
response.headers().add(HttpHeaders.Names.SERVER, Versions.SERVER_VERSION);
response.headers().add(HttpHeaders.Names.DATE, HttpUtil.getDateString(fileMTime));
response.headers().add(HttpHeaders.Names.CONTENT_TYPE, HttpUtil.getMimeType(requestFile));
response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, content.length);
response.headers().add(HttpHeaders.Names.LAST_MODIFIED, HttpUtil.getDateString(fileMTime));
// 相对当前的过期时间,以分钟为单位
response.headers().add(HttpHeaders.Names.EXPIRES, HttpUtil.getDateString(fileMTime + LIVE_CACHE_TIME));
response.headers().add(HttpHeaders.Names.CACHE_CONTROL, "max-age=" + (LIVE_CACHE_TIME / 1000));
response.setContent(ChannelBuffers.copiedBuffer(content));
e.getChannel().write(response);
}
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project tez by apache.
the class TestShuffleHandler method testKeepAlive.
@Test(timeout = 10000)
public void testKeepAlive() throws Exception {
final ArrayList<Throwable> failures = new ArrayList<Throwable>(1);
Configuration conf = new Configuration();
conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
conf.setBoolean(ShuffleHandler.SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED, true);
// try setting to -ve keep alive timeout.
conf.setInt(ShuffleHandler.SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT, -100);
final LastSocketAddress lastSocketAddress = new LastSocketAddress();
ShuffleHandler shuffleHandler = new ShuffleHandler() {
@Override
protected Shuffle getShuffle(final Configuration conf) {
// replace the shuffle handler with one stubbed for testing
return new Shuffle(conf) {
@Override
protected MapOutputInfo getMapOutputInfo(String dagId, String mapId, String jobId, String user) throws IOException {
return null;
}
@Override
protected void verifyRequest(String appid, ChannelHandlerContext ctx, HttpRequest request, HttpResponse response, URL requestUri) throws IOException {
}
@Override
protected void populateHeaders(List<String> mapIds, String jobId, String dagId, String user, Range reduceRange, HttpResponse response, boolean keepAliveParam, Map<String, MapOutputInfo> infoMap) throws IOException {
// Send some dummy data (populate content length details)
ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1);
DataOutputBuffer dob = new DataOutputBuffer();
header.write(dob);
dob = new DataOutputBuffer();
for (int i = 0; i < 100000; ++i) {
header.write(dob);
}
long contentLength = dob.getLength();
// disable connectinKeepAliveEnabled if keepAliveParam is available
if (keepAliveParam) {
connectionKeepAliveEnabled = false;
}
super.setResponseHeaders(response, keepAliveParam, contentLength);
}
@Override
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch, String user, String mapId, Range reduceRange, MapOutputInfo info) throws IOException {
lastSocketAddress.setAddress(ch.getRemoteAddress());
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
// send a shuffle header and a lot of data down the channel
// to trigger a broken pipe
ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1);
DataOutputBuffer dob = new DataOutputBuffer();
header.write(dob);
ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
dob = new DataOutputBuffer();
for (int i = 0; i < 100000; ++i) {
header.write(dob);
}
return ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
}
@Override
protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
if (failures.size() == 0) {
failures.add(new Error());
ctx.getChannel().close();
}
}
@Override
protected void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) {
if (failures.size() == 0) {
failures.add(new Error());
ctx.getChannel().close();
}
}
};
}
};
shuffleHandler.init(conf);
shuffleHandler.start();
String shuffleBaseURL = "http://127.0.0.1:" + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY);
URL url = new URL(shuffleBaseURL + "/mapOutput?job=job_12345_1&dag=1&reduce=1&" + "map=attempt_12345_1_m_1_0");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
conn.connect();
DataInputStream input = new DataInputStream(conn.getInputStream());
Assert.assertEquals(HttpHeaders.Values.KEEP_ALIVE, conn.getHeaderField(HttpHeaders.Names.CONNECTION));
Assert.assertEquals("timeout=1", conn.getHeaderField(HttpHeaders.Values.KEEP_ALIVE));
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
ShuffleHeader header = new ShuffleHeader();
header.readFields(input);
byte[] buffer = new byte[1024];
while (input.read(buffer) != -1) {
}
SocketAddress firstAddress = lastSocketAddress.getSocketAddres();
input.close();
// For keepAlive via URL
url = new URL(shuffleBaseURL + "/mapOutput?job=job_12345_1&dag=1&reduce=1&" + "map=attempt_12345_1_m_1_0&keepAlive=true");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
conn.connect();
input = new DataInputStream(conn.getInputStream());
Assert.assertEquals(HttpHeaders.Values.KEEP_ALIVE, conn.getHeaderField(HttpHeaders.Names.CONNECTION));
Assert.assertEquals("timeout=1", conn.getHeaderField(HttpHeaders.Values.KEEP_ALIVE));
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
header = new ShuffleHeader();
header.readFields(input);
input.close();
SocketAddress secondAddress = lastSocketAddress.getSocketAddres();
Assert.assertNotNull("Initial shuffle address should not be null", firstAddress);
Assert.assertNotNull("Keep-Alive shuffle address should not be null", secondAddress);
Assert.assertEquals("Initial shuffle address and keep-alive shuffle " + "address should be the same", firstAddress, secondAddress);
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project socket.io-netty by ibdknox.
the class PollingIOClient method _write.
private void _write(String message) {
if (!this.open)
return;
HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
res.addHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Connection", "keep-alive");
res.setContent(ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));
setContentLength(res, res.getContent().readableBytes());
// Send the response and close the connection if necessary.
Channel chan = ctx.getChannel();
if (chan.isOpen()) {
ChannelFuture f = chan.write(res);
if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
this.connected = false;
}
Aggregations