Search in sources :

Example 1 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext in project carbon-apimgt by wso2.

the class WebsocketHandlerTestCase method testGraphQLWriteResponse.

@Test
public void testGraphQLWriteResponse() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    inboundMessageContext.setElectedAPI(graphQLAPI);
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    msg = new TextWebSocketFrame("{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{}," + "\"extensions\":{},\"operationName\":null," + "\"query\":\"subscription {\\n  liftStatusChange {\\n    id\\n    name\\n    }\\n}\\n\"}}");
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setHttpVerb(GraphQLConstants.SubscriptionConstants.HTTP_METHOD_NAME);
    verbInfoDTO.setAuthType("OAUTH");
    GraphQLOperationDTO graphQLOperationDTO = new GraphQLOperationDTO(verbInfoDTO, "liftStatusChange");
    inboundMessageContext.addVerbInfoForGraphQLMsgId("1", graphQLOperationDTO);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(Mockito.anyInt(), Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
    // happy path
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// No error has occurred context exists in data-holder map.
    channelIdString)));
    // close connection error
    responseDTO.setError(true);
    responseDTO.setCloseConnection(true);
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertFalse(InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// Closing connection error has occurred
    channelIdString));
    // Websocket frame error has occurred
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    responseDTO.setError(true);
    responseDTO.setCloseConnection(false);
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelIdString)));
}
Also used : GraphQLOperationDTO(org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 2 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext in project carbon-apimgt by wso2.

the class WebsocketInboundHandlerTestCase method testWSFrameResponse.

@Test
public void testWSFrameResponse() throws Exception {
    InboundMessageContext inboundMessageContext = createWebSocketApiMessageContext();
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    ByteBuf content = Mockito.mock(ByteBuf.class);
    WebSocketFrame msg = Mockito.mock(WebSocketFrame.class);
    Mockito.when(msg.content()).thenReturn(content);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    Mockito.when(inboundWebSocketProcessor.handleRequest(msg, inboundMessageContext)).thenReturn(responseDTO);
    websocketInboundHandler.channelRead(channelHandlerContext, msg);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// No error has occurred context exists in data-holder map.
    channelIdString)));
    // error response
    responseDTO.setError(true);
    websocketInboundHandler.channelRead(channelHandlerContext, msg);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelIdString)));
    // close connection error response
    responseDTO.setCloseConnection(true);
    websocketInboundHandler.channelRead(channelHandlerContext, msg);
    Assert.assertFalse((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelIdString)));
}
Also used : InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext in project carbon-apimgt by wso2.

the class WebsocketInboundHandlerTestCase method testWSHandshakeResponse.

@Test
public void testWSHandshakeResponse() throws Exception {
    InboundMessageContext inboundMessageContext = createWebSocketApiMessageContext();
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    String headerName = "test-header";
    String headerValue = "test-header-value";
    String strWebSocket = "websocket";
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    FullHttpRequest fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "ws://localhost:8080/graphql");
    fullHttpRequest.headers().set(headerName, headerValue);
    fullHttpRequest.headers().set(HttpHeaders.UPGRADE, strWebSocket);
    Mockito.when(inboundWebSocketProcessor.handleHandshake(fullHttpRequest, channelHandlerContext, inboundMessageContext)).thenReturn(responseDTO);
    websocketInboundHandler.channelRead(channelHandlerContext, fullHttpRequest);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// No error has occurred context exists in data-holder map.
    channelIdString)));
    Assert.assertEquals(inboundMessageContext.getRequestHeaders().get(headerName), headerValue);
    Assert.assertEquals(inboundMessageContext.getToken(), fullHttpRequest.headers().get(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER));
    Assert.assertEquals(inboundMessageContext.getUserIP(), remoteIP);
    // error response
    responseDTO.setError(true);
    responseDTO.setErrorMessage("error");
    fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "ws://localhost:8080/graphql");
    Mockito.when(inboundWebSocketProcessor.handleHandshake(fullHttpRequest, channelHandlerContext, inboundMessageContext)).thenReturn(responseDTO);
    fullHttpRequest.headers().set(headerName, headerValue);
    fullHttpRequest.headers().set(HttpHeaders.UPGRADE, strWebSocket);
    websocketInboundHandler.channelRead(channelHandlerContext, fullHttpRequest);
    Assert.assertFalse(InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// Closing connection error has occurred
    channelIdString));
    Assert.assertFalse(fullHttpRequest.headers().contains(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER));
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext in project carbon-apimgt by wso2.

