use of org.apache.synapse.api.Resource 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;
}
use of org.apache.synapse.api.Resource 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);
}
}
}
use of org.apache.synapse.api.Resource in project wso2-synapse by wso2.
the class URITemplateBasedDispatcher method findResource.
public Resource findResource(MessageContext synCtx, Collection<Resource> resources) {
String url = ApiUtils.getSubRequestPath(synCtx);
for (Resource r : resources) {
DispatcherHelper helper = r.getDispatcherHelper();
if (helper instanceof URITemplateHelper) {
URITemplateHelper templateHelper = (URITemplateHelper) helper;
Map<String, String> variables = new HashMap<String, String>();
if (templateHelper.getUriTemplate().matches(url, variables)) {
for (Map.Entry<String, String> entry : variables.entrySet()) {
synCtx.setProperty(RESTConstants.REST_URI_VARIABLE_PREFIX + entry.getKey(), entry.getValue());
}
return r;
}
}
}
return null;
}
use of org.apache.synapse.api.Resource in project wso2-synapse by wso2.
the class URLMappingBasedDispatcher method findResource.
public Resource findResource(MessageContext synCtx, Collection<Resource> resources) {
List<URLMappingHelper> mappings = new ArrayList<URLMappingHelper>();
List<Resource> filteredResources = new ArrayList<Resource>();
for (Resource r : resources) {
DispatcherHelper helper = r.getDispatcherHelper();
if (helper instanceof URLMappingHelper) {
mappings.add((URLMappingHelper) helper);
filteredResources.add(r);
}
}
int count = filteredResources.size();
if (count == 0) {
return null;
}
String url = ApiUtils.getSubRequestPath(synCtx);
for (int i = 0; i < count; i++) {
if (mappings.get(i).isExactMatch(url)) {
if (log.isDebugEnabled()) {
log.debug("Found exact URL match for: " + url);
}
return filteredResources.get(i);
}
}
int maxLength = 0;
Resource matchedResource = null;
for (int i = 0; i < count; i++) {
int length = mappings.get(i).getPrefixMatchingLength(url);
if (length > maxLength) {
maxLength = length;
matchedResource = filteredResources.get(i);
}
}
if (matchedResource != null) {
if (log.isDebugEnabled()) {
log.debug("Found path match for: " + url + " with matching length: " + maxLength);
}
return matchedResource;
}
for (int i = 0; i < count; i++) {
if (mappings.get(i).isExtensionMatch(url)) {
if (log.isDebugEnabled()) {
log.debug("Found extension match for: " + url);
}
return filteredResources.get(i);
}
}
return null;
}
use of org.apache.synapse.api.Resource in project wso2-synapse by wso2.
the class APIDebugUtil method registerAPISequenceMediationFlowSkip.
/**
* Registers/Un-registers a skip, point where mediator disables from the mediation flow
*
* @param synCfg Synapse configuration
* @param mapping either resource url-mapping or uri-template
* @param method resource http method
* @param seqType Synapse sequence type
* @param apiKey name of the API
* @param position array of integers that uniquely specifies a point in mediation route
* @param registerMode specify whether register or un register
*/
public static void registerAPISequenceMediationFlowSkip(SynapseConfiguration synCfg, String mapping, String method, String seqType, String apiKey, int[] position, boolean registerMode) {
SynapseSequenceType synapseSequenceType = SynapseSequenceType.valueOf(seqType.toUpperCase());
APIMediationFlowPoint skipPoint = new APIMediationFlowPoint();
skipPoint.setSynapseMediationComponent(SynapseMediationComponent.SEQUENCE);
skipPoint.setKey(apiKey);
skipPoint.setMediatorPosition(position);
skipPoint.setSynapseSequenceType(synapseSequenceType);
skipPoint.setSequenceBaseType(SynapseDebugCommandConstants.DEBUG_COMMAND_MEDIATION_COMPONENT_SEQUENCE_API);
skipPoint.setResourceMapping(mapping);
skipPoint.setResourceHTTPMethod(method);
Mediator seqMediator = null;
Resource api_resource = null;
API api = synCfg.getAPI(apiKey);
if (api == null) {
if (log.isDebugEnabled()) {
log.debug("Non existing API for the key " + skipPoint.getKey());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_API_NOT_FOUND).toString());
return;
}
Resource[] resource_array = api.getResources();
for (int counter = 0; counter < resource_array.length; counter++) {
if (resource_array[counter].getDispatcherHelper() != null && mapping != null) {
if (mapping.equals(resource_array[counter].getDispatcherHelper().getString())) {
for (String m1 : resource_array[counter].getMethods()) {
if (m1.equals(method)) {
api_resource = resource_array[counter];
break;
}
}
if (api_resource != null) {
break;
}
}
} else if (resource_array[counter].getDispatcherHelper() == null && mapping == null) {
for (String m1 : resource_array[counter].getMethods()) {
if (m1.equals(method)) {
api_resource = resource_array[counter];
break;
}
}
if (api_resource != null) {
break;
}
}
}
if (api_resource != null) {
if (synapseSequenceType.equals(SynapseSequenceType.API_INSEQ)) {
seqMediator = api_resource.getInSequence();
} else if (synapseSequenceType.equals(SynapseSequenceType.API_OUTSEQ)) {
seqMediator = api_resource.getOutSequence();
} else if (synapseSequenceType.equals(SynapseSequenceType.API_FAULTSEQ)) {
seqMediator = api_resource.getFaultSequence();
}
} else {
if (log.isDebugEnabled()) {
log.debug("Resource not found for the API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_API_RESOURCE_NOT_FOUND).toString());
return;
}
if (seqMediator != null) {
Mediator current_mediator = null;
current_mediator = MediatorTreeTraverseUtil.getMediatorReference(synCfg, seqMediator, position);
if (current_mediator != null) {
skipPoint.setMediatorReference(current_mediator);
if (registerMode) {
if (!((AbstractMediator) current_mediator).isSkipEnabled()) {
((AbstractMediator) current_mediator).setSkipEnabled(true);
((AbstractMediator) current_mediator).registerMediationFlowPoint(skipPoint);
if (log.isDebugEnabled()) {
log.debug("Registered skip at mediator position " + logMediatorPosition(skipPoint) + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod() + " sequence type " + skipPoint.getSynapseSequenceType().toString());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(true, null).toString());
} else {
if (log.isDebugEnabled()) {
log.debug("Failed register skip. Already skip enabled at mediator position " + logMediatorPosition(skipPoint) + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod() + " sequence type " + skipPoint.getSynapseSequenceType().toString());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_ALREADY_SKIP_ENABLED).toString());
}
} else {
if (((AbstractMediator) current_mediator).isSkipEnabled()) {
((AbstractMediator) current_mediator).unregisterMediationFlowPoint();
((AbstractMediator) current_mediator).setSkipEnabled(false);
if (log.isDebugEnabled()) {
log.debug("Unregistered skip at mediator position " + logMediatorPosition(skipPoint) + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod() + " sequence type " + skipPoint.getSynapseSequenceType().toString());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(true, null).toString());
} else {
if (log.isDebugEnabled()) {
log.debug("Failed unregister skip. Already skip disabled at mediator position " + logMediatorPosition(skipPoint) + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod() + " sequence type " + skipPoint.getSynapseSequenceType().toString());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_ALREADY_SKIP_DISABLED).toString());
}
}
} else {
if (registerMode) {
if (log.isDebugEnabled()) {
log.debug("Failed register skip. Non existing mediator position at " + logMediatorPosition(skipPoint) + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod() + " sequence type " + skipPoint.getSynapseSequenceType().toString());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_NON_EXISTING_MEDIATOR_POSITION).toString());
} else {
if (log.isDebugEnabled()) {
log.debug("Failed unregister skip. Non existing mediator position at " + logMediatorPosition(skipPoint) + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod() + " sequence type " + skipPoint.getSynapseSequenceType().toString());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_NON_EXISTING_MEDIATOR_POSITION).toString());
}
}
} else {
if (registerMode) {
if (log.isDebugEnabled()) {
log.debug("Failed register skip. Non existing sequence " + skipPoint.getSynapseSequenceType().toString() + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_NON_EXISTING_SEQUENCE).toString());
} else {
if (log.isDebugEnabled()) {
log.debug("Failed unregister skip. Non existing sequence " + skipPoint.getSynapseSequenceType().toString() + " for API key " + skipPoint.getKey() + " resource mapping " + skipPoint.getResourceMapping() + " resource HTTP method " + skipPoint.getResourceHTTPMethod());
}
debugManager.advertiseCommandResponse(debugManager.createDebugCommandResponse(false, SynapseDebugCommandConstants.DEBUG_COMMAND_RESPONSE_NON_EXISTING_SEQUENCE).toString());
}
}
}
Aggregations