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);
}
}
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);
}
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;
}
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);
}
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));
}
Aggregations