Search in sources :

Example 36 with API

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

the class CORSRequestHandler method handleRequest.

@MethodStats
public boolean handleRequest(MessageContext messageContext) {
    Timer.Context context = startMetricTimer();
    TracingSpan CORSRequestHandlerSpan = null;
    if (Util.tracingEnabled()) {
        TracingSpan responseLatencySpan = (TracingSpan) messageContext.getProperty(APIMgtGatewayConstants.RESOURCE_SPAN);
        TracingTracer tracer = Util.getGlobalTracer();
        CORSRequestHandlerSpan = Util.startSpan(APIMgtGatewayConstants.CORS_REQUEST_HANDLER, responseLatencySpan, tracer);
    }
    if (Utils.isGraphQLSubscriptionRequest(messageContext)) {
        if (log.isDebugEnabled()) {
            log.debug("Skipping GraphQL subscription handshake request.");
        }
        return true;
    }
    try {
        if (!initializeHeaderValues) {
            initializeHeaders();
        }
        String apiContext = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
        String apiVersion = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
        String httpMethod = (String) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
        API selectedApi = Utils.getSelectedAPI(messageContext);
        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
        Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        String corsRequestMethod = (String) headers.get(APIConstants.CORSHeaders.ACCESS_CONTROL_REQUEST_METHOD);
        Resource selectedResource = null;
        Utils.setSubRequestPath(selectedApi, messageContext);
        if (selectedApi != null) {
            Resource[] allAPIResources = selectedApi.getResources();
            Set<Resource> acceptableResources = new LinkedHashSet<>();
            for (Resource resource : allAPIResources) {
                // 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(corsRequestMethod)) || (resource.getMethods() != null && Arrays.asList(resource.getMethods()).contains(httpMethod))) {
                    acceptableResources.add(resource);
                }
            }
            if (!acceptableResources.isEmpty()) {
                for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
                    Resource resource = dispatcher.findResource(messageContext, acceptableResources);
                    if (resource != null) {
                        selectedResource = resource;
                        break;
                    }
                }
                if (selectedResource == null) {
                    handleResourceNotFound(messageContext, Arrays.asList(allAPIResources));
                    return false;
                }
            } else // If no acceptable resources are found
            {
                // We're going to send a 405 or a 404. Run the following logic to determine which.
                handleResourceNotFound(messageContext, Arrays.asList(allAPIResources));
                return false;
            }
            // No matching resource found
            if (selectedResource == null) {
                // Respond with a 404
                onResourceNotFoundError(messageContext, HttpStatus.SC_NOT_FOUND, APIMgtGatewayConstants.RESOURCE_NOT_FOUND_ERROR_MSG);
                return false;
            }
        }
        String resourceString = selectedResource.getDispatcherHelper().getString();
        String resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
        messageContext.setProperty(APIConstants.API_ELECTED_RESOURCE, resourceString);
        messageContext.setProperty(APIConstants.API_RESOURCE_CACHE_KEY, resourceCacheKey);
        messageContext.setProperty(APIConstants.REST_METHOD, httpMethod);
        // If this is an OPTIONS request
        if (APIConstants.SupportedHTTPVerbs.OPTIONS.name().equalsIgnoreCase(httpMethod)) {
            // If the OPTIONS method is explicity specified in the resource
            if (Arrays.asList(selectedResource.getMethods()).contains(APIConstants.SupportedHTTPVerbs.OPTIONS.name())) {
                // We will not handle the CORS headers, let the back-end do it.
                return true;
            }
            setCORSHeaders(messageContext, selectedResource);
            Mediator corsSequence = messageContext.getSequence(APIConstants.CORS_SEQUENCE_NAME);
            if (corsSequence != null) {
                corsSequence.mediate(messageContext);
            }
            Utils.send(messageContext, HttpStatus.SC_OK);
            return false;
        } else if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(apiImplementationType)) {
            setCORSHeaders(messageContext, selectedResource);
            messageContext.getSequence(APIConstants.CORS_SEQUENCE_NAME).mediate(messageContext);
        }
        setCORSHeaders(messageContext, selectedResource);
        return true;
    } catch (Exception e) {
        if (Util.tracingEnabled() && CORSRequestHandlerSpan != null) {
            Util.setTag(CORSRequestHandlerSpan, APIMgtGatewayConstants.ERROR, APIMgtGatewayConstants.CORS_REQUEST_HANDLER_ERROR);
        }
        throw e;
    } finally {
        stopMetricTimer(context);
        if (Util.tracingEnabled()) {
            Util.finishSpan(CORSRequestHandlerSpan);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TracingTracer(org.wso2.carbon.apimgt.tracing.TracingTracer) Resource(org.apache.synapse.api.Resource) RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) Timer(org.wso2.carbon.metrics.manager.Timer) API(org.apache.synapse.api.API) Mediator(org.apache.synapse.Mediator) TracingSpan(org.wso2.carbon.apimgt.tracing.TracingSpan) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 37 with API

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

the class Utils method getSelectedAPIList.

public static TreeMap<String, org.wso2.carbon.apimgt.keymgt.model.entity.API> getSelectedAPIList(String path, String tenantDomain) {
    TreeMap<String, org.wso2.carbon.apimgt.keymgt.model.entity.API> selectedAPIMap = new TreeMap<>(new ContextLengthSorter());
    SubscriptionDataStore tenantSubscriptionStore = SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
    if (tenantSubscriptionStore != null) {
        Map<String, org.wso2.carbon.apimgt.keymgt.model.entity.API> contextAPIMap = tenantSubscriptionStore.getAllAPIsByContextList();
        if (contextAPIMap != null) {
            contextAPIMap.forEach((context, api) -> {
                if (ApiUtils.matchApiPath(path, context)) {
                    selectedAPIMap.put(context, api);
                }
            });
        }
    }
    return selectedAPIMap;
}
Also used : API(org.apache.synapse.api.API) SubscriptionDataStore(org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore)

Example 38 with API

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

the class SynapseXMLConfigurationFactory method defineAPI.

public static API defineAPI(SynapseConfiguration config, OMElement elem, Properties properties) {
    API api = null;
    try {
        api = APIFactory.createAPI(elem, properties);
        config.addAPI(api.getName(), api);
    } catch (Exception e) {
        String msg = "API configuration cannot be built";
        handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_API, msg, e);
    }
    return api;
}
Also used : API(org.apache.synapse.api.API) SynapseException(org.apache.synapse.SynapseException)

Example 39 with API

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

the class SynapseXMLConfigurationFactory method defineAPI.

/**
 * Add api with the option of re-ordering the api collection based on the context
 *
 * @param config SynapseConfiguration
 * @param elem OMElement element
 * @param properties Properties
 * @param reOrder reorder the deployment order based on the context
 * @return API api object
 */
public static API defineAPI(SynapseConfiguration config, OMElement elem, Properties properties, boolean reOrder) {
    API api = null;
    try {
        api = APIFactory.createAPI(elem, properties);
        config.addAPI(api.getName(), api, reOrder);
    } catch (Exception e) {
        String msg = "API configuration cannot be built";
        handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_API, msg, e);
    }
    return api;
}
Also used : API(org.apache.synapse.api.API) SynapseException(org.apache.synapse.SynapseException)

Example 40 with API

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

the class SynapseXMLConfigurationSerializer method serializeAPIs.

private static void serializeAPIs(OMElement definitions, Collection<API> apiSet) {
    for (API api : apiSet) {
        OMElement apiElt = APISerializer.serializeAPI(api);
        definitions.addChild(apiElt);
    }
}
Also used : API(org.apache.synapse.api.API)

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