Search in sources :

Example 11 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project cdap by caskdata.

the class AppFabricClient method getHistory.

public List<RunRecord> getHistory(Id.Program programId, ProgramRunStatus status) throws Exception {
    String namespaceId = programId.getNamespaceId();
    String appId = programId.getApplicationId();
    String programName = programId.getId();
    String categoryName = programId.getType().getCategoryName();
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/%s/%s/runs?status=" + status.name(), getNamespacePath(namespaceId), appId, categoryName, programName);
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
    programLifecycleHttpHandler.programHistory(request, responder, namespaceId, appId, categoryName, programName, status.name(), null, null, 100);
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Getting workflow history failed");
    return responder.decodeResponseContent(RUN_RECORDS_TYPE);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest)

Example 12 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project traccar by traccar.

the class Mta6ProtocolDecoder method decode.

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;
    ChannelBuffer buf = request.getContent();
    buf.skipBytes("id=".length());
    int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '&');
    String uniqueId = buf.toString(buf.readerIndex(), index - buf.readerIndex(), StandardCharsets.US_ASCII);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, uniqueId);
    if (deviceSession == null) {
        return null;
    }
    buf.skipBytes(uniqueId.length());
    buf.skipBytes("&bin=".length());
    short packetId = buf.readUnsignedByte();
    // dataOffset
    short offset = buf.readUnsignedByte();
    short packetCount = buf.readUnsignedByte();
    // reserved
    buf.readUnsignedByte();
    // timezone
    buf.readUnsignedByte();
    buf.skipBytes(offset - 5);
    if (channel != null) {
        sendContinue(channel);
        sendResponse(channel, packetId, packetCount);
    }
    if (packetId == 0x31 || packetId == 0x32 || packetId == 0x36) {
        if (simple) {
            return parseFormatA1(deviceSession, buf);
        } else {
            return parseFormatA(deviceSession, buf);
        }
    }
    return null;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DeviceSession(org.traccar.DeviceSession) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 13 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest 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;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) QueryStringDecoder(org.jboss.netty.handler.codec.http.QueryStringDecoder) DeviceSession(org.traccar.DeviceSession) Position(org.traccar.model.Position) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Parser(org.traccar.helper.Parser)

Example 14 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project traccar by traccar.

the class DmtHttpProtocolDecoder method decode.

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;
    JsonObject root = Json.createReader(new StringReader(request.getContent().toString(StandardCharsets.US_ASCII))).readObject();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, root.getString("IMEI"));
    if (deviceSession == null) {
        sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
        return null;
    }
    List<Position> positions = new LinkedList<>();
    JsonArray records = root.getJsonArray("Records");
    for (int i = 0; i < records.size(); i++) {
        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());
        JsonObject record = records.getJsonObject(i);
        position.set(Position.KEY_INDEX, record.getInt("SeqNo"));
        position.set(Position.KEY_EVENT, record.getInt("Reason"));
        position.setDeviceTime(dateFormat.parse(record.getString("DateUTC")));
        JsonArray fields = record.getJsonArray("Fields");
        for (int j = 0; j < fields.size(); j++) {
            JsonObject field = fields.getJsonObject(j);
            switch(field.getInt("FType")) {
                case 0:
                    position.setFixTime(dateFormat.parse(field.getString("GpsUTC")));
                    position.setLatitude(field.getJsonNumber("Lat").doubleValue());
                    position.setLongitude(field.getJsonNumber("Long").doubleValue());
                    position.setAltitude(field.getInt("Alt"));
                    position.setSpeed(UnitsConverter.knotsFromCps(field.getInt("Spd")));
                    position.setCourse(field.getInt("Head"));
                    position.setAccuracy(field.getInt("PosAcc"));
                    position.setValid(field.getInt("GpsStat") > 0);
                    break;
                case 2:
                    int input = field.getInt("DIn");
                    int output = field.getInt("DOut");
                    position.set(Position.KEY_IGNITION, BitUtil.check(input, 0));
                    position.set(Position.KEY_INPUT, input);
                    position.set(Position.KEY_OUTPUT, output);
                    position.set(Position.KEY_STATUS, field.getInt("DevStat"));
                    break;
                case 6:
                    JsonObject adc = field.getJsonObject("AnalogueData");
                    if (adc.containsKey("1")) {
                        position.set(Position.KEY_BATTERY, adc.getInt("1") * 0.001);
                    }
                    if (adc.containsKey("2")) {
                        position.set(Position.KEY_POWER, adc.getInt("2") * 0.01);
                    }
                    if (adc.containsKey("3")) {
                        position.set(Position.KEY_DEVICE_TEMP, adc.getInt("3") * 0.01);
                    }
                    if (adc.containsKey("4")) {
                        position.set(Position.KEY_RSSI, adc.getInt("4"));
                    }
                    if (adc.containsKey("5")) {
                        position.set("solarPower", adc.getInt("5") * 0.001);
                    }
                    break;
                default:
                    break;
            }
        }
        positions.add(position);
    }
    sendResponse(channel, HttpResponseStatus.OK);
    return positions;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) JsonArray(javax.json.JsonArray) DeviceSession(org.traccar.DeviceSession) Position(org.traccar.model.Position) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) SimpleDateFormat(java.text.SimpleDateFormat) LinkedList(java.util.LinkedList)

Example 15 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest 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);
    }
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) HlsClientSession(com.feeyo.hls.HlsClientSession) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) M3U8(com.feeyo.hls.m3u8.M3U8) TsSegment(com.feeyo.hls.ts.TsSegment) Date(java.util.Date) QueryStringDecoder(org.jboss.netty.handler.codec.http.QueryStringDecoder) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HlsLiveStream(com.feeyo.hls.HlsLiveStream) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)136 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)69 Channel (org.jboss.netty.channel.Channel)47 Test (org.junit.Test)47 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)46 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)43 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)31 ChannelFuture (org.jboss.netty.channel.ChannelFuture)26 List (java.util.List)19 ArrayList (java.util.ArrayList)17 Map (java.util.Map)17 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)17 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)17 InetSocketAddress (java.net.InetSocketAddress)14 ChannelHandlerContext (org.jboss.netty.channel.ChannelHandlerContext)13 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)13 SimpleHttpResponseHandler (com.linkedin.databus.core.test.netty.SimpleHttpResponseHandler)12 SimpleTestHttpClient (com.linkedin.databus.core.test.netty.SimpleTestHttpClient)12 Configuration (org.apache.hadoop.conf.Configuration)12 YarnConfiguration (org.apache.hadoop.yarn.conf.YarnConfiguration)12