org.apache.synapse.core.axis2.Axis2MessageContext Java Examples

The following examples show how to use org.apache.synapse.core.axis2.Axis2MessageContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TemplateResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean invoke(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axis2MessageContext =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    SynapseConfiguration synapseConfiguration = messageContext.getConfiguration();
    if (Objects.isNull(axis2MessageContext) || Objects.isNull(synapseConfiguration)) {
        return false;
    }

    String templateTypeParam = Utils.getQueryParameter(messageContext, TEMPLATE_TYPE_PARAM);
    if (Objects.nonNull(templateTypeParam)) {
        String templateNameParam = Utils.getQueryParameter(messageContext, TEMPLATE_NAME_PARAM);
        if (Objects.nonNull(templateNameParam)) {
            populateTemplateData(messageContext, templateNameParam, templateTypeParam);
        } else {
            populateTemplateListByType(messageContext, templateTypeParam);
        }
    } else {
        populateFullTemplateList(axis2MessageContext, synapseConfiguration);
    }
    axis2MessageContext.removeProperty(Constants.NO_ENTITY_BODY);
    return true;
}
 
Example #2
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
    public void testMsgThrottleOutWhenBlockingConditionsAreSatisfied() {
        ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

        ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);

        MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
        ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
                .MessageContext.TRANSPORT_HEADERS);
        throttleDataHolder.addIpBlockingCondition("carbon.super", 1, "{\"fixedIp\":\"127.0.0.1\",\"invert\":false}",
                APIConstants.BLOCKING_CONDITIONS_IP);
        AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
                (API_AUTH_CONTEXT);
//        Mockito.when(throttleDataHolder.isRequestBlocked(apiContext, authenticationContext
//                .getSubscriber() + ":" + authenticationContext.getApplicationName(), authenticationContext
//                .getUsername(), "carbon.super" + ":" + "127.0.0.1")).thenReturn(true);
        Assert.assertFalse(throttleHandler.handleRequest(messageContext));
        throttleDataHolder.removeIpBlockingCondition("carbon.super", 1);
        Assert.assertTrue(throttleHandler.handleRequest(messageContext));
    }
 
Example #3
Source File: RegularExpressionProtector.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks whether the request path contains matching vulnerable keywords.
 *
 * @param messageContext contains the message properties of the relevant API request which was
 *                       enabled the regexValidator message mediation in flow.
 * @return true if request Headers contain matching vulnerable keywords
 */
private boolean isRequestHeadersVulnerable(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext)
            messageContext).getAxis2MessageContext();
    if (enabledCheckHeaders) {
        Map transportHeaders = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (pattern != null && transportHeaders != null && pattern.matcher(transportHeaders.toString()).find()) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Threat detected in Transport headers [ %s ] by regex [ %s ]",
                        transportHeaders, pattern));
            }
            GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE,
                    threatType + " " + APIMgtGatewayConstants.HTTP_HEADER_THREAT_MSG);
            return true;
        }
    }
    return false;
}
 
Example #4
Source File: DataProcessAndPublishingAgentTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void setDataReferenceWithHeaderConditionEnable() throws Exception {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnabled(true);
    throttleProperties.setEnableHeaderConditions(true);
    DataProcessAndPublishingAgent dataProcessAndPublishingAgent = new DataProcessAndPublishingAgentWrapper
            (throttleProperties);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext
            .class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--PizzaShackAPI");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS))
            .thenReturn(new TreeMap<>());
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setContentAware(false);
    ArrayList<VerbInfoDTO> list = new ArrayList<VerbInfoDTO>();
    list.add(verbInfoDTO);
    Mockito.when(messageContext.getProperty(APIConstants.VERB_INFO_DTO)).thenReturn(list);
    dataProcessAndPublishingAgent.setDataReference(applicationLevelThrottleKey, applicationLevelTier,
            apiLevelThrottleKey, null, subscriptionLevelThrottleKey, subscriptionLevelTier,
            resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant,
            apiTenant, appId, messageContext, authenticationContext);
    dataProcessAndPublishingAgent.run();
}
 
Example #5
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static void sendFault(MessageContext messageContext, int status) {
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
            getAxis2MessageContext();

    axis2MC.setProperty(NhttpConstants.HTTP_SC, status);
    messageContext.setResponse(true);
    messageContext.setProperty("RESPONSE", "true");
    messageContext.setTo(null);        
    axis2MC.removeProperty("NO_ENTITY_BODY");

    // Always remove the ContentType - Let the formatter do its thing
    axis2MC.removeProperty(Constants.Configuration.CONTENT_TYPE);
    Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    if (headers != null) {
        headers.remove(HttpHeaders.AUTHORIZATION);

        headers.remove(HttpHeaders.HOST);
    }
    Axis2Sender.sendBack(messageContext);
}
 
