Search in sources :

Example 16 with ConfigurationContext

use of org.apache.axis2.context.ConfigurationContext in project wso2-synapse by wso2.

the class ThrottleHandler method process.

/**
 * processing through the throttle
 * 1) concurrent throttling
 * 2) access rate based throttling - domain or ip
 *
 * @param throttle       The Throttle object - holds all configuration and state data
 *                       of the throttle
 * @param messageContext The MessageContext , that holds all data per message basis
 * @throws AxisFault         Throws when access must deny for caller
 * @throws ThrottleException    ThrottleException
 */
public void process(Throttle throttle, MessageContext messageContext) throws ThrottleException, AxisFault {
    String throttleId = throttle.getId();
    ConfigurationContext cc = messageContext.getConfigurationContext();
    // acquiring  cache manager.
    Cache<String, ConcurrentAccessController> cache;
    CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(THROTTLING_CACHE_MANAGER);
    if (cacheManager != null) {
        cache = cacheManager.getCache(THROTTLING_CACHE);
    } else {
        cache = Caching.getCacheManager().getCache(THROTTLING_CACHE);
    }
    if (log.isDebugEnabled()) {
        log.debug("created throttling cache : " + cache);
    }
    // Get the concurrent access controller
    ConcurrentAccessController cac;
    String key = null;
    key = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + throttleId + ThrottleConstants.CAC_SUFFIX;
    cac = cache.get(key);
    // check for concurrent access
    boolean canAccess = doConcurrentThrottling(cac, messageContext);
    if (canAccess) {
        if (messageContext.getFLOW() == MessageContext.IN_FLOW) {
            // gets the remote caller domain name
            String domain = null;
            HttpServletRequest request = (HttpServletRequest) messageContext.getPropertyNonReplicable(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            if (request != null) {
                domain = request.getRemoteHost();
            }
            // Domain name based throttling
            // check whether a configuration has been defined for this domain name or not
            String callerId = null;
            if (domain != null) {
                // loads the ThrottleContext
                ThrottleContext throttleCtxt = throttle.getThrottleContext(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY);
                if (throttleCtxt != null) {
                    // Loads the ThrottleConfiguration
                    ThrottleConfiguration throttleConfig = throttleCtxt.getThrottleConfiguration();
                    if (throttleConfig != null) {
                        // check for configuration for this caller
                        callerId = throttleConfig.getConfigurationKeyOfCaller(domain);
                        if (callerId != null) {
                            // If this is a clustered env.
                            throttleCtxt.setThrottleId(throttleId);
                            AccessInformation infor = accessRateController.canAccess(throttleCtxt, callerId, ThrottleConstants.DOMAIN_BASE);
                            StatCollector.collect(infor, domain, ThrottleConstants.DOMAIN_BASE);
                            // check for the permission for access
                            if (!infor.isAccessAllowed()) {
                                // if the access has denied by rate based throttling
                                if (cac != null) {
                                    cac.incrementAndGet();
                                    cache.put(key, cac);
                                    if (debugOn) {
                                        log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
                                    }
                                }
                                throw new AxisFault(" Access deny for a " + "caller with Domain " + domain + " " + " : Reason : " + infor.getFaultReason());
                            }
                        } else {
                            if (debugOn) {
                                log.debug("Could not find the Throttle Context for domain-Based " + "Throttling for domain name " + domain + " Throttling for this " + "domain name may not be configured from policy");
                            }
                        }
                    }
                }
            } else {
                if (debugOn) {
                    log.debug("Could not find the domain of the caller - IP-based throttling may occur");
                }
            }
            if (callerId == null) {
                String ip = (String) messageContext.getProperty(MessageContext.REMOTE_ADDR);
                if (ip != null) {
                    // loads IP based throttle context
                    ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY);
                    if (context != null) {
                        // Loads the ThrottleConfiguration
                        ThrottleConfiguration config = context.getThrottleConfiguration();
                        if (config != null) {
                            // check for configuration for this ip
                            callerId = config.getConfigurationKeyOfCaller(ip);
                            if (callerId != null) {
                                context.setThrottleId(throttleId);
                                AccessInformation infor = accessRateController.canAccess(context, callerId, ThrottleConstants.IP_BASE);
                                // check for the permission for access
                                StatCollector.collect(infor, ip, ThrottleConstants.IP_BASE);
                                if (!infor.isAccessAllowed()) {
                                    // if the access has denied by rate based throttling
                                    if (cac != null) {
                                        cac.incrementAndGet();
                                        // set back if this is a clustered env
                                        cache.put(key, cac);
                                        if (debugOn) {
                                            log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
                                        }
                                    }
                                    throw new AxisFault(" Access deny for a " + "caller with IP " + ip + " " + " : Reason : " + infor.getFaultReason());
                                }
                            }
                        }
                    } else {
                        if (debugOn) {
                            log.debug("Could not find the throttle Context for IP-Based throttling");
                        }
                    }
                } else {
                    if (debugOn) {
                        log.debug("Could not find the IP address of the caller " + "- throttling will not occur");
                    }
                }
            }
        }
        // just replicate the current state of ConcurrentAccessController
        if (cac != null) {
            cache.put(key, cac);
            if (debugOn) {
                log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
            }
        }
        // finally engage rolebased access throttling if available
        doRoleBasedAccessThrottling(throttle, messageContext);
    } else {
        // replicate the current state of ConcurrentAccessController
        if (cac != null) {
            cache.put(key, cac);
            if (debugOn) {
                log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
            }
        }
        throw new AxisFault("Access has currently been denied since " + " maximum concurrent access have exceeded");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) AxisFault(org.apache.axis2.AxisFault) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) CacheManager(javax.cache.CacheManager) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController)

