Search in sources :

Example 56 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project traccar by tananaev.

the class OsmAndProtocolDecoder method decode.

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
    FullHttpRequest request = (FullHttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    Map<String, List<String>> params = decoder.parameters();
    if (params.isEmpty()) {
        decoder = new QueryStringDecoder(request.content().toString(StandardCharsets.US_ASCII), false);
        params = decoder.parameters();
    }
    Position position = new Position(getProtocolName());
    position.setValid(true);
    Network network = new Network();
    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        for (String value : entry.getValue()) {
            switch(entry.getKey()) {
                case "id":
                case "deviceid":
                    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, value);
                    if (deviceSession == null) {
                        sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
                        return null;
                    }
                    position.setDeviceId(deviceSession.getDeviceId());
                    break;
                case "valid":
                    position.setValid(Boolean.parseBoolean(value) || "1".equals(value));
                    break;
                case "timestamp":
                    try {
                        long timestamp = Long.parseLong(value);
                        if (timestamp < Integer.MAX_VALUE) {
                            timestamp *= 1000;
                        }
                        position.setTime(new Date(timestamp));
                    } catch (NumberFormatException error) {
                        if (value.contains("T")) {
                            position.setTime(DateUtil.parseDate(value));
                        } else {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            position.setTime(dateFormat.parse(value));
                        }
                    }
                    break;
                case "lat":
                    position.setLatitude(Double.parseDouble(value));
                    break;
                case "lon":
                    position.setLongitude(Double.parseDouble(value));
                    break;
                case "location":
                    String[] location = value.split(",");
                    position.setLatitude(Double.parseDouble(location[0]));
                    position.setLongitude(Double.parseDouble(location[1]));
                    break;
                case "cell":
                    String[] cell = value.split(",");
                    if (cell.length > 4) {
                        network.addCellTower(CellTower.from(Integer.parseInt(cell[0]), Integer.parseInt(cell[1]), Integer.parseInt(cell[2]), Integer.parseInt(cell[3]), Integer.parseInt(cell[4])));
                    } else {
                        network.addCellTower(CellTower.from(Integer.parseInt(cell[0]), Integer.parseInt(cell[1]), Integer.parseInt(cell[2]), Integer.parseInt(cell[3])));
                    }
                    break;
                case "wifi":
                    String[] wifi = value.split(",");
                    network.addWifiAccessPoint(WifiAccessPoint.from(wifi[0].replace('-', ':'), Integer.parseInt(wifi[1])));
                    break;
                case "speed":
                    position.setSpeed(convertSpeed(Double.parseDouble(value), "kn"));
                    break;
                case "bearing":
                case "heading":
                    position.setCourse(Double.parseDouble(value));
                    break;
                case "altitude":
                    position.setAltitude(Double.parseDouble(value));
                    break;
                case "accuracy":
                    position.setAccuracy(Double.parseDouble(value));
                    break;
                case "hdop":
                    position.set(Position.KEY_HDOP, Double.parseDouble(value));
                    break;
                case "batt":
                    position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value));
                    break;
                case "driverUniqueId":
                    position.set(Position.KEY_DRIVER_UNIQUE_ID, value);
                    break;
                default:
                    try {
                        position.set(entry.getKey(), Double.parseDouble(value));
                    } catch (NumberFormatException e) {
                        switch(value) {
                            case "true":
                                position.set(entry.getKey(), true);
                                break;
                            case "false":
                                position.set(entry.getKey(), false);
                                break;
                            default:
                                position.set(entry.getKey(), value);
                                break;
                        }
                    }
                    break;
            }
        }
    }
    if (position.getFixTime() == null) {
        position.setTime(new Date());
    }
    if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) {
        position.setNetwork(network);
    }
    if (position.getLatitude() == 0 && position.getLongitude() == 0) {
        getLastLocation(position, position.getDeviceTime());
    }
    if (position.getDeviceId() != 0) {
        String response = null;
        CommandsManager commandsManager = Context.getCommandsManager();
        if (commandsManager != null) {
            for (Command command : commandsManager.readQueuedCommands(position.getDeviceId(), 1)) {
                response = command.getString(Command.KEY_DATA);
            }
        }
        if (response != null) {
            sendResponse(channel, HttpResponseStatus.OK, Unpooled.copiedBuffer(response, StandardCharsets.UTF_8));
        } else {
            sendResponse(channel, HttpResponseStatus.OK);
        }
        return position;
    } else {
        sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
        return null;
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DeviceSession(org.traccar.DeviceSession) Position(org.traccar.model.Position) Date(java.util.Date) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Command(org.traccar.model.Command) Network(org.traccar.model.Network) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) List(java.util.List) CommandsManager(org.traccar.database.CommandsManager) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat)

Example 57 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project traccar by tananaev.