Example #6
Source File: DataServiceResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private void populateDataServiceList(MessageContext msgCtx) throws Exception {
    SynapseConfiguration configuration = msgCtx.getConfiguration();
    AxisConfiguration axisConfiguration = configuration.getAxisConfiguration();
    String[] dataServicesNames = DBUtils.getAvailableDS(axisConfiguration);

    // initiate list model
    DataServicesList dataServicesList = new DataServicesList(dataServicesNames.length);

    for (String dataServiceName : dataServicesNames) {
        DataService dataService = getDataServiceByName(msgCtx, dataServiceName);
        ServiceMetaData serviceMetaData = getServiceMetaData(dataService);
        // initiate summary model
        DataServiceSummary summary = null;
        if (serviceMetaData != null) {
            summary = new DataServiceSummary(serviceMetaData.getName(), serviceMetaData.getWsdlURLs());
        }
        dataServicesList.addServiceSummary(summary);
    }

    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) msgCtx)
            .getAxis2MessageContext();

    String stringPayload = new Gson().toJson(dataServicesList);
    Utils.setJsonPayLoad(axis2MessageContext, new JSONObject(stringPayload));
}
 
Example #7
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test(expected = SynapseException.class)
public void testMsgFailWhenUnsupportedThrottleTypeProvided() throws XMLStreamException,
        ThrottleException {
    //Set concurrency count to be 100
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "INVALID", IP, 0, 60000,
            "true"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    apiThrottleHandler.handleRequest(messageContext);
}
 
Example #8
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetThrottledInConditionWithHeaderConditionInvert() {

    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnableHeaderConditions(true);
    ServiceReferenceHolder.getInstance().setThrottleProperties(throttleProperties);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    Map map = new TreeMap();
    map.put("abc", "cde");
    map.put("bcd", "xyz");
    ((Axis2MessageContext) messageContext).getAxis2MessageContext()
            .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, map);
    Map<String, List<ConditionDto>> conditionMap = new HashMap<>();
    conditionMap.put("condition1", Arrays.asList(new ConditionDto[]{getHeaderCondition(true)}));
    conditionMap.put("default", Arrays.asList(new ConditionDto[]{getHeaderCondition(true)}));
    String condition = throttleConditionEvaluator.getThrottledInCondition(messageContext, null, conditionMap);
    Assert.assertEquals(condition, "default");
}
 
Example #9
Source File: InboundEndpointResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean invoke(MessageContext messageContext) {

    buildMessage(messageContext);

    org.apache.axis2.context.MessageContext axis2MessageContext =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();

    String param = Utils.getQueryParameter(messageContext, "inboundEndpointName");

    if (Objects.nonNull(param)) {
        populateInboundEndpointData(messageContext, param);
    } else {
        populateInboundEndpointList(messageContext);
    }

    axis2MessageContext.removeProperty(Constants.NO_ENTITY_BODY);
    return true;
}
 
Example #10
Source File: SynapsePropertiesHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void handleRequest() throws Exception {
    SynapseConfiguration synCfg = new SynapseConfiguration();
    org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
    AxisConfiguration axisConfig = new AxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
    MessageContext synCtx = new Axis2MessageContext(axisMsgCtx, synCfg,
            new Axis2SynapseEnvironment(cfgCtx, synCfg));
    System.setProperty("http.nio.port","8280");
    System.setProperty("https.nio.port","8243");
    System.setProperty(APIConstants.KEYMANAGER_PORT,"9443");
    System.setProperty(APIConstants.KEYMANAGER_HOSTNAME,"api.wso2.com");
    SynapsePropertiesHandler synapsePropertiesHandler = new SynapsePropertiesHandler();
    synapsePropertiesHandler.handleRequest(synCtx);
    Assert.assertEquals(synCtx.getProperty("http.nio.port"),"8280");
    Assert.assertEquals(synCtx.getProperty("https.nio.port"),"8243");
    Assert.assertEquals(synCtx.getProperty("keyManager.port"),"9443");
    Assert.assertEquals(synCtx.getProperty("keyManager.hostname"),"api.wso2.com");

}
 