Example 17 with ConfigurationContext

use of org.apache.axis2.context.ConfigurationContext in project wso2-synapse by wso2.

the class ThrottleHandler method doRoleBasedAccessThrottling.

/**
 * Helper method for handling role based Access throttling
 *
 * @param messageContext             MessageContext - message level states
 * @return true if access is allowed through concurrent throttling ,o.w false
 */
private boolean doRoleBasedAccessThrottling(Throttle throttle, MessageContext messageContext) throws AxisFault, ThrottleException {
    boolean canAccess = true;
    if (throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY) == null) {
        // if no role base throttle config return immediately
        return canAccess;
    }
    ConfigurationContext cc = messageContext.getConfigurationContext();
    String throttleId = throttle.getId();
    // acquiring  cache manager.
    Cache<String, ConcurrentAccessController> cache;
    CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(THROTTLING_CACHE_MANAGER);
    if (cacheManager != null) {
        cache = cacheManager.getCache(THROTTLING_CACHE);
    } else {
        cache = Caching.getCacheManager().getCache(THROTTLING_CACHE);
    }
    if (log.isDebugEnabled()) {
        log.debug("created throttling cache : " + cache);
    }
    String key = null;
    ConcurrentAccessController cac = null;
    key = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + throttleId + ThrottleConstants.CAC_SUFFIX;
    cac = cache.get(key);
    if (messageContext.getFLOW() == MessageContext.IN_FLOW) {
        // gets the remote caller role name
        String consumerKey = null;
        boolean isAuthenticated = false;
        String roleID = null;
        HttpServletRequest request = (HttpServletRequest) messageContext.getPropertyNonReplicable(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        if (request != null) {
            String oAuthHeader = request.getHeader("OAuth");
            // consumerKey = Utils.extractCustomerKeyFromAuthHeader(oAuthHeader);
            // roleID = Utils.extractCustomerKeyFromAuthHeader(oAuthHeader);
            DummyAuthenticator authFuture = new DummyAuthenticator(oAuthHeader);
            consumerKey = authFuture.getAPIKey();
            new DummyHandler().authenticateUser(authFuture);
            roleID = (String) authFuture.getAuthorizedRoles().get(0);
            isAuthenticated = authFuture.isAuthenticated();
        }
        if (!isAuthenticated) {
            throw new AxisFault(" Access deny for a " + "caller with consumer Key: " + consumerKey + " " + " : Reason : Authentication failure");
        }
        // Domain name based throttling
        // check whether a configuration has been defined for this role name or not
        String consumerRoleID = null;
        if (consumerKey != null && isAuthenticated) {
            // loads the ThrottleContext
            ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
            if (context != null) {
                // Loads the ThrottleConfiguration
                ThrottleConfiguration config = context.getThrottleConfiguration();
                if (config != null) {
                    // check for configuration for this caller
                    consumerRoleID = config.getConfigurationKeyOfCaller(roleID);
                    if (consumerRoleID != null) {
                        context.setThrottleId(throttleId);
                        AccessInformation infor = roleBasedAccessController.canAccess(context, consumerKey, consumerRoleID);
                        StatCollector.collect(infor, consumerKey, ThrottleConstants.ROLE_BASE);
                        // check for the permission for access
                        if (!infor.isAccessAllowed()) {
                            // if the access has denied by rate based throttling
                            if (cac != null) {
                                cac.incrementAndGet();
                                cache.put(key, cac);
                                if (debugOn) {
                                    log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
                                }
                            }
                            throw new AxisFault(" Access deny for a " + "caller with Domain " + consumerKey + " " + " : Reason : " + infor.getFaultReason());
                        }
                    } else {
                        if (debugOn) {
                            log.debug("Could not find the Throttle Context for role-Based " + "Throttling for role name " + consumerKey + " Throttling for this " + "role name may not be configured from policy");
                        }
                    }
                }
            }
        } else {
            if (debugOn) {
                log.debug("Could not find the role of the caller - role based throttling NOT applied");
            }
        }
    }
    return canAccess;
}
Also used : AxisFault(org.apache.axis2.AxisFault) ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) DummyAuthenticator(org.apache.synapse.commons.throttle.module.utils.impl.DummyAuthenticator) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) HttpServletRequest(javax.servlet.http.HttpServletRequest) DummyHandler(org.apache.synapse.commons.throttle.module.utils.impl.DummyHandler) CacheManager(javax.cache.CacheManager) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController)

