Search in sources :

Example 21 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project netty-socketio by mrniko.

the class PollingTransport method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
        List<String> transport = queryDecoder.parameters().get("transport");
        if (transport != null && NAME.equals(transport.get(0))) {
            List<String> sid = queryDecoder.parameters().get("sid");
            List<String> j = queryDecoder.parameters().get("j");
            List<String> b64 = queryDecoder.parameters().get("b64");
            String origin = req.headers().get(HttpHeaderNames.ORIGIN);
            ctx.channel().attr(EncoderHandler.ORIGIN).set(origin);
            String userAgent = req.headers().get(HttpHeaderNames.USER_AGENT);
            ctx.channel().attr(EncoderHandler.USER_AGENT).set(userAgent);
            if (j != null && j.get(0) != null) {
                Integer index = Integer.valueOf(j.get(0));
                ctx.channel().attr(EncoderHandler.JSONP_INDEX).set(index);
            }
            if (b64 != null && b64.get(0) != null) {
                Integer enable = Integer.valueOf(b64.get(0));
                ctx.channel().attr(EncoderHandler.B64).set(enable == 1);
            }
            try {
                if (sid != null && sid.get(0) != null) {
                    final UUID sessionId = UUID.fromString(sid.get(0));
                    handleMessage(req, sessionId, queryDecoder, ctx);
                } else {
                    // first connection
                    ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
                    handleMessage(req, client.getSessionId(), queryDecoder, ctx);
                }
            } finally {
                req.release();
            }
            return;
        }
    }
    ctx.fireChannelRead(msg);
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ClientHead(com.corundumstudio.socketio.handler.ClientHead) UUID(java.util.UUID)

Example 22 with QueryStringDecoder

use of io.netty.handler.codec.http.QueryStringDecoder in project netty-socketio by mrniko.

the class WebSocketTransport method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof CloseWebSocketFrame) {
        ctx.channel().close();
        ReferenceCountUtil.release(msg);
    } else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) {
        ByteBufHolder frame = (ByteBufHolder) msg;
        ClientHead client = clientsBox.get(ctx.channel());
        if (client == null) {
            log.debug("Client with was already disconnected. Channel closed!");
            ctx.channel().close();
            frame.release();
            return;
        }
        ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET));
        frame.release();
    } else if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
        String path = queryDecoder.path();
        List<String> transport = queryDecoder.parameters().get("transport");
        List<String> sid = queryDecoder.parameters().get("sid");
        if (transport != null && NAME.equals(transport.get(0))) {
            try {
                if (!configuration.getTransports().contains(Transport.WEBSOCKET)) {
                    log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET);
                    ctx.channel().close();
                    return;
                }
                if (sid != null && sid.get(0) != null) {
                    final UUID sessionId = UUID.fromString(sid.get(0));
                    handshake(ctx, sessionId, path, req);
                } else {
                    ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
                    // first connection
                    handshake(ctx, client.getSessionId(), path, req);
                }
            } finally {
                req.release();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PacketsMessage(com.corundumstudio.socketio.messages.PacketsMessage) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) ByteBufHolder(io.netty.buffer.ByteBufHolder) ClientHead(com.corundumstudio.socketio.handler.ClientHead) UUID(java.util.UUID)

Example 23 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) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Whitebox(org.mockito.internal.util.reflection.Whitebox) 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) 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) 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 24 with QueryStringDecoder

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

the class RequestInfoImpl method dummyInstanceForUnknownRequests.

/**
     * Creates a new RequestInfo that represents unknown requests. Usually only needed in error situations. The URI,
     * query params, and headers will be tagged with {@link #NONE_OR_UNKNOWN_TAG} to indicate that the request was
     * unknown.
     */
public static RequestInfoImpl<?> dummyInstanceForUnknownRequests() {
    HttpHeaders headers = new DefaultHttpHeaders().set(NONE_OR_UNKNOWN_TAG, "true");
    QueryStringDecoder queryParams = new QueryStringDecoder("/?" + NONE_OR_UNKNOWN_TAG + "=true");
    return new RequestInfoImpl(NONE_OR_UNKNOWN_TAG, null, headers, null, queryParams, null, null, null, null, false, true, false);
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders)

Example 25 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)28 Test (org.junit.Test)11 List (java.util.List)10 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)5 HttpContent (io.netty.handler.codec.http.HttpContent)5 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)4 HashMap (java.util.HashMap)4 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)3 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)3 HttpPostRequestDecoder (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)3 IOException (java.io.IOException)3 Map (java.util.Map)3 UUID (java.util.UUID)3 ClientHead (com.corundumstudio.socketio.handler.ClientHead)2 ByteBuf (io.netty.buffer.ByteBuf)2 Channel (io.netty.channel.Channel)2 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)2 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)2 HttpResponse (io.netty.handler.codec.http.HttpResponse)2