Example #11
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplicabilityOfNonMatchingQueryParameterTypeCondition() {

    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("QueryParameterTypeConditionGroup");
    ConditionDTO invertedCondition = new ConditionDTO();
    invertedCondition.setConditionType("QueryParameterType");
    invertedCondition.setConditionName("city");
    invertedCondition.setConditionValue("mountain-view");

    ConditionDTO[] conditionDTOS = {invertedCondition};
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = {conditionGroupDTO};

    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REST_URL_POSTFIX",
            "/temperature?city=colombo");
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions
            (messageContext, new AuthenticationContext(), conditionGroupDTOS);
    Assert.assertNull(matchingConditionGroups.get(0));
}
 
Example #12
Source File: InboundWebsocketSourceHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
protected void handleWebsocketBinaryFrame(WebSocketFrame frame, MessageContext synCtx) throws AxisFault {
    String endpointName = WebsocketEndpointManager.getInstance().getEndpointName(port, tenantDomain);

    InboundEndpoint endpoint = synCtx.getConfiguration().getInboundEndpoint(endpointName);

    if (endpoint == null) {
        log.error("Cannot find deployed inbound endpoint " + endpointName + "for process request");
        return;
    }

    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_BINARY_FRAME_PRESENT, new Boolean(true));
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundWebsocketConstants.WEBSOCKET_BINARY_FRAME_PRESENT, new Boolean(true));
    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_BINARY_FRAME, frame);
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundWebsocketConstants.WEBSOCKET_BINARY_FRAME, frame);

}
 
Example #13
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgFailWhenResourceThrottlingInfoNotAvaialable() throws XMLStreamException,
        ThrottleException {
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Gold", 20, 60000,
            "true"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Gold", 20, 60000,
            "true"),THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    ThrottleConfiguration throttleConfiguration = Mockito.mock(ThrottleConfiguration.class);
    Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
    //Throttling limits won't apply, since the auth context is not available (verbInfoDTO = null)
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #14
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * @param to     get an endpoint to send the information
 * @param member The member to which an EP has to be created
 * @param synCtx synapse context
 * @return the created endpoint
 */
private Endpoint getEndpoint(EndpointReference to, org.apache.axis2.clustering.Member member, MessageContext synCtx) {
    AddressEndpoint endpoint = new AddressEndpoint();
    endpoint.setEnableMBeanStats(false);
    endpoint.setName("DLB:" + member.getHostName() +
            ":" + member.getPort() + ":" + UUID.randomUUID());

    EndpointDefinition definition = new EndpointDefinition();
    definition.setTimeoutAction(SynapseConstants.DISCARD_AND_FAULT);
    definition.setTimeoutDuration(LoadBalancerConfiguration.getInstance().getEndpointTimeout());
    definition.setReplicationDisabled(true);
    definition.setAddress(to.getAddress());

    endpoint.setDefinition(definition);
    endpoint.init((SynapseEnvironment)
            ((Axis2MessageContext) synCtx).getAxis2MessageContext().
                    getConfigurationContext().getAxisConfiguration().
                    getParameterValue(SynapseConstants.SYNAPSE_ENV));
    return endpoint;
}
 
Example #15
Source File: ApiResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public boolean invoke(MessageContext messageContext) {

        buildMessage(messageContext);

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        String param = Utils.getQueryParameter(messageContext, "apiName");

        if (Objects.nonNull(param)) {
            populateApiData(messageContext, param);
        } else {
            populateApiList(messageContext);
        }

        axis2MessageContext.removeProperty(Constants.NO_ENTITY_BODY);
        return true;
    }
 
Example #16
Source File: TaskResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private void populateTasksList(MessageContext messageContext) {

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        SynapseConfiguration configuration = messageContext.getConfiguration();

        Collection<Startup> tasks = configuration.getStartups();
        JSONObject jsonBody = Utils.createJSONList(tasks.size());
        for (Startup task : tasks) {
            JSONObject taskObject = new JSONObject();
            taskObject.put(Constants.NAME, task.getName());
            jsonBody.getJSONArray(Constants.LIST).put(taskObject);
        }
        Utils.setJsonPayLoad(axis2MessageContext, jsonBody);
    }
 