Example 18 with ConfigurationContext

use of org.apache.axis2.context.ConfigurationContext in project wso2-synapse by wso2.

the class ThrottleEnguageUtils method enguage.

public static void enguage(AxisDescription axisDescription, ConfigurationContext configctx, Throttle defaultThrottle) throws AxisFault {
    String currentServiceName;
    if (axisDescription instanceof AxisService) {
        Throttle throttle = null;
        AxisService currentService = ((AxisService) axisDescription);
        PolicySubject policySubject = currentService.getPolicySubject();
        if (policySubject != null) {
            try {
                List policies = new ArrayList(policySubject.getAttachedPolicyComponents());
                Policy currentPolicy = PolicyUtil.getMergedPolicy(policies, currentService);
                if (currentPolicy != null) {
                    throttle = ThrottleFactory.createServiceThrottle(currentPolicy);
                    if (throttle == null) {
                        // this is for the scenario when throttle policy is empty rather than
                        // null (eg: removing the throttle policy via policy editor)
                        throttle = defaultThrottle;
                    }
                // todo - done by isuru, recheck
                } else {
                    AxisConfiguration axisConfig = configctx.getAxisConfiguration();
                    AxisModule throttleModule = axisConfig.getModule(ThrottleConstants.THROTTLE_MODULE_NAME);
                    policySubject = throttleModule.getPolicySubject();
                    if (policySubject != null) {
                        currentPolicy = ThrottleEnguageUtils.getThrottlePolicy(policySubject.getAttachedPolicyComponents());
                        if (currentPolicy != null) {
                            throttle = ThrottleFactory.createModuleThrottle(currentPolicy);
                        }
                    }
                // todo - done by isuru
                }
            } catch (ThrottleException e) {
                log.error("Error was occurred when engaging throttle module for" + " the service :" + currentService.getName() + e.getMessage());
                log.info("Throttling will occur using default module policy");
                throttle = defaultThrottle;
            }
            if (throttle != null) {
                Map throttles = (Map) configctx.getPropertyNonReplicable(ThrottleConstants.THROTTLES_MAP);
                if (throttles == null) {
                    throttles = new HashMap();
                    configctx.setNonReplicableProperty(ThrottleConstants.THROTTLES_MAP, throttles);
                }
                String serviceName = currentService.getName();
                throttle.setId(serviceName);
                throttles.put(serviceName, throttle);
                ConcurrentAccessController cac = throttle.getConcurrentAccessController();
                if (cac != null) {
                    String cacKey = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + serviceName + ThrottleConstants.CAC_SUFFIX;
                    configctx.setProperty(cacKey, cac);
                }
            }
        }
    } else if (axisDescription instanceof AxisOperation) {
        Throttle throttle = null;
        AxisOperation currentOperation = ((AxisOperation) axisDescription);
        AxisService axisService = (AxisService) currentOperation.getParent();
        if (axisService != null) {
            currentServiceName = axisService.getName();
            PolicySubject policySubject = currentOperation.getPolicySubject();
            if (policySubject != null) {
                try {
                    List policies = new ArrayList(policySubject.getAttachedPolicyComponents());
                    Policy currentPolicy = PolicyUtil.getMergedPolicy(policies, currentOperation);
                    if (currentPolicy != null) {
                        throttle = ThrottleFactory.createOperationThrottle(currentPolicy);
                    }
                } catch (ThrottleException e) {
                    log.error("Error was occurred when engaging throttle module " + "for operation : " + currentOperation.getName() + " in the service :" + currentServiceName + e.getMessage());
                    log.info("Throttling will occur using default module policy");
                }
                // if current throttle is null, use the default throttle
                if (throttle == null) {
                    throttle = defaultThrottle;
                }
                Map throttles = (Map) configctx.getPropertyNonReplicable(ThrottleConstants.THROTTLES_MAP);
                if (throttles == null) {
                    throttles = new HashMap();
                    configctx.setNonReplicableProperty(ThrottleConstants.THROTTLES_MAP, throttles);
                }
                QName opQName = currentOperation.getName();
                if (opQName != null) {
                    String opName = opQName.getLocalPart();
                    String key = currentServiceName + opName;
                    throttle.setId(key);
                    throttles.put(key, throttle);
                    ConcurrentAccessController cac = throttle.getConcurrentAccessController();
                    if (cac != null) {
                        String cacKey = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + key + ThrottleConstants.CAC_SUFFIX;
                        configctx.setProperty(cacKey, cac);
                    }
                }
            }
        }
    }
}
Also used : Policy(org.apache.neethi.Policy) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Throttle(org.apache.synapse.commons.throttle.core.Throttle) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ArrayList(java.util.ArrayList) List(java.util.List) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) HashMap(java.util.HashMap) Map(java.util.Map)