the class PathAwayProtocolDecoder method decode.

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
    FullHttpRequest request = (FullHttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, decoder.parameters().get("UserName").get(0));
    if (deviceSession == null) {
        return null;
    }
    Parser parser = new Parser(PATTERN, decoder.parameters().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) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        channel.writeAndFlush(new NetworkMessage(response, remoteAddress)).addListener(ChannelFutureListener.CLOSE);
    }
    return position;
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DeviceSession(org.traccar.DeviceSession) Position(org.traccar.model.Position) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NetworkMessage(org.traccar.NetworkMessage) Parser(org.traccar.helper.Parser)

Example 58 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project traccar by tananaev.

the class PiligrimProtocolDecoder method decode.

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
    FullHttpRequest request = (FullHttpRequest) msg;
    String uri = request.uri();
    if (uri.startsWith("/config")) {
        sendResponse(channel, "CONFIG: OK");
    } else if (uri.startsWith("/addlog")) {
        sendResponse(channel, "ADDLOG: OK");
    } else if (uri.startsWith("/inform")) {
        sendResponse(channel, "INFORM: OK");
    } else if (uri.startsWith("/bingps")) {
        sendResponse(channel, "BINGPS: OK");
        QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, decoder.parameters().get("imei").get(0));
        if (deviceSession == null) {
            return null;
        }
        List<Position> positions = new LinkedList<>();
        ByteBuf buf = request.content();
        while (buf.readableBytes() > 2) {
            // header
            buf.readUnsignedByte();
            int type = buf.readUnsignedByte();
            // length
            buf.readUnsignedByte();
            if (type == MSG_GPS || type == MSG_GPS_SENSORS) {
                Position position = new Position(getProtocolName());
                position.setDeviceId(deviceSession.getDeviceId());
                DateBuilder dateBuilder = new DateBuilder().setDay(buf.readUnsignedByte()).setMonth(buf.getByte(buf.readerIndex()) & 0x0f).setYear(2010 + (buf.readUnsignedByte() >> 4)).setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte());
                position.setTime(dateBuilder.getDate());
                double latitude = buf.readUnsignedByte();
                latitude += buf.readUnsignedByte() / 60.0;
                latitude += buf.readUnsignedByte() / 6000.0;
                latitude += buf.readUnsignedByte() / 600000.0;
                double longitude = buf.readUnsignedByte();
                longitude += buf.readUnsignedByte() / 60.0;
                longitude += buf.readUnsignedByte() / 6000.0;
                longitude += buf.readUnsignedByte() / 600000.0;
                int flags = buf.readUnsignedByte();
                if (BitUtil.check(flags, 0)) {
                    latitude = -latitude;
                }
                if (BitUtil.check(flags, 1)) {
                    longitude = -longitude;
                }
                position.setLatitude(latitude);
                position.setLongitude(longitude);
                int satellites = buf.readUnsignedByte();
                position.set(Position.KEY_SATELLITES, satellites);
                position.setValid(satellites >= 3);
                position.setSpeed(buf.readUnsignedByte());
                double course = buf.readUnsignedByte() << 1;
                course += (flags >> 2) & 1;
                course += buf.readUnsignedByte() / 100.0;
                position.setCourse(course);
                if (type == MSG_GPS_SENSORS) {
                    double power = buf.readUnsignedByte();
                    power += buf.readUnsignedByte() << 8;
                    position.set(Position.KEY_POWER, power * 0.01);
                    double battery = buf.readUnsignedByte();
                    battery += buf.readUnsignedByte() << 8;
                    position.set(Position.KEY_BATTERY, battery * 0.01);
                    buf.skipBytes(6);
                }
                positions.add(position);
            } else if (type == MSG_EVENTS) {
                buf.skipBytes(13);
            }
        }
        return positions;
    }
    return null;
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DeviceSession(org.traccar.DeviceSession) Position(org.traccar.model.Position) DateBuilder(org.traccar.helper.DateBuilder) List(java.util.List) LinkedList(java.util.LinkedList) ByteBuf(io.netty.buffer.ByteBuf)

Example 59 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project riposte by Nike-Inc.

the class RequestInfoImplTest method uber_constructor_works_for_valid_values.