Example #17
Source File: APIMgtLatencySynapseHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequestInFlow(MessageContext messageContext) {
    TracingTracer tracer = ServiceReferenceHolder.getInstance().getTracer();

    if (Util.tracingEnabled()) {
        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
        Map headersMap =
                (Map) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        TracingSpan spanContext = Util.extract(tracer, headersMap);
        TracingSpan responseLatencySpan =
                Util.startSpan(APIMgtGatewayConstants.RESPONSE_LATENCY, spanContext, tracer);
        Util.setTag(responseLatencySpan, APIMgtGatewayConstants.SPAN_KIND, APIMgtGatewayConstants.SERVER);
        GatewayUtils.setRequestRelatedTags(responseLatencySpan, messageContext);
        messageContext.setProperty(APIMgtGatewayConstants.RESPONSE_LATENCY, responseLatencySpan);
    }
    return true;
}
 
Example #18
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgContinueWhenRemoteIPIsNotSpecifiedInMsgCtx() throws XMLStreamException,
        ThrottleException {
    //Set concurrency count to be 100
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext()
            .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, new TreeMap<String, Object>());
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "IP", IP, 0, 60000, "true"),
            THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "IP", IP, 0, 60000, "true"),
            THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    //Throttling limits won't get applied, since the remote IP is not specified in message context,
    //Thus message will be continued by the gateway, even though the limits are exceeded 0/60000
    Assert.assertTrue(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #19
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgThrottleOutWhenApplicationLevelQuotaExceeded() throws XMLStreamException,
        ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApplicationTier("Silver");
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 0,
            60000, "true"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 0,
            60000, "true"),THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
    Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn
            (callerConfiguration);
    //Set application level access state to be ACCESS_DENIED
    Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #20
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgThrottleOutWhenIPBasedThrottlingAccessRateIsExceeded() throws XMLStreamException,
        ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REMOTE_ADDR", IP);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REMOTE_HOST", domain);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "IP", IP, 1, 60000, "true"),
            THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "IP", IP, 1, 60000, "true"),
            THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    //First request should continue as the access rates are not exceeded yet (Access rate = 1 per 60000ms )
    Assert.assertTrue(apiThrottleHandler.handleRequest(messageContext));
    //Second request should throttle out as the access rate is exceeded
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #21
Source File: HttpCachingFilter.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * If the cached response is expired, response needs to be fetched again. And if the cached response have the
 * no-cache header, existing cached response needs to be validated with the backend by sending a request with
 * If-None-Match header with ETag value. This method returns whether a request needs to be sent to the backend
 * or not.
 *
 * @param cachedResponse The cached response.
 * @param synCtx         The message context.
 * @return True if response need to validated with backend.
 */
public static boolean isValidCacheEntry(CachableResponse cachedResponse, MessageContext synCtx) {
    Map<String, Object> httpHeaders = cachedResponse.getHeaderProperties();
    org.apache.axis2.context.MessageContext msgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String eTagValue = null;
    boolean isNoCache = false;
    long maxAge = -1;
    //Read cache-control, max-age and ETag header from cached response.
    if (httpHeaders != null) {
        eTagValue = getETagValue(httpHeaders);
        if (httpHeaders.get(HttpHeaders.CACHE_CONTROL) != null) {
            String cacheControlHeaderValue = String.valueOf(httpHeaders.get(HttpHeaders.CACHE_CONTROL));
            List<String> cacheControlHeaders = Arrays.asList(cacheControlHeaderValue.split("\\s*,\\s*"));
            for (String cacheControlHeader : cacheControlHeaders) {
                if (CachingConstants.NO_CACHE_STRING.equalsIgnoreCase(cacheControlHeader)) {
                    isNoCache = true;
                }
                if (cacheControlHeader.contains(CachingConstants.MAX_AGE_STRING)) {
                    maxAge = Long.parseLong(cacheControlHeader.split("=")[1]);
                }
            }
        }
    }
    return isCachedResponseExpired(cachedResponse, maxAge) ||
            isValidateResponseWithETag(msgCtx, eTagValue, isNoCache);
}
 
