Search in sources :

Example 6 with VerbInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO 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 7 with VerbInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgent method run.

public void run() {
    JSONObject jsonObMap = new JSONObject();
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    if (ipAddress != null && ipAddress.length() > 0) {
        if (ipAddress.contains(":") && ipAddress.split(":").length == 2) {
            log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + ipAddress);
            ipAddress = ipAddress.split(":")[0];
        }
        try {
            InetAddress address = APIUtil.getAddress(ipAddress);
            if (address instanceof Inet4Address) {
                jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(ipAddress));
                jsonObMap.put(APIThrottleConstants.IPv6, 0);
            } else if (address instanceof Inet6Address) {
                jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(ipAddress));
                jsonObMap.put(APIThrottleConstants.IP, 0);
            }
        } catch (UnknownHostException e) {
            // send empty value as ip
            log.error("Error while parsing host IP " + ipAddress, e);
            jsonObMap.put(APIThrottleConstants.IPv6, 0);
            jsonObMap.put(APIThrottleConstants.IP, 0);
        }
    }
    // HeaderMap will only be set if the Header Publishing has been enabled.
    if (getThrottleProperties().isEnableHeaderConditions()) {
        if (this.headersMap != null) {
            jsonObMap.putAll(this.headersMap);
        }
    }
    // adding any custom property if available to stream's property map
    if (this.customPropertyMap != null) {
        jsonObMap.putAll(this.customPropertyMap);
    }
    // Setting query parameters
    if (getThrottleProperties().isEnableQueryParamConditions()) {
        Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext);
        if (queryParams != null) {
            jsonObMap.putAll(queryParams);
        }
    }
    // Publish jwt claims
    if (getThrottleProperties().isEnableJwtConditions()) {
        if (authenticationContext.getCallerToken() != null) {
            Map<String, String> assertions = JWTUtil.getJWTClaims(authenticationContext.getCallerToken());
            if (assertions != null) {
                jsonObMap.putAll(assertions);
            }
        }
    }
    // this parameter will be used to capture message size and pass it to calculation logic
    ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
    boolean isVerbInfoContentAware = false;
    if (list != null && !list.isEmpty()) {
        VerbInfoDTO verbInfoDTO = list.get(0);
        isVerbInfoContentAware = verbInfoDTO.isContentAware();
    }
    if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
        if (log.isDebugEnabled()) {
            log.debug("Message size: " + messageSizeInBytes + "B");
        }
        jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes);
        if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) {
            jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName());
        }
        if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils.isEmpty(authenticationContext.getProductProvider())) {
            jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE);
        } else {
            jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE);
        }
    }
    Object[] objects = new Object[] { messageContext.getMessageID(), this.applicationLevelThrottleKey, this.applicationLevelTier, this.apiLevelThrottleKey, this.apiLevelTier, this.subscriptionLevelThrottleKey, this.subscriptionLevelTier, this.resourceLevelThrottleKey, this.resourceLevelTier, this.authorizedUser, this.apiContext, this.apiVersion, this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID, System.currentTimeMillis(), null, null, objects);
    dataPublisher.tryPublish(event);
}
Also used : Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) Inet6Address(java.net.Inet6Address) JSONObject(org.json.simple.JSONObject) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) JSONObject(org.json.simple.JSONObject) InetAddress(java.net.InetAddress) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 8 with VerbInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgent method setDataReference.

/**
 * This method will use to set message context.
 */
public void setDataReference(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) {
    if (!StringUtils.isEmpty(apiLevelTier)) {
        resourceLevelTier = apiLevelTier;
        resourceLevelThrottleKey = apiLevelThrottleKey;
    }
    this.authenticationContext = authenticationContext;
    this.messageContext = messageContext;
    this.applicationLevelThrottleKey = applicationLevelThrottleKey;
    this.applicationLevelTier = applicationLevelTier;
    this.apiLevelThrottleKey = apiLevelThrottleKey;
    this.subscriptionLevelThrottleKey = subscriptionLevelThrottleKey;
    this.subscriptionLevelTier = subscriptionLevelTier;
    this.resourceLevelThrottleKey = resourceLevelThrottleKey;
    this.resourceLevelTier = resourceLevelTier;
    this.authorizedUser = authorizedUser;
    this.apiContext = apiContext;
    this.apiVersion = apiVersion;
    this.appTenant = appTenant;
    this.apiTenant = apiTenant;
    this.appId = appId;
    this.apiName = GatewayUtils.getAPINameFromContextAndVersion(messageContext);
    this.messageSizeInBytes = 0;
    ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
    boolean isVerbInfoContentAware = false;
    if (list != null && !list.isEmpty()) {
        VerbInfoDTO verbInfoDTO = list.get(0);
        isVerbInfoContentAware = verbInfoDTO.isContentAware();
    }
    // Build the message if needed from here since it cannot be done from the run() method because content
    // in axis2MessageContext is modified.
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map<String, String> transportHeaderMap = (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    if (transportHeaderMap != null) {
        this.headersMap = new HashMap<>(transportHeaderMap);
    }
    if (messageContext.getProperty(APIThrottleConstants.CUSTOM_PROPERTY) != null) {
        HashMap<String, Object> propertyFromMsgCtx = (HashMap<String, Object>) messageContext.getProperty(APIThrottleConstants.CUSTOM_PROPERTY);
        if (propertyFromMsgCtx != null) {
            this.customPropertyMap = (Map<String, Object>) propertyFromMsgCtx.clone();
        }
    }
    this.ipAddress = GatewayUtils.getIp(axis2MessageContext);
    if (log.isDebugEnabled()) {
        log.debug("Remote IP address : " + ipAddress);
    }
    if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
        Object contentLength = transportHeaderMap.get(APIThrottleConstants.CONTENT_LENGTH);
        if (contentLength != null) {
            log.debug("Content lenght found in the request. Using it as the message size..");
            messageSizeInBytes = Long.parseLong(contentLength.toString());
        } else {
            log.debug("Building the message to get the message size..");
            try {
                buildMessage(axis2MessageContext);
            } catch (Exception ex) {
                // In case of any exception, it won't be propagated up,and set response size to 0
                log.error("Error occurred while building the message to" + " calculate the response body size", ex);
            }
            SOAPEnvelope env = messageContext.getEnvelope();
            if (env != null) {
                SOAPBody soapbody = env.getBody();
                if (soapbody != null) {
                    byte[] size = soapbody.toString().getBytes(Charset.defaultCharset());
                    messageSizeInBytes = size.length;
                }
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SOAPBody(org.apache.axiom.soap.SOAPBody) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 9 with VerbInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.

the class ThrottleHandlerTest method testMsgDoThrottleWhenUserLevelThrottlingIsTriggerred.

@Test
public void testMsgDoThrottleWhenUserLevelThrottlingIsTriggerred() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    verbInfo.setApplicableLevel("userLevel");
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    // Should continue the message flow, when user level throttling is triggered and not exceeded
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
Also used : ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 10 with VerbInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.

the class ThrottleHandlerTest method testMsgContinueWhenSubscriptionLevelIsThrottledAndStopOnQuotaReachIsDisabled.

@Test
public void testMsgContinueWhenSubscriptionLevelIsThrottledAndStopOnQuotaReachIsDisabled() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    // Set stopOnQuota
    authenticationContext.setStopOnQuotaReach(false);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    matchingConditions.add(conditionGroupDTO);
    String subscriptionLevelThrottleKey = authenticationContext.getApplicationId() + ":" + apiContext + ":" + apiVersion;
    // Set subscription level throttled out
    throttleDataHolder.addThrottleData(subscriptionLevelThrottleKey, System.currentTimeMillis() + 10000);
    // Though subscription level is throttled out, should continue the message flow, if stop on quota reach is
    // disabled
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
Also used : ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ArrayList(java.util.ArrayList) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)51 Test (org.junit.Test)47 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)41 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)37 MessageContext (org.apache.synapse.MessageContext)34 ArrayList (java.util.ArrayList)33 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)15 ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)14 InboundProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO)13 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)12 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)12 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)11 TreeMap (java.util.TreeMap)8 GraphQLProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.GraphQLProcessorResponseDTO)7 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)7 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)7 GraphQLOperationDTO (org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO)6 GraphQLSchema (graphql.schema.GraphQLSchema)5 SchemaParser (graphql.schema.idl.SchemaParser)5