Search in sources :

Example 11 with Resource

use of org.apache.synapse.api.Resource in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testFindMatchingVerb.

/*
     *  This method will test for findMatchingVerb()
     * */
@Test
public void testFindMatchingVerb() {
    MessageContext synCtx = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION_STRATEGY)).thenReturn(null);
    Mockito.when(synCtx.getProperty(APIConstants.API_RESOURCE_CACHE_KEY)).thenReturn("abc");
    Mockito.when(synCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH)).thenReturn("abc");
    Mockito.when(synCtx.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("");
    Mockito.when(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(((Axis2MessageContext) synCtx).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    SynapseConfiguration synapseConfiguration = Mockito.mock(SynapseConfiguration.class);
    Mockito.when(synapseConfiguration.getAPI("abc")).thenReturn(new API("abc", "/"));
    Mockito.when(synCtx.getConfiguration()).thenReturn(synapseConfiguration);
    Mockito.when(synCtx.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    VerbInfoDTO verbInfoDTO = getDefaultVerbInfoDTO();
    APIKeyValidator apiKeyValidator = createAPIKeyValidator(true, getDefaultURITemplates("/menu", "GET"), verbInfoDTO);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.GATEWAY_RESOURCE_CACHE_ENABLED)).thenReturn("true");
    try {
        List<VerbInfoDTO> verbList = apiKeyValidator.findMatchingVerb(synCtx);
        int length = verbList.toArray().length;
        // Test for ResourceNotFoundexception
        PowerMockito.mockStatic(Cache.class);
        Cache cache = Mockito.mock(Cache.class);
        PowerMockito.mockStatic(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        PowerMockito.mockStatic(APIManagerConfigurationService.class);
        PowerMockito.mockStatic(CacheProvider.class);
        org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        final APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        PowerMockito.when(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        PowerMockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        CacheProvider cacheProvider = Mockito.mock(CacheProvider.class);
        PowerMockito.when(cacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);
        Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
        assertNotNull(verbList.get(0));
    // todo    Mockito.when(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION_STRATEGY)).thenReturn("url");
    } catch (ResourceNotFoundException e) {
        assert true;
    } catch (APISecurityException e) {
        fail("APISecurityException is thrown " + e);
    }
    APIKeyValidator apiKeyValidator1 = createAPIKeyValidator(false, getDefaultURITemplates("/menu", "GET"), verbInfoDTO);
    Resource resource = Mockito.mock(Resource.class);
    API api = new API("abc", "/");
    Mockito.when(synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/menu");
    api.addResource(resource);
    Mockito.when(synapseConfiguration.getAPI("abc")).thenReturn((api));
    try {
        List<VerbInfoDTO> verbInfoList = new ArrayList<>();
        verbInfoList.add(verbInfoDTO);
        // Test for matching verb is found path
        PowerMockito.mockStatic(Cache.class);
        Cache cache = Mockito.mock(Cache.class);
        PowerMockito.mockStatic(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        PowerMockito.mockStatic(APIManagerConfigurationService.class);
        PowerMockito.mockStatic(CacheProvider.class);
        org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        final APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        PowerMockito.when(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        PowerMockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        CacheProvider cacheProvider = Mockito.mock(CacheProvider.class);
        PowerMockito.when(cacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);
        Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
        assertEquals("", verbInfoList, apiKeyValidator1.findMatchingVerb(synCtx));
    } catch (ResourceNotFoundException e) {
        fail("ResourceNotFoundException exception is thrown " + e);
    } catch (APISecurityException e) {
        fail("APISecurityException is thrown " + e);
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) Resource(org.apache.synapse.api.Resource) ArrayList(java.util.ArrayList) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) CacheProvider(org.wso2.carbon.apimgt.impl.caching.CacheProvider) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) API(org.apache.synapse.api.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 12 with Resource

use of org.apache.synapse.api.Resource in project carbon-apimgt by wso2.

the class CORSRequestHandler method handleResourceNotFound.

private void handleResourceNotFound(MessageContext messageContext, List<Resource> allAPIResources) {
    Resource uriMatchingResource = null;
    for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
        uriMatchingResource = dispatcher.findResource(messageContext, allAPIResources);
        // If a resource with a matching URI was found.
        if (uriMatchingResource != null) {
            onResourceNotFoundError(messageContext, HttpStatus.SC_METHOD_NOT_ALLOWED, APIMgtGatewayConstants.METHOD_NOT_FOUND_ERROR_MSG);
            return;
        }
    }
    // If a resource with a matching URI was not found.
    // Respond with a 404.
    onResourceNotFoundError(messageContext, HttpStatus.SC_NOT_FOUND, APIMgtGatewayConstants.RESOURCE_NOT_FOUND_ERROR_MSG);
}
Also used : RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) Resource(org.apache.synapse.api.Resource)

Example 13 with Resource

use of org.apache.synapse.api.Resource in project carbon-apimgt by wso2.

the class WebSocketUtils method getEndpointUrl.

/**
 * Gets the uri-template of the endpoint, which has been specified in the given resource.
 * @param resource  API Resource
 * @param synCtx    MessageContext
 * @return          URI template
 */
public static String getEndpointUrl(Resource resource, MessageContext synCtx) {
    Optional<Mediator> filterMediator = resource.getInSequence().getList().stream().filter(m -> m instanceof FilterMediator).findFirst();
    if (filterMediator.isPresent()) {
        Optional<Mediator> sendMediator = ((FilterMediator) filterMediator.get()).getList().stream().filter(m -> m instanceof SendMediator).findFirst();
        if (sendMediator.isPresent()) {
            Endpoint endpoint = ((SendMediator) sendMediator.get()).getEndpoint();
            if (endpoint instanceof IndirectEndpoint) {
                String endpointKey = ((IndirectEndpoint) endpoint).getKey();
                Endpoint directEndpoint = synCtx.getConfiguration().getEndpoint(endpointKey);
                if (directEndpoint instanceof HTTPEndpoint) {
                    return ((HTTPEndpoint) synCtx.getConfiguration().getEndpoint(endpointKey)).getUriTemplate().getTemplate();
                }
            }
        }
    }
    // Ideally we won't reach here
    return null;
}
Also used : AttributeKey(io.netty.util.AttributeKey) HTTPEndpoint(org.apache.synapse.endpoints.HTTPEndpoint) SendMediator(org.apache.synapse.mediators.builtin.SendMediator) HashMap(java.util.HashMap) IndirectEndpoint(org.apache.synapse.endpoints.IndirectEndpoint) FilterMediator(org.apache.synapse.mediators.filters.FilterMediator) Endpoint(org.apache.synapse.endpoints.Endpoint) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Mediator(org.apache.synapse.Mediator) Map(java.util.Map) Resource(org.apache.synapse.api.Resource) Optional(java.util.Optional) MessageContext(org.apache.synapse.MessageContext) IndirectEndpoint(org.apache.synapse.endpoints.IndirectEndpoint) HTTPEndpoint(org.apache.synapse.endpoints.HTTPEndpoint) HTTPEndpoint(org.apache.synapse.endpoints.HTTPEndpoint) IndirectEndpoint(org.apache.synapse.endpoints.IndirectEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) FilterMediator(org.apache.synapse.mediators.filters.FilterMediator) SendMediator(org.apache.synapse.mediators.builtin.SendMediator) FilterMediator(org.apache.synapse.mediators.filters.FilterMediator) Mediator(org.apache.synapse.Mediator) SendMediator(org.apache.synapse.mediators.builtin.SendMediator)

Example 14 with Resource

use of org.apache.synapse.api.Resource 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 15 with Resource

use of org.apache.synapse.api.Resource in project carbon-apimgt by wso2.

the class CORSRequestHandlerTestCase method testHandleRequest.

@Test
public void testHandleRequest() throws Exception {
    PowerMockito.mockStatic(Utils.class);
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/ishara");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin-AT-wso2.com--PizzaShackAPI");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    SynapseConfiguration synapseConfiguration = Mockito.mock(SynapseConfiguration.class);
    API api = Mockito.mock(API.class);
    Mockito.when(api.getContext()).thenReturn("/ishara");
    Resource resource = Mockito.mock(Resource.class);
    Resource[] resources = new Resource[1];
    resources[0] = resource;
    Mockito.when(api.getResources()).thenReturn(resources);
    VersionStrategy versionStrategy = Mockito.mock(VersionStrategy.class);
    Mockito.when(versionStrategy.getVersionType()).thenReturn("url");
    Mockito.when(versionStrategy.getVersion()).thenReturn("1.0");
    Mockito.when(api.getVersionStrategy()).thenReturn(versionStrategy);
    Mockito.when(Utils.getSelectedAPI(messageContext)).thenReturn(api);
    Mockito.when(synapseConfiguration.getAPI("admin-AT-wso2.com--PizzaShackAPI")).thenReturn(api);
    Mockito.when(messageContext.getConfiguration()).thenReturn(synapseConfiguration);
    CORSRequestHandler corsRequestHandler = createCORSRequestHandler();
    corsRequestHandler.init(synapseEnvironment);
    // test ResourceNotFound path
    Assert.assertFalse(corsRequestHandler.handleRequest(messageContext));
    // test for resource that is found
    String[] methods = { "GET", "POST" };
    Mockito.when(resource.getMethods()).thenReturn(methods);
    DispatcherHelper dispatcherHelper = new URLMappingHelper("/ishara/1.0") {

        @Override
        public String getString() {
            return "/xx";
        }
    };
    Mockito.when(resource.getDispatcherHelper()).thenReturn(dispatcherHelper);
    Mockito.when(messageContext.getProperty("REST_SUB_REQUEST_PATH")).thenReturn("/ishara/1.0");
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put("Origin", "");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Assert.assertTrue(corsRequestHandler.handleRequest(messageContext));
    DispatcherHelper dispatcherHelper1 = new URLMappingHelper("/ishara/1.0") {

        @Override
        public String getString() {
            return "/xx";
        }
    };
    Mockito.when(resource.getDispatcherHelper()).thenReturn(dispatcherHelper1);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("OPTIONS");
    // test for OPTIONS request when OPTIONS is not supported by SupportedHTTPVerbs
    Assert.assertFalse(corsRequestHandler.handleRequest(messageContext));
    // test for OPTIONS request when OPTIONS is supported by SupportedHTTPVerbs
    String[] methodsWithOptions = { "GET", "POST", "OPTIONS" };
    Mockito.when(resource.getMethods()).thenReturn(methodsWithOptions);
    Assert.assertTrue(corsRequestHandler.handleRequest(messageContext));
}
Also used : HashMap(java.util.HashMap) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) DispatcherHelper(org.apache.synapse.api.dispatch.DispatcherHelper) URLMappingHelper(org.apache.synapse.api.dispatch.URLMappingHelper) Resource(org.apache.synapse.api.Resource) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) TreeMap(java.util.TreeMap) VersionStrategy(org.apache.synapse.api.version.VersionStrategy) API(org.apache.synapse.api.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Resource (org.apache.synapse.api.Resource)29 API (org.apache.synapse.api.API)23 MessageContext (org.apache.synapse.MessageContext)19 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)17 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)10 URLMappingHelper (org.apache.synapse.api.dispatch.URLMappingHelper)7 URITemplateHelper (org.apache.synapse.api.dispatch.URITemplateHelper)5 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 Mediator (org.apache.synapse.Mediator)4 RESTDispatcher (org.apache.synapse.api.dispatch.RESTDispatcher)4 Test (org.junit.Test)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 HashMap (java.util.HashMap)3 LinkedHashSet (java.util.LinkedHashSet)3 Cache (javax.cache.Cache)3 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)3 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)3 CacheProvider (org.wso2.carbon.apimgt.impl.caching.CacheProvider)3 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)3