the class WebsocketHandler method write.

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    String channelId = ctx.channel().id().asLongText();
    InboundMessageContext inboundMessageContext;
    if (InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelId)) {
        inboundMessageContext = InboundMessageContextDataHolder.getInstance().getInboundMessageContextForConnectionId(channelId);
    } else {
        inboundMessageContext = new InboundMessageContext();
        InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelId, inboundMessageContext);
    }
    if (APIUtil.isAnalyticsEnabled()) {
        WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.REQUEST_START_TIME_PROPERTY, System.currentTimeMillis());
    }
    if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PongWebSocketFrame)) {
        // remove inbound message context from data holder
        InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().remove(channelId);
        // if the inbound frame is a closed frame, throttling, analytics will not be published.
        outboundHandler().write(ctx, msg, promise);
    } else if (msg instanceof WebSocketFrame) {
        InboundProcessorResponseDTO responseDTO = inboundHandler().getWebSocketProcessor().handleResponse((WebSocketFrame) msg, inboundMessageContext);
        if (responseDTO.isError()) {
            if (responseDTO.isCloseConnection()) {
                InboundMessageContextDataHolder.getInstance().removeInboundMessageContextForConnection(channelId);
                if (log.isDebugEnabled()) {
                    log.debug("Error while handling Outbound Websocket frame. Closing connection for " + ctx.channel().toString());
                }
                outboundHandler().write(ctx, new CloseWebSocketFrame(responseDTO.getErrorCode(), responseDTO.getErrorMessage() + StringUtils.SPACE + "Connection closed" + "!"), promise);
                outboundHandler().flush(ctx);
                outboundHandler().close(ctx, promise);
            } else {
                String errorMessage = responseDTO.getErrorResponseString();
                outboundHandler().write(ctx, new TextWebSocketFrame(errorMessage), promise);
                if (responseDTO.getErrorCode() == WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR) {
                    if (log.isDebugEnabled()) {
                        log.debug("Outbound Websocket frame is throttled. " + ctx.channel().toString());
                    }
                    publishSubscribeThrottledEvent(ctx);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Outbound Websocket frame." + ctx.channel().toString());
            }
            outboundHandler().write(ctx, msg, promise);
            // publish analytics events if analytics is enabled
            publishSubscribeEvent(ctx);
        }
    } else {
        outboundHandler().write(ctx, msg, promise);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)

Example 5 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext in project carbon-apimgt by wso2.

the class HandshakeProcessorTest method handleSuccessfulHandshake.

@Test
public void handleSuccessfulHandshake() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    URLMapping urlMapping = new URLMapping();
    urlMapping.setHttpMethod("SUBSCRIPTION");
    urlMapping.setThrottlingPolicy("Unlimited");
    urlMapping.setUrlPattern("liftStatusChange");
    org.wso2.carbon.apimgt.keymgt.model.entity.API api = new API();
    api.addResource(urlMapping);
    inboundMessageContext.setElectedAPI(api);
    PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
    PowerMockito.when(InboundWebsocketProcessorUtil.isAuthenticated(inboundMessageContext)).thenReturn(true);
    HandshakeProcessor handshakeProcessor = new HandshakeProcessor();
    InboundProcessorResponseDTO inboundProcessorResponseDTO = handshakeProcessor.processHandshake(inboundMessageContext);
    Assert.assertFalse(inboundProcessorResponseDTO.isError());
    Assert.assertNull(inboundProcessorResponseDTO.getErrorMessage());
    Assert.assertFalse(inboundProcessorResponseDTO.isCloseConnection());
}
Also used : API(org.wso2.carbon.apimgt.keymgt.model.entity.API) URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

InboundProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO)32 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)31 Test (org.junit.Test)26 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)26 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)15 GraphQLProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO)12 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)8 GraphQLOperationDTO (org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO)7 GraphQLSchema (graphql.schema.GraphQLSchema)6 SchemaParser (graphql.schema.idl.SchemaParser)6 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)6 JSONObject (org.json.simple.JSONObject)6 JSONParser (org.json.simple.parser.JSONParser)6 GraphQLSchemaDTO (org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO)6 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)5 WebSocketApiException (org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException)4 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)3 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)3