@Test
public void uber_constructor_works_for_valid_values() {
    // given
    String uri = "/some/uri/path/%24foobar%26?notused=blah";
    HttpMethod method = HttpMethod.PATCH;
    Charset contentCharset = CharsetUtil.US_ASCII;
    HttpHeaders headers = new DefaultHttpHeaders().add("header1", "val1").add(HttpHeaders.Names.CONTENT_TYPE, "text/text charset=" + contentCharset.displayName());
    QueryStringDecoder queryParams = new QueryStringDecoder(uri + "?foo=bar&secondparam=secondvalue");
    Set<Cookie> cookies = new HashSet<>(Arrays.asList(new DefaultCookie("cookie1", "val1"), new DefaultCookie("cookie2", "val2")));
    Map<String, String> pathParams = Arrays.stream(new String[][] { { "pathParam1", "val1" }, { "pathParam2", "val2" } }).collect(Collectors.toMap(pair -> pair[0], pair -> pair[1]));
    String content = UUID.randomUUID().toString();
    byte[] contentBytes = content.getBytes();
    LastHttpContent chunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(contentBytes));
    chunk.trailingHeaders().add("trailingHeader1", "trailingVal1");
    List<HttpContent> contentChunks = Collections.singletonList(chunk);
    HttpVersion protocolVersion = HttpVersion.HTTP_1_1;
    boolean keepAlive = true;
    boolean fullRequest = true;
    boolean isMultipart = false;
    // when
    RequestInfoImpl<?> requestInfo = new RequestInfoImpl<>(uri, method, headers, chunk.trailingHeaders(), queryParams, cookies, pathParams, contentChunks, protocolVersion, keepAlive, fullRequest, isMultipart);
    // then
    assertThat("getUri should return passed in value", requestInfo.getUri(), is(uri));
    assertThat("getPath did not decode as expected", requestInfo.getPath(), is("/some/uri/path/$foobar&"));
    assertThat(requestInfo.getMethod(), is(method));
    assertThat(requestInfo.getHeaders(), is(headers));
    assertThat(requestInfo.getTrailingHeaders(), is(chunk.trailingHeaders()));
    assertThat(requestInfo.getQueryParams(), is(queryParams));
    assertThat(requestInfo.getCookies(), is(cookies));
    assertThat(requestInfo.pathTemplate, nullValue());
    assertThat(requestInfo.pathParams, is(pathParams));
    assertThat(requestInfo.getRawContentBytes(), is(contentBytes));
    assertThat(requestInfo.getRawContent(), is(content));
    assertThat(requestInfo.content, nullValue());
    assertThat(requestInfo.getContentCharset(), is(contentCharset));
    assertThat(requestInfo.getProtocolVersion(), is(protocolVersion));
    assertThat(requestInfo.isKeepAliveRequested(), is(keepAlive));
    assertThat(requestInfo.isCompleteRequestWithAllChunks, is(fullRequest));
    assertThat(requestInfo.isMultipart, is(isMultipart));
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) Unpooled(io.netty.buffer.Unpooled) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Mockito.doThrow(org.mockito.Mockito.doThrow) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) CharsetUtil(io.netty.util.CharsetUtil) Assertions(org.assertj.core.api.Assertions) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Mockito.doReturn(org.mockito.Mockito.doReturn) RequestContentDeserializationException(com.nike.riposte.server.error.exception.RequestContentDeserializationException) Set(java.util.Set) UUID(java.util.UUID) Cookie(io.netty.handler.codec.http.cookie.Cookie) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) Collectors(java.util.stream.Collectors) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Sets(com.google.common.collect.Sets) List(java.util.List) Type(java.lang.reflect.Type) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) HttpPostMultipartRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) RequestInfo(com.nike.riposte.server.http.RequestInfo) HttpVersion(io.netty.handler.codec.http.HttpVersion) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HashSet(java.util.HashSet) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) ClientCookieEncoder(io.netty.handler.codec.http.cookie.ClientCookieEncoder) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) PathParameterMatchingException(com.nike.riposte.server.error.exception.PathParameterMatchingException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Whitebox(com.nike.riposte.testutils.Whitebox) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) CoreMatchers.sameInstance(org.hamcrest.CoreMatchers.sameInstance) HttpContent(io.netty.handler.codec.http.HttpContent) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TestCase.fail(junit.framework.TestCase.fail) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test) IOException(java.io.IOException) Mockito.verify(org.mockito.Mockito.verify) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) Mockito.never(org.mockito.Mockito.never) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Pair(com.nike.internal.util.Pair) Collections(java.util.Collections) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Charset(java.nio.charset.Charset) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 60 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project riposte by Nike-Inc.

the class RequestInfoTest method getQueryParamSingle_returns_null_if_param_value_list_is_null.

@Test
public void getQueryParamSingle_returns_null_if_param_value_list_is_null() {
    // given
    QueryStringDecoder queryParamsMock = mock(QueryStringDecoder.class);
    Map<String, List<String>> params = new HashMap<>();
    doReturn(params).when(queryParamsMock).parameters();
    RequestInfo<?> requestInfoSpy = getSpy();
    doReturn(queryParamsMock).when(requestInfoSpy).getQueryParams();
    // when
    String value = requestInfoSpy.getQueryParamSingle("foo");
    // then
    assertThat(value, nullValue());
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) HashMap(java.util.HashMap) List(java.util.List) Test(org.junit.Test)

Aggregations

QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)70 List (java.util.List)29 Test (org.junit.Test)15 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)14 Map (java.util.Map)10 HashMap (java.util.HashMap)9 IOException (java.io.IOException)8 URI (java.net.URI)7 ByteBuf (io.netty.buffer.ByteBuf)6 HttpContent (io.netty.handler.codec.http.HttpContent)6 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)6 HttpPostRequestDecoder (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)6 ArrayList (java.util.ArrayList)6 HttpMethod (io.netty.handler.codec.http.HttpMethod)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 DeviceSession (org.traccar.DeviceSession)5 Position (org.traccar.model.Position)5 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)4 Channel (io.netty.channel.Channel)3 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)3