Example #22
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgContinueWhenResourceLevelQuotaExceededAndStopOnQuotaReachDisabled() throws XMLStreamException,
        ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    //Set StopOnQuotaReach = false
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000,
            "false"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000,
            "false"),THROTTLE_POLICY_RESOURCE_KEY, true,0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
    Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn
            (callerConfiguration);
    //Set resource level access state to be ACCESS_DENIED
    Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
    //Message should be successful even though the access state is set to be 'ACCESS_DENIED', since the
    //stopOnQuotaReach is disabled
    Assert.assertTrue(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #23
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Setup load balancer message context properties to be used by the out block of the main sequence.
 * These values will be used to update the Location value in the response header.
 *
 * @param synCtx
 * @param currentMember
 */
private void setupLoadBalancerContextProperties(MessageContext synCtx, org.apache.axis2.clustering.Member currentMember) {
    String targetHostname = extractTargetHost(synCtx);
    org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();

    String httpTransportName = "http", httpsTransportName = "https";
    String transportId = getTransportId(extractIncomingTransport(synCtx));

    if (transportId != null) {
        httpsTransportName = httpsTransportName.concat(transportId);
        httpTransportName = httpTransportName.concat(transportId);
    }

    TransportInDescription httpTransportIn = axis2MsgCtx.getConfigurationContext().getAxisConfiguration().getTransportIn(httpTransportName);
    TransportInDescription httpsTransportIn = axis2MsgCtx.getConfigurationContext().getAxisConfiguration().getTransportIn(httpsTransportName);
    String lbHttpPort = (String) httpTransportIn.getParameter("port").getValue();
    String lbHttpsPort = (String) httpsTransportIn.getParameter("port").getValue();
    String clusterId = currentMember.getProperties().getProperty(LoadBalancerConstants.CLUSTER_ID);

    synCtx.setProperty(LoadBalancerConstants.LB_TARGET_HOSTNAME, targetHostname);
    synCtx.setProperty(LoadBalancerConstants.LB_HTTP_PORT, lbHttpPort);
    synCtx.setProperty(LoadBalancerConstants.LB_HTTPS_PORT, lbHttpsPort);
    synCtx.setProperty(LoadBalancerConstants.CLUSTER_ID, clusterId);
}
 
Example #24
Source File: ODataPassThroughHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequestInFlow(MessageContext messageContext) {
    try {
        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
        Object isODataService = axis2MessageContext.getProperty("IsODataService");
        // In this if block we are skipping proxy services, inbound related message contexts & api.
        if (axis2MessageContext.getProperty("TransportInURL") != null && isODataService != null) {
            RelayUtils.buildMessage(axis2MessageContext);
            ODataServletRequest request = new ODataServletRequest(axis2MessageContext);
            ODataServletResponse response = new ODataServletResponse(axis2MessageContext);
            ODataEndpoint.process(request, response);
            setContent(axis2MessageContext, response);
            setHeaders(axis2MessageContext, response);
            messageContext.setTo(null);
            messageContext.setResponse(true);
            Axis2Sender.sendBack(messageContext);
        }
        return true;
    } catch (Exception e) {
        this.handleException("Error occurred in integrator handler.", e, messageContext);
        return true;
    }
}
 
Example #25
Source File: TestUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static MessageContext getMessageContextWithAuthContext(String context, String version) {
    SynapseConfiguration synCfg = new SynapseConfiguration();
    org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
    axisMsgCtx.setIncomingTransportName("http");
    axisMsgCtx.setProperty(Constants.Configuration.TRANSPORT_IN_URL, "/test/1.0.0/search.atom");
    AxisConfiguration axisConfig = new AxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
    MessageContext synCtx = new Axis2MessageContext(axisMsgCtx, synCfg,
            new Axis2SynapseEnvironment(cfgCtx, synCfg));
    synCtx.setProperty(RESTConstants.REST_API_CONTEXT, context);
    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API_VERSION, version);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setUsername("sanjeewa");
    authenticationContext.setApiKey("123456789");
    authenticationContext.setApplicationId("123");
    authenticationContext.setApplicationName("test-app");
    authenticationContext.setAuthenticated(true);
    authenticationContext.setCallerToken("987654321");
    authenticationContext.setTier("Silver");
    authenticationContext.setSpikeArrestLimit(600);
    authenticationContext.setSubscriber("testSubscriber");
    Map map = new TreeMap();
    map.put("host","127.0.0.1");
    map.put("X-FORWARDED-FOR", "127.0.0.1");
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, map);
    synCtx.setProperty(API_AUTH_CONTEXT, authenticationContext);
    return synCtx;
}
 
Example #26
Source File: ThreatExceptionHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * The method sets message context properties for error message.
 *
 * @param messageContext This message context contains the request message properties of the relevant API which was
 *                       enabled a Validator message mediation in flow.
 * @param errorMessage   specific error message for each validator.
 */