Example 19 with ConfigurationContext

use of org.apache.axis2.context.ConfigurationContext in project wso2-synapse by wso2.

the class TestCasesMediator method createSynapseMessageContext.

/**
 * Creating message context using input payload and the synapse configuration.
 *
 * @param payload       received input payload for particular test case
 * @param synapseConfig synapse configuration used for deploy the sequence deployer
 * @return message context
 */
private static MessageContext createSynapseMessageContext(String payload, SynapseConfiguration synapseConfig) {
    MessageContext synapseMessageContext = null;
    try {
        org.apache.axis2.context.MessageContext messageContext = new org.apache.axis2.context.MessageContext();
        AxisConfiguration axisConfig = synapseConfig.getAxisConfiguration();
        if (axisConfig == null) {
            axisConfig = new AxisConfiguration();
            synapseConfig.setAxisConfiguration(axisConfig);
        }
        ConfigurationContext configurationContext = new ConfigurationContext(axisConfig);
        SynapseEnvironment env = new Axis2SynapseEnvironment(configurationContext, synapseConfig);
        // Create custom Axis2MessageContext with required data and SOAP1.1 envelop
        synapseMessageContext = new Axis2MessageContext(messageContext, synapseConfig, env);
        synapseMessageContext.setContinuationEnabled(true);
        synapseMessageContext.setMessageID(UIDGenerator.generateURNString());
        synapseMessageContext.setEnvelope(OMAbstractFactory.getSOAP11Factory().createSOAPEnvelope());
        SOAPEnvelope envelope = synapseMessageContext.getEnvelope();
        envelope.addChild(OMAbstractFactory.getSOAP12Factory().createSOAPBody());
        ((Axis2MessageContext) synapseMessageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
        ((Axis2MessageContext) synapseMessageContext).getAxis2MessageContext().setOperationContext(new OperationContext(new InOutAxisOperation(), new ServiceContext()));
        if (payload != null) {
            Map.Entry<String, String> inputPayload = CommonUtils.checkInputStringFormat(payload);
            String inputPayloadType = inputPayload.getKey();
            String trimmedInputPayload = inputPayload.getValue();
            if (inputPayloadType.equals(XML_FORMAT)) {
                envelope.getBody().addChild(createOMElement(trimmedInputPayload));
            } else if (inputPayloadType.equals(JSON_FORMAT)) {
                org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synapseMessageContext).getAxis2MessageContext();
                envelope.getBody().addChild(JsonUtil.getNewJsonPayload(axis2MessageContext, trimmedInputPayload, true, true));
            } else if (inputPayloadType.equals(TEXT_FORMAT)) {
                envelope.getBody().addChild(getTextElement(trimmedInputPayload));
            }
        }
    } catch (Exception e) {
        log.error("Exception while creating synapse message context", e);
    }
    return synapseMessageContext;
}
Also used : OperationContext(org.apache.axis2.context.OperationContext) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) ServiceContext(org.apache.axis2.context.ServiceContext) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Map(java.util.Map) AbstractMap(java.util.AbstractMap) TreeMap(java.util.TreeMap) InOutAxisOperation(org.apache.axis2.description.InOutAxisOperation) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 20 with ConfigurationContext

