use of org.jboss.netty.handler.codec.http.QueryStringDecoder in project traccar by traccar.
the class PathAwayProtocolDecoder method decode.
@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
HttpRequest request = (HttpRequest) msg;
QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
if (deviceSession == null) {
return null;
}
Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
if (!parser.matches()) {
return null;
}
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));
position.setValid(true);
position.setLatitude(parser.nextDouble(0));
position.setLongitude(parser.nextDouble(0));
position.setAltitude(parser.nextDouble(0));
position.setSpeed(parser.nextDouble(0));
position.setCourse(parser.nextDouble(0));
if (channel != null) {
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
return position;
}
use of org.jboss.netty.handler.codec.http.QueryStringDecoder 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.QueryStringDecoder in project cdap by caskdata.
the class MetricsHandler method query.
@POST
@Path("/query")
public void query(HttpRequest request, HttpResponder responder, @QueryParam("metric") List<String> metrics, @QueryParam("groupBy") List<String> groupBy, @QueryParam("tag") List<String> tags) throws Exception {
try {
if (new QueryStringDecoder(request.getUri()).getParameters().isEmpty()) {
if (HttpHeaders.getContentLength(request) > 0) {
Map<String, MetricsQueryHelper.QueryRequestFormat> queries = GSON.fromJson(request.getContent().toString(Charsets.UTF_8), new TypeToken<Map<String, MetricsQueryHelper.QueryRequestFormat>>() {
}.getType());
responder.sendJson(HttpResponseStatus.OK, metricsQueryHelper.executeBatchQueries(queries));
return;
}
responder.sendJson(HttpResponseStatus.BAD_REQUEST, "Batch request with empty content");
}
responder.sendJson(HttpResponseStatus.OK, metricsQueryHelper.executeTagQuery(tags, metrics, groupBy, new QueryStringDecoder(request.getUri()).getParameters()));
} catch (IllegalArgumentException e) {
LOG.warn("Invalid request", e);
responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage());
} catch (Exception e) {
LOG.error("Exception querying metrics ", e);
responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while querying for metrics");
}
}
use of org.jboss.netty.handler.codec.http.QueryStringDecoder in project cdap by caskdata.
the class PreviewHttpHandler method query.
@POST
@Path("previews/{preview-id}/metrics/query")
public void query(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("preview-id") String previewId, @QueryParam("metric") List<String> metrics, @QueryParam("groupBy") List<String> groupBy, @QueryParam("tag") List<String> tags) throws Exception {
MetricsQueryHelper helper = getMetricsQueryHelper(namespaceId, previewId);
try {
if (new QueryStringDecoder(request.getUri()).getParameters().isEmpty()) {
if (HttpHeaders.getContentLength(request) > 0) {
Map<String, MetricsQueryHelper.QueryRequestFormat> queries = GSON.fromJson(request.getContent().toString(Charsets.UTF_8), new TypeToken<Map<String, MetricsQueryHelper.QueryRequestFormat>>() {
}.getType());
overrideQueries(queries, namespaceId, previewId);
responder.sendJson(HttpResponseStatus.OK, helper.executeBatchQueries(queries));
return;
}
responder.sendJson(HttpResponseStatus.BAD_REQUEST, "Batch request with empty content");
}
tags = overrideTags(tags, namespaceId, previewId);
responder.sendJson(HttpResponseStatus.OK, helper.executeTagQuery(tags, metrics, groupBy, new QueryStringDecoder(request.getUri()).getParameters()));
} catch (IllegalArgumentException e) {
LOG.warn("Invalid request", e);
responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage());
} catch (Exception e) {
LOG.error("Exception querying metrics ", e);
responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while querying for metrics");
}
}
use of org.jboss.netty.handler.codec.http.QueryStringDecoder in project traccar by traccar.
the class OpenGtsProtocolDecoder method decode.
@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
HttpRequest request = (HttpRequest) msg;
QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
Map<String, List<String>> params = decoder.getParameters();
Position position = new Position();
position.setProtocol(getProtocolName());
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String value = entry.getValue().get(0);
switch(entry.getKey()) {
case "id":
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, value);
if (deviceSession == null) {
sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
return null;
}
position.setDeviceId(deviceSession.getDeviceId());
break;
case "gprmc":
Parser parser = new Parser(PATTERN, value);
if (!parser.matches()) {
sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
return null;
}
DateBuilder dateBuilder = new DateBuilder().setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
position.setValid(parser.next().equals("A"));
position.setLatitude(parser.nextCoordinate());
position.setLongitude(parser.nextCoordinate());
position.setSpeed(parser.nextDouble(0));
position.setCourse(parser.nextDouble(0));
dateBuilder.setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
position.setTime(dateBuilder.getDate());
break;
case "alt":
position.setAltitude(Double.parseDouble(value));
break;
case "batt":
position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value));
break;
default:
break;
}
}
if (position.getDeviceId() != 0) {
sendResponse(channel, HttpResponseStatus.OK);
return position;
} else {
sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
return null;
}
}
Aggregations