Search in sources :

Example 41 with InboundProcessorResponseDTO

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

the class WebsocketHandlerTestCase method testWSWriteSuccessResponse.

/*
     * This method tests write() when msg is a WebSocketFrame for WebSocket API.
     * */
@Test
public void testWSWriteSuccessResponse() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    inboundMessageContext.setElectedAPI(websocketAPI);
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottle(Mockito.anyInt(), Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// No error has occurred context exists in data-holder map.
    channelIdString)));
}
Also used : 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 42 with InboundProcessorResponseDTO

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

the class WebsocketHandlerTestCase method testWSWriteErrorResponse.

/*
     * This method tests write() when msg is a WebSocketFrame for WebSocket API and returns error responses.
     * */
@Test
public void testWSWriteErrorResponse() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    inboundMessageContext.setElectedAPI(websocketAPI);
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    responseDTO.setError(true);
    responseDTO.setCloseConnection(true);
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottle(Mockito.anyInt(), Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
    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 : 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 43 with InboundProcessorResponseDTO

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

the class WebsocketInboundHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    String channelId = ctx.channel().id().asLongText();
    // This block is for the health check of the ports 8099 and 9099
    if (msg instanceof FullHttpRequest && ((FullHttpRequest) msg).headers() != null && !((FullHttpRequest) msg).headers().contains(HttpHeaders.UPGRADE) && ((FullHttpRequest) msg).uri().equals(APIConstants.WEB_SOCKET_HEALTH_CHECK_PATH)) {
        ctx.fireChannelRead(msg);
        return;
    }
    InboundMessageContext inboundMessageContext;
    if (InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelId)) {
        inboundMessageContext = InboundMessageContextDataHolder.getInstance().getInboundMessageContextForConnectionId(channelId);
    } else {
        inboundMessageContext = new InboundMessageContext();
        InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelId, inboundMessageContext);
    }
    inboundMessageContext.setUserIP(getRemoteIP(ctx));
    if (APIUtil.isAnalyticsEnabled()) {
        WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.REQUEST_START_TIME_PROPERTY, System.currentTimeMillis());
        WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.USER_IP_PROPERTY, inboundMessageContext.getUserIP());
    }
    // check if the request is a handshake
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        populateContextHeaders(req, inboundMessageContext);
        InboundProcessorResponseDTO responseDTO = webSocketProcessor.handleHandshake(req, ctx, inboundMessageContext);
        if (!responseDTO.isError()) {
            setApiAuthPropertiesToChannel(ctx, inboundMessageContext);
            if (StringUtils.isNotEmpty(inboundMessageContext.getToken())) {
                req.headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, inboundMessageContext.getToken());
            }
            ctx.fireChannelRead(req);
            publishHandshakeEvent(ctx, inboundMessageContext);
            InboundWebsocketProcessorUtil.publishGoogleAnalyticsData(inboundMessageContext, ctx.channel().remoteAddress().toString());
        } else {
            InboundMessageContextDataHolder.getInstance().removeInboundMessageContextForConnection(channelId);
            FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(responseDTO.getErrorCode()), Unpooled.copiedBuffer(responseDTO.getErrorMessage(), CharsetUtil.UTF_8));
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
            ctx.writeAndFlush(httpResponse);
        }
    } else if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PingWebSocketFrame)) {
        // 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.
        ctx.fireChannelRead(msg);
    } else if (msg instanceof WebSocketFrame) {
        InboundProcessorResponseDTO responseDTO = webSocketProcessor.handleRequest((WebSocketFrame) msg, inboundMessageContext);
        if (responseDTO.isError()) {
            if (responseDTO.isCloseConnection()) {
                // remove inbound message context from data holder
                InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().remove(channelId);
                if (log.isDebugEnabled()) {
                    log.debug("Error while handling Outbound Websocket frame. Closing connection for " + ctx.channel().toString());
                }
                ctx.writeAndFlush(new CloseWebSocketFrame(responseDTO.getErrorCode(), responseDTO.getErrorMessage() + StringUtils.SPACE + "Connection closed" + "!"));
                ctx.close();
            } else {
                String errorMessage = responseDTO.getErrorResponseString();
                ctx.writeAndFlush(new TextWebSocketFrame(errorMessage));
                if (responseDTO.getErrorCode() == WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR) {
                    if (log.isDebugEnabled()) {
                        log.debug("Inbound Websocket frame is throttled. " + ctx.channel().toString());
                    }
                    publishPublishThrottledEvent(ctx);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Inbound Websocket frame." + ctx.channel().toString());
            }
            ctx.fireChannelRead(msg);
            // publish analytics events if analytics is enabled
            publishPublishEvent(ctx);
        }
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) 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) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Aggregations

InboundProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO)35 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)28 Test (org.junit.Test)26 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)26 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)13 GraphQLProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO)12 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 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)6 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)5 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)4 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)3 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)3 JSONObject (org.json.JSONObject)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3