use of org.apache.axis2.context.ConfigurationContext in project wso2-synapse by wso2.

the class ConfigurationDeployer method createConfigurationContext.

/**
 * Get configuration context from synapse configuration.
 *
 * @param synapseConfiguration     synapse configuration context
 * @return configuration context
 * @throws AxisFault while return the configuration context
 */
private ConfigurationContext createConfigurationContext(SynapseConfiguration synapseConfiguration) throws AxisFault {
    AxisConfiguration axisConfiguration = synapseConfiguration.getAxisConfiguration();
    ConfigurationContext configurationContext = new ConfigurationContext(axisConfiguration);
    SynapseEnvironment synapseEnvironment = new Axis2SynapseEnvironment(configurationContext, synapseConfiguration);
    axisConfiguration.addParameter(new Parameter(SynapseConstants.SYNAPSE_ENV, synapseEnvironment));
    axisConfiguration.addParameter(new Parameter(SynapseConstants.SYNAPSE_CONFIG, synapseConfiguration));
    configurationContext.setAxisConfiguration(axisConfiguration);
    return configurationContext;
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) Parameter(org.apache.axis2.description.Parameter)

Aggregations

ConfigurationContext (org.apache.axis2.context.ConfigurationContext)184 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)119 Axis2SynapseEnvironment (org.apache.synapse.core.axis2.Axis2SynapseEnvironment)70 Test (org.junit.Test)64 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)62 Parameter (org.apache.axis2.description.Parameter)56 SynapseEnvironment (org.apache.synapse.core.SynapseEnvironment)48 OMElement (org.apache.axiom.om.OMElement)43 AxisFault (org.apache.axis2.AxisFault)34 MessageContext (org.apache.synapse.MessageContext)34 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)31 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)30 AxisService (org.apache.axis2.description.AxisService)26 EndpointReference (org.apache.axis2.addressing.EndpointReference)24 MessageContext (org.apache.axis2.context.MessageContext)23 Options (org.apache.axis2.client.Options)22 HashMap (java.util.HashMap)20 ServiceContext (org.apache.axis2.context.ServiceContext)19 Map (java.util.Map)18 TransportOutDescription (org.apache.axis2.description.TransportOutDescription)16