Search in sources :

Example 46 with InboundMessageContext

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

the class InboundWebSocketProcessor method setMatchingResource.

/**
 * Get matching resource for invoking handshake request.
 *
 * @param ctx                   Channel context
 * @param req                   Handshake request
 * @param inboundMessageContext InboundMessageContext
 * @throws WebSocketApiException     If an error occurs
 * @throws ResourceNotFoundException If no matching API or resource found
 */
private void setMatchingResource(ChannelHandlerContext ctx, FullHttpRequest req, InboundMessageContext inboundMessageContext) throws WebSocketApiException, ResourceNotFoundException {
    String matchingResource;
    try {
        MessageContext synCtx = getMessageContext(inboundMessageContext);
        API api = InboundWebsocketProcessorUtil.getApi(synCtx, inboundMessageContext);
        if (api == null) {
            throw new ResourceNotFoundException("No matching API found to dispatch the request");
        }
        inboundMessageContext.setApi(api);
        reConstructFullUriWithVersion(req, synCtx, inboundMessageContext);
        inboundMessageContext.setApiContext(api.getContext());
        Resource selectedResource = null;
        Utils.setSubRequestPath(api, synCtx);
        Set<Resource> acceptableResources = new LinkedHashSet<>(Arrays.asList(api.getResources()));
        if (!acceptableResources.isEmpty()) {
            for (RESTDispatcher dispatcher : ApiUtils.getDispatchers()) {
                Resource resource = dispatcher.findResource(synCtx, acceptableResources);
                if (resource != null) {
                    selectedResource = resource;
                    if (APIUtil.isAnalyticsEnabled()) {
                        WebSocketUtils.setApiPropertyToChannel(ctx, APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS, WebSocketUtils.getEndpointUrl(resource, synCtx));
                    }
                    break;
                }
            }
        }
        setApiPropertiesToChannel(ctx, inboundMessageContext);
        if (selectedResource == null) {
            throw new ResourceNotFoundException("No matching resource found to dispatch the request");
        }
        if (APIConstants.GRAPHQL_API.equals(inboundMessageContext.getElectedAPI().getApiType())) {
            inboundMessageContext.setGraphQLSchemaDTO(DataHolder.getInstance().getGraphQLSchemaDTOForAPI(inboundMessageContext.getElectedAPI().getUuid()));
        }
        matchingResource = selectedResource.getDispatcherHelper().getString();
        if (log.isDebugEnabled()) {
            log.info("Selected resource for API dispatch : " + matchingResource);
        }
    } catch (AxisFault | URISyntaxException e) {
        throw new WebSocketApiException("Error while getting matching resource for Websocket API");
    }
    inboundMessageContext.setMatchingResource(matchingResource);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) AxisFault(org.apache.axis2.AxisFault) RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) Resource(org.apache.synapse.api.Resource) API(org.apache.synapse.api.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) URISyntaxException(java.net.URISyntaxException) ResourceNotFoundException(org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException)

Example 47 with InboundMessageContext

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

the class InboundWebSocketProcessor method handleResponse.

/**
 * This method process websocket response messages (subscribe messages) and
 * hand over the processing to relevant response intercepting processor for authentication, scope validation,
 * throttling etc.
 *
 * @param msg                   Websocket request message frame
 * @param inboundMessageContext InboundMessageContext
 * @return InboundProcessorResponseDTO with handshake processing response
 */
public InboundProcessorResponseDTO handleResponse(WebSocketFrame msg, InboundMessageContext inboundMessageContext) throws Exception {
    ResponseProcessor responseProcessor;
    String msgText = null;
    if (APIConstants.GRAPHQL_API.equals(inboundMessageContext.getElectedAPI().getApiType()) && msg instanceof TextWebSocketFrame) {
        responseProcessor = new GraphQLResponseProcessor();
        msgText = ((TextWebSocketFrame) msg).text();
    } else {
        responseProcessor = new ResponseProcessor();
    }
    return responseProcessor.handleResponse(msg.content().capacity(), msgText, inboundMessageContext);
}
Also used : GraphQLResponseProcessor(org.wso2.carbon.apimgt.gateway.inbound.websocket.response.GraphQLResponseProcessor) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) GraphQLResponseProcessor(org.wso2.carbon.apimgt.gateway.inbound.websocket.response.GraphQLResponseProcessor) ResponseProcessor(org.wso2.carbon.apimgt.gateway.inbound.websocket.response.ResponseProcessor)

Example 48 with InboundMessageContext

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

the class GraphQLRequestProcessor method validateQueryPayload.

/**
 * Validates GraphQL query payload using QueryValidator and graphql schema of the invoking API.
 *
 * @param inboundMessageContext InboundMessageContext
 * @param document              Graphql payload
 * @param operationId           Graphql message id
 * @return InboundProcessorResponseDTO
 */
private InboundProcessorResponseDTO validateQueryPayload(InboundMessageContext inboundMessageContext, Document document, String operationId) {
    GraphQLProcessorResponseDTO responseDTO = new GraphQLProcessorResponseDTO();
    responseDTO.setId(operationId);
    QueryValidator queryValidator = new QueryValidator(new Validator());
    // payload validation
    String validationErrorMessage = queryValidator.validatePayload(inboundMessageContext.getGraphQLSchemaDTO().getGraphQLSchema(), document);
    if (validationErrorMessage != null) {
        String error = WebSocketApiConstants.FrameErrorConstants.GRAPHQL_INVALID_QUERY_MESSAGE + " : " + validationErrorMessage;
        log.error(error);
        responseDTO.setError(true);
        responseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.GRAPHQL_INVALID_QUERY);
        responseDTO.setErrorMessage(error);
        return responseDTO;
    }
    return responseDTO;
}
Also used : GraphQLProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO) QueryValidator(org.wso2.carbon.apimgt.common.gateway.graphql.QueryValidator) QueryValidator(org.wso2.carbon.apimgt.common.gateway.graphql.QueryValidator) Validator(graphql.validation.Validator)

Example 49 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext 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 50 with InboundMessageContext

use of org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext 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)

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