public static void handleException(MessageContext messageContext, String errorMessage) {
    messageContext.setProperty(ThreatProtectorConstants.STATUS, true);
    messageContext.setProperty(ThreatProtectorConstants.ERROR_CODE,
            ThreatProtectorConstants.HTTP_HEADER_THREAT_CODE);
    messageContext.setProperty(ThreatProtectorConstants.ERROR_MESSAGE, errorMessage);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(
            ThreatProtectorConstants.HTTP_SC, ThreatProtectorConstants.HTTP_SC_CODE);
    throw new SynapseException(errorMessage);
}
 
Example #27
Source File: APIMgtResponseHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void mediateWithStartTimeNotSet() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    Mockito.when(apiManagerAnalyticsConfiguration.isBuildMsg()).thenReturn(false);
    APIMgtResponseHandler apiMgtResponseHandler = new APIMgtResponseHandlerWrapper(apiMgtUsageDataPublisher,
            true, false, apiManagerAnalyticsConfiguration);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext
            .class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(SynapseConstants.HTTP_SC)).thenReturn(200);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.REST_URL_PREFIX)).thenReturn("https://localhost");
    apiMgtResponseHandler.mediate(messageContext);
}
 
Example #28
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetThrottledInConditionWithComplexConditionNegative() {

    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnableHeaderConditions(true);
    ServiceReferenceHolder.getInstance().setThrottleProperties(throttleProperties);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REST_URL_POSTFIX",
            "/temperature?abc=cde&bcd=xyz");
    Map<String, List<ConditionDto>> conditionMap = new HashMap<>();
    conditionMap.put("condition1", Arrays.asList(new ConditionDto[]{getComplexCondition1()}));
    conditionMap.put("default", Arrays.asList(new ConditionDto[]{getComplexCondition1(), getComplexCondition2()}));
    String condition = throttleConditionEvaluator.getThrottledInCondition(messageContext, null, conditionMap);
    Assert.assertEquals(null, condition);
}
 
Example #29
Source File: APIManagerExtensionHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleRequestWithGlobalInOutSeq() {
	// Test for both in and out sequences
	MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
	SynapseConfiguration synapseConfig = Mockito.mock(SynapseConfiguration.class);
	org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito
			.mock(org.apache.axis2.context.MessageContext.class);
	Options options = Mockito.mock(Options.class);
	EndpointReference endPoint = Mockito.mock(EndpointReference.class);

	Map localRegistry = Mockito.mock(Map.class);

	Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
	Mockito.when(((Axis2MessageContext) messageContext).getConfiguration()).thenReturn(synapseConfig);
	Mockito.when(synapseConfig.getLocalRegistry()).thenReturn(localRegistry);
	Mockito.when(axis2MsgCntxt.getOptions()).thenReturn(options);
	Mockito.when(options.getTo()).thenReturn(endPoint);
	Mockito.when(endPoint.getAddress()).thenReturn("http://localhost:9443/test");

	Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn(API_NAME);

	SequenceMediator globalOutSeq = Mockito.mock(SequenceMediator.class);
	SequenceMediator globalInSeq = Mockito.mock(SequenceMediator.class);
	Mockito.when(localRegistry.get(EXT_SEQUENCE_PREFIX + DIRECTION_IN)).thenReturn(globalInSeq);
	Mockito.when(localRegistry.get(EXT_SEQUENCE_PREFIX + DIRECTION_OUT)).thenReturn(globalOutSeq);
	Mockito.when(((Mediator) globalOutSeq).mediate(messageContext)).thenReturn(true);
	Mockito.when(((Mediator) globalInSeq).mediate(messageContext)).thenReturn(true);

	APIManagerExtensionHandler handler = createAPIManagerExtensionHandler();
	// both methods are executed during a full request path
	handler.handleRequest(messageContext);
	handler.handleResponse(messageContext);

	// check whether custom out sequnce is only executed once
	Mockito.verify(globalOutSeq, Mockito.times(1)).mediate(messageContext);
	// check whether custom in sequnce is only executed once
	Mockito.verify(globalInSeq, Mockito.times(1)).mediate(messageContext);
}
 
Example #30
Source File: ApiResource.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private void populateApiData(MessageContext messageContext, String apiName) {

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        JSONObject jsonBody = getApiByName(messageContext, apiName);

        if (Objects.nonNull(jsonBody)) {
            Utils.setJsonPayLoad(axis2MessageContext, jsonBody);
        } else {
            axis2MessageContext.setProperty(Constants.HTTP_STATUS_CODE, Constants.NOT_FOUND);
        }
    }