Search in sources :

Example 31 with API

use of org.apache.synapse.api.API in project wso2-synapse by wso2.

the class APISerializationTest method testAPISerialization3.

public void testAPISerialization3() throws Exception {
    String xml = "<api name=\"test\" context=\"/dictionary\" binds-to=\"\" transports=\"https\" hostname=\"apache.org\" port=\"8243\"" + " xmlns=\"http://ws.apache.org/ns/synapse\"><resource binds-to=\"\" url-mapping=\"/admin/view\" " + "inSequence=\"in\"><outSequence><log/><send/></outSequence></resource></api>";
    OMElement om = AXIOMUtil.stringToOM(xml);
    API api = APIFactory.createAPI(om);
    OMElement out = APISerializer.serializeAPI(api);
    assertXMLEqual(xml, out.toString());
}
Also used : OMElement(org.apache.axiom.om.OMElement) API(org.apache.synapse.api.API)

Example 32 with API

use of org.apache.synapse.api.API in project wso2-synapse by wso2.

the class APISerializationTest method testAPISerialization1.

public void testAPISerialization1() throws Exception {
    String xml = "<api name=\"test\" context=\"/dictionary\" binds-to=\"\" transports=\"https\" xmlns=\"http://ws.apache.org/ns/synapse\">" + "<resource binds-to=\"\" url-mapping=\"/admin/view\" inSequence=\"in\" outSequence=\"out\"/></api>";
    OMElement om = AXIOMUtil.stringToOM(xml);
    API api = APIFactory.createAPI(om);
    OMElement out = APISerializer.serializeAPI(api);
    assertXMLEqual(xml, out.toString());
}
Also used : OMElement(org.apache.axiom.om.OMElement) API(org.apache.synapse.api.API)

Example 33 with API

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

use of org.apache.synapse.api.API 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)

Example 35 with API

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

the class APIKeyValidator method findMatchingVerb.

public List<VerbInfoDTO> findMatchingVerb(MessageContext synCtx) throws ResourceNotFoundException, APISecurityException {
    List<VerbInfoDTO> verbInfoList = new ArrayList<>();
    String resourceCacheKey;
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String fullRequestPath = (String) synCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
    String electedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    ArrayList<String> resourceArray = null;
    if (electedResource != null) {
        if (APIConstants.GRAPHQL_API.equalsIgnoreCase((String) synCtx.getProperty(APIConstants.API_TYPE))) {
            resourceArray = new ArrayList<>(Arrays.asList(electedResource.split(",")));
        } else {
            resourceArray = new ArrayList<>(Arrays.asList(electedResource));
        }
    }
    String requestPath = getRequestPath(synCtx, apiContext, apiVersion, fullRequestPath);
    if ("".equals(requestPath)) {
        requestPath = "/";
    }
    if (log.isDebugEnabled()) {
        log.debug("Setting REST_SUB_REQUEST_PATH in msg context: " + requestPath);
    }
    synCtx.setProperty(RESTConstants.REST_SUB_REQUEST_PATH, requestPath);
    // verb has been put into the cache.
    if (resourceArray != null) {
        for (String resourceString : resourceArray) {
            VerbInfoDTO verbInfo;
            if (isGatewayAPIResourceValidationEnabled) {
                String apiCacheKey = APIUtil.getAPIInfoDTOCacheKey(apiContext, apiVersion);
                if (!getResourceCache().containsKey(apiCacheKey)) {
                    break;
                }
                resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
                verbInfo = (VerbInfoDTO) getResourceCache().get(resourceCacheKey);
                // Cache hit
                if (verbInfo != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Found resource in Cache for key: " + resourceCacheKey);
                    }
                    verbInfoList.add(verbInfo);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Resource not found in cache for key: " + resourceCacheKey);
                    }
                }
            }
        }
        if (resourceArray.size() == verbInfoList.size()) {
            return verbInfoList;
        }
    } else {
        API selectedApi = Utils.getSelectedAPI(synCtx);
        Resource selectedResource = null;
        String resourceString;
        if (selectedApi != null) {
            Resource[] selectedAPIResources = selectedApi.getResources();
            Set<Resource> acceptableResources = new LinkedHashSet<Resource>();
            for (Resource resource : selectedAPIResources) {
                // If the requesting method is OPTIONS or if the Resource contains the requesting method
                if (RESTConstants.METHOD_OPTIONS.equals(httpMethod) || (resource.getMethods() != null && Arrays.asList(resource.getMethods()).contains(httpMethod))) {
                    acceptableResources.add(resource);
                }
            }
            if (acceptableResources.size() > 0) {
                for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
                    Resource resource = dispatcher.findResource(synCtx, acceptableResources);
                    if (resource != null && Arrays.asList(resource.getMethods()).contains(httpMethod)) {
                        selectedResource = resource;
                        break;
                    }
                }
            }
        }
        if (selectedResource == null) {
            // No matching resource found.
            String msg = "Could not find matching resource for " + requestPath;
            log.error(msg);
            throw new ResourceNotFoundException(msg);
        }
        resourceString = selectedResource.getDispatcherHelper().getString();
        resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
        if (log.isDebugEnabled()) {
            log.debug("Selected Resource: " + resourceString);
        }
        // Set the elected resource
        synCtx.setProperty(APIConstants.API_ELECTED_RESOURCE, resourceString);
        if (isGatewayAPIResourceValidationEnabled) {
            VerbInfoDTO verbInfo;
            verbInfo = (VerbInfoDTO) getResourceCache().get(resourceCacheKey);
            // Cache hit
            if (verbInfo != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Got Resource from cache for key: " + resourceCacheKey);
                }
                verbInfoList.add(verbInfo);
                return verbInfoList;
            } else if (log.isDebugEnabled()) {
                log.debug("Cache miss for Resource for key: " + resourceCacheKey);
            }
        }
    }
    String apiCacheKey = APIUtil.getAPIInfoDTOCacheKey(apiContext, apiVersion);
    APIInfoDTO apiInfoDTO = null;
    if (isGatewayAPIResourceValidationEnabled) {
        apiInfoDTO = (APIInfoDTO) getResourceCache().get(apiCacheKey);
    }
    // Cache miss
    if (apiInfoDTO == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find API object in cache for key: " + apiCacheKey);
        }
        String apiType = (String) synCtx.getProperty(APIMgtGatewayConstants.API_TYPE);
        if (APIConstants.ApiTypes.PRODUCT_API.name().equalsIgnoreCase(apiType)) {
            apiInfoDTO = doGetAPIProductInfo(synCtx, apiContext, apiVersion);
        } else {
            apiInfoDTO = doGetAPIInfo(synCtx, apiContext, apiVersion);
        }
        if (isGatewayAPIResourceValidationEnabled) {
            getResourceCache().put(apiCacheKey, apiInfoDTO);
        }
    }
    if (apiInfoDTO.getResources() != null) {
        for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
            Set<VerbInfoDTO> verbDTOList = resourceInfoDTO.getHttpVerbs();
            for (VerbInfoDTO verb : verbDTOList) {
                if (verb.getHttpVerb().equals(httpMethod)) {
                    for (String resourceString : resourceArray) {
                        if (isResourcePathMatching(resourceString, resourceInfoDTO)) {
                            resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
                            verb.setRequestKey(resourceCacheKey);
                            verbInfoList.add(verb);
                            if (isGatewayAPIResourceValidationEnabled) {
                                // Set cache key in the message c\ontext so that it can be used by the subsequent handlers.
                                if (log.isDebugEnabled()) {
                                    log.debug("Putting resource object in cache with key: " + resourceCacheKey);
                                }
                                getResourceCache().put(resourceCacheKey, verb);
                                synCtx.setProperty(APIConstants.API_RESOURCE_CACHE_KEY, resourceCacheKey);
                            }
                        }
                    }
                }
            }
        }
    }
    if (verbInfoList.size() == 0) {
        verbInfoList = null;
    }
    return verbInfoList;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) Resource(org.apache.synapse.api.Resource) RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) API(org.apache.synapse.api.API) APIInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIInfoDTO) ResourceInfoDTO(org.wso2.carbon.apimgt.impl.dto.ResourceInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

API (org.apache.synapse.api.API)64 MessageContext (org.apache.synapse.MessageContext)33 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)33 Resource (org.apache.synapse.api.Resource)23 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)14 OMElement (org.apache.axiom.om.OMElement)10 URLMappingHelper (org.apache.synapse.api.dispatch.URLMappingHelper)7 Test (org.junit.Test)6 URITemplateHelper (org.apache.synapse.api.dispatch.URITemplateHelper)5 Cache (javax.cache.Cache)4 DeploymentException (org.apache.axis2.deployment.DeploymentException)4 SynapseException (org.apache.synapse.SynapseException)4 ContextVersionStrategy (org.apache.synapse.api.version.ContextVersionStrategy)4 ProxyService (org.apache.synapse.core.axis2.ProxyService)4 InboundEndpoint (org.apache.synapse.inbound.InboundEndpoint)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)4 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)4 CacheProvider (org.wso2.carbon.apimgt.impl.caching.CacheProvider)4 ArrayList (java.util.ArrayList)3