You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by la...@apache.org on 2013/07/12 09:53:10 UTC
[17/18] git commit: applying 0001-Refactor-throttling-module.patch
applying 0001-Refactor-throttling-module.patch
Project: http://git-wip-us.apache.org/repos/asf/incubator-stratos/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-stratos/commit/767082e3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-stratos/tree/767082e3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-stratos/diff/767082e3
Branch: refs/heads/master
Commit: 767082e314345555db5de93396908d4642f6dd4b
Parents: a875aab
Author: Lakmal Warusawithana <la...@wso2.com>
Authored: Fri Jul 12 13:21:52 2013 +0530
Committer: Lakmal Warusawithana <la...@wso2.com>
Committed: Fri Jul 12 13:21:52 2013 +0530
----------------------------------------------------------------------
.../org.apache.stratos.throttling.agent/pom.xml | 138 ++++
.../throttling/agent/ThrottlingAgent.java | 246 +++++++
.../Axis2ConfigurationContextObserverImpl.java | 45 ++
.../agent/cache/TenantThrottlingInfo.java | 56 ++
.../agent/cache/ThrottlingActionInfo.java | 40 +
.../agent/cache/ThrottlingInfoCache.java | 121 +++
.../cache/ThrottlingInfoCacheUpdaterTask.java | 82 +++
.../MultitenancyThrottlingServiceClient.java | 65 ++
.../agent/client/ThrottlingRuleInvoker.java | 23 +
.../conf/ThrottlingAgentConfiguration.java | 88 +++
.../ThrottlingAgentServiceComponent.java | 191 +++++
.../listeners/PerRegistryRequestListener.java | 119 +++
.../agent/listeners/PerUserAddListener.java | 90 +++
.../agent/listeners/ServiceRequestListener.java | 114 +++
.../agent/listeners/ThrottlingModule.java | 50 ++
.../agent/listeners/WebAppRequestListener.java | 180 +++++
.../agent/validation/ValidationException.java | 28 +
.../agent/validation/ValidationInfo.java | 42 ++
.../validation/ValidationInfoRetriever.java | 112 +++
.../src/main/resources/META-INF/module.xml | 34 +
.../MultitenancyThrottlingService.wsdl | 82 +++
.../pom.xml | 177 +++++
.../manager/conf/ThrottlingConfiguration.java | 107 +++
.../conf/ThrottlingTaskConfiguration.java | 120 +++
...ThrottlingTaskDataProviderConfiguration.java | 117 +++
.../dataobjects/ThrottlingAccessValidation.java | 73 ++
.../dataobjects/ThrottlingDataContext.java | 148 ++++
.../dataobjects/ThrottlingDataEntry.java | 87 +++
.../ThrottlingDataEntryConstants.java | 44 ++
.../dataproviders/BillingDataProvider.java | 55 ++
.../manager/dataproviders/DataProvider.java | 38 +
.../dataproviders/UsageDataProvider.java | 106 +++
.../manager/exception/ThrottlingException.java | 28 +
.../ThrottlingManagerServiceComponent.java | 129 ++++
.../manager/rules/KnowledgeBaseManager.java | 73 ++
.../throttling/manager/rules/RuleInvoker.java | 92 +++
.../throttling/manager/rules/RuleProperty.java | 45 ++
.../manager/scheduling/ThrottlingJob.java | 120 +++
.../services/MultitenancyThrottlingService.java | 59 ++
.../services/ThrottlingRuleEditorService.java | 90 +++
.../stratos/throttling/manager/tasks/Task.java | 94 +++
.../manager/utils/DataProviderIterator.java | 72 ++
.../stratos/throttling/manager/utils/Util.java | 464 ++++++++++++
.../validation/ValidationInfoManager.java | 122 ++++
.../src/main/resources/META-INF/component.xml | 40 +
.../src/main/resources/META-INF/services.xml | 59 ++
.../carbon/throttling/test/ThrottlingTest.java | 228 ++++++
.../throttling/test/utils/BaseTestCase.java | 116 +++
.../test/utils/CustomDataProvider.java | 46 ++
.../resources/carbon-home/dbscripts/db2.sql | 450 ++++++++++++
.../resources/carbon-home/dbscripts/derby.sql | 364 ++++++++++
.../test/resources/carbon-home/dbscripts/h2.sql | 337 +++++++++
.../resources/carbon-home/dbscripts/mssql.sql | 494 +++++++++++++
.../resources/carbon-home/dbscripts/mysql.sql | 370 ++++++++++
.../resources/carbon-home/dbscripts/oracle.sql | 644 ++++++++++++++++
.../carbon-home/dbscripts/oracle_rac.sql | 644 ++++++++++++++++
.../carbon-home/dbscripts/postgresql.sql | 427 +++++++++++
.../resources/carbon-home/repository/README | 22 +
.../carbon-home/repository/conf/README | 39 +
.../carbon-home/repository/conf/axis2.xml | 633 ++++++++++++++++
.../repository/conf/axis2_client.xml | 283 +++++++
.../repository/conf/broker-config.xml | 55 ++
.../carbon-home/repository/conf/carbon.xml | 354 +++++++++
.../repository/conf/cipher-text.properties | 8 +
.../repository/conf/mgt-transports.xml | 87 +++
.../carbon-home/repository/conf/mime.types | 728 +++++++++++++++++++
.../repository/conf/node/registry.xml | 84 +++
.../repository/conf/node/user-mgt.xml | 106 +++
.../repository/conf/ports-config.xml | 58 ++
.../carbon-home/repository/conf/registry.xml | 102 +++
.../repository/conf/secret-conf.properties | 37 +
.../carbon-home/repository/conf/synapse.xml | 31 +
.../repository/conf/throttling-config1.xml | 48 ++
.../repository/conf/throttling-config2.xml | 48 ++
.../repository/conf/throttling-config3.xml | 48 ++
.../repository/conf/throttling-rules1.drl | 60 ++
.../repository/conf/throttling-rules2.drl | 18 +
.../repository/conf/throttling-rules3.drl | 17 +
.../carbon-home/repository/conf/user-mgt.xml | 117 +++
.../carbon-home/repository/conf/wrapper.conf | 125 ++++
.../carbon-home/repository/logs/README | 1 +
.../src/test/resources/registry.xml | 250 +++++++
.../user-test/adv-jdbc-readonly-test.xml | 60 ++
.../resources/user-test/jdbc-readonly-test.xml | 60 ++
.../user-test/user-mgt-registry-test.xml | 95 +++
.../test/resources/user-test/user-mgt-test.xml | 96 +++
.../org.apache.stratos.throttling.ui/pom.xml | 126 ++++
.../ui/clients/ThrottlingRuleEditorClient.java | 98 +++
.../src/main/resources/META-INF/component.xml | 37 +
.../resources/ThrottlingRuleEditorService.wsdl | 148 ++++
.../throttling/ui/i18n/JSResources.properties | 1 +
.../throttling/ui/i18n/Resources.properties | 2 +
.../web/mt-throttling/docs/images/add-org.png | Bin 0 -> 49926 bytes
.../web/mt-throttling/docs/userguide.html | 35 +
.../web/mt-throttling/images/throttling.gif | Bin 0 -> 1008 bytes
.../resources/web/mt-throttling/throttling.jsp | 104 +++
.../mt-throttling/throttling_ajaxprocessor.jsp | 30 +
.../2.1.0/pom.xml | 136 ----
.../throttling/agent/ThrottlingAgent.java | 244 -------
.../Axis2ConfigurationContextObserverImpl.java | 42 --
.../agent/cache/TenantThrottlingInfo.java | 53 --
.../agent/cache/ThrottlingActionInfo.java | 37 -
.../agent/cache/ThrottlingInfoCache.java | 118 ---
.../cache/ThrottlingInfoCacheUpdaterTask.java | 79 --
.../MultitenancyThrottlingServiceClient.java | 62 --
.../agent/client/ThrottlingRuleInvoker.java | 20 -
.../conf/ThrottlingAgentConfiguration.java | 85 ---
.../ThrottlingAgentServiceComponent.java | 193 -----
.../listeners/PerRegistryRequestListener.java | 116 ---
.../agent/listeners/PerUserAddListener.java | 87 ---
.../agent/listeners/ServiceRequestListener.java | 113 ---
.../agent/listeners/ThrottlingModule.java | 49 --
.../agent/listeners/WebAppRequestListener.java | 179 -----
.../agent/validation/ValidationException.java | 25 -
.../agent/validation/ValidationInfo.java | 39 -
.../validation/ValidationInfoRetriever.java | 109 ---
.../src/main/resources/META-INF/module.xml | 33 -
.../MultitenancyThrottlingService.wsdl | 82 ---
.../2.1.0/pom.xml | 170 -----
.../manager/conf/ThrottlingConfiguration.java | 104 ---
.../conf/ThrottlingTaskConfiguration.java | 117 ---
...ThrottlingTaskDataProviderConfiguration.java | 114 ---
.../dataobjects/ThrottlingAccessValidation.java | 70 --
.../dataobjects/ThrottlingDataContext.java | 145 ----
.../dataobjects/ThrottlingDataEntry.java | 84 ---
.../ThrottlingDataEntryConstants.java | 41 --
.../dataproviders/BillingDataProvider.java | 52 --
.../manager/dataproviders/DataProvider.java | 35 -
.../dataproviders/UsageDataProvider.java | 103 ---
.../manager/exception/ThrottlingException.java | 25 -
.../ThrottlingManagerServiceComponent.java | 129 ----
.../manager/rules/KnowledgeBaseManager.java | 70 --
.../throttling/manager/rules/RuleInvoker.java | 89 ---
.../throttling/manager/rules/RuleProperty.java | 42 --
.../manager/scheduling/ThrottlingJob.java | 117 ---
.../services/MultitenancyThrottlingService.java | 58 --
.../services/ThrottlingRuleEditorService.java | 87 ---
.../carbon/throttling/manager/tasks/Task.java | 91 ---
.../manager/utils/DataProviderIterator.java | 69 --
.../carbon/throttling/manager/utils/Util.java | 461 ------------
.../validation/ValidationInfoManager.java | 119 ---
.../src/main/resources/META-INF/component.xml | 37 -
.../src/main/resources/META-INF/services.xml | 49 --
.../carbon/throttling/test/ThrottlingTest.java | 226 ------
.../throttling/test/utils/BaseTestCase.java | 113 ---
.../test/utils/CustomDataProvider.java | 43 --
.../resources/carbon-home/dbscripts/db2.sql | 450 ------------
.../resources/carbon-home/dbscripts/derby.sql | 364 ----------
.../test/resources/carbon-home/dbscripts/h2.sql | 337 ---------
.../resources/carbon-home/dbscripts/mssql.sql | 494 -------------
.../resources/carbon-home/dbscripts/mysql.sql | 370 ----------
.../resources/carbon-home/dbscripts/oracle.sql | 644 ----------------
.../carbon-home/dbscripts/oracle_rac.sql | 644 ----------------
.../carbon-home/dbscripts/postgresql.sql | 427 -----------
.../resources/carbon-home/repository/README | 22 -
.../carbon-home/repository/conf/README | 39 -
.../carbon-home/repository/conf/axis2.xml | 630 ----------------
.../repository/conf/axis2_client.xml | 280 -------
.../repository/conf/broker-config.xml | 52 --
.../carbon-home/repository/conf/carbon.xml | 351 ---------
.../repository/conf/cipher-text.properties | 8 -
.../repository/conf/mgt-transports.xml | 84 ---
.../carbon-home/repository/conf/mime.types | 727 ------------------
.../repository/conf/node/registry.xml | 81 ---
.../repository/conf/node/user-mgt.xml | 105 ---
.../repository/conf/ports-config.xml | 55 --
.../carbon-home/repository/conf/registry.xml | 99 ---
.../repository/conf/secret-conf.properties | 37 -
.../carbon-home/repository/conf/synapse.xml | 30 -
.../repository/conf/throttling-config1.xml | 47 --
.../repository/conf/throttling-config2.xml | 47 --
.../repository/conf/throttling-config3.xml | 47 --
.../repository/conf/throttling-rules1.drl | 60 --
.../repository/conf/throttling-rules2.drl | 18 -
.../repository/conf/throttling-rules3.drl | 17 -
.../carbon-home/repository/conf/user-mgt.xml | 114 ---
.../carbon-home/repository/conf/wrapper.conf | 125 ----
.../carbon-home/repository/logs/README | 1 -
.../2.1.0/src/test/resources/registry.xml | 247 -------
.../user-test/adv-jdbc-readonly-test.xml | 59 --
.../resources/user-test/jdbc-readonly-test.xml | 59 --
.../user-test/user-mgt-registry-test.xml | 94 ---
.../test/resources/user-test/user-mgt-test.xml | 95 ---
.../org.wso2.carbon.throttling.ui/2.1.0/pom.xml | 120 ---
.../ui/clients/ThrottlingRuleEditorClient.java | 97 ---
.../src/main/resources/META-INF/component.xml | 36 -
.../resources/ThrottlingRuleEditorService.wsdl | 148 ----
.../throttling/ui/i18n/JSResources.properties | 1 -
.../throttling/ui/i18n/Resources.properties | 2 -
.../web/mt-throttling/docs/images/add-org.png | Bin 49926 -> 0 bytes
.../web/mt-throttling/docs/userguide.html | 35 -
.../web/mt-throttling/images/throttling.gif | Bin 1008 -> 0 bytes
.../resources/web/mt-throttling/throttling.jsp | 103 ---
.../mt-throttling/throttling_ajaxprocessor.jsp | 29 -
components/stratos/throttling/pom.xml | 42 --
195 files changed, 12876 insertions(+), 12734 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/pom.xml b/components/org.apache.stratos.throttling.agent/pom.xml
new file mode 100644
index 0000000..5a92a50
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/pom.xml
@@ -0,0 +1,138 @@
+<!--
+ # Licensed to the Apache Software Foundation (ASF) under one
+ # or more contributor license agreements. See the NOTICE file
+ # distributed with this work for additional information
+ # regarding copyright ownership. The ASF licenses this file
+ # to you under the Apache License, Version 2.0 (the
+ # "License"); you may not use this file except in compliance
+ # with the License. You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing,
+ # software distributed under the License is distributed on an
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ # KIND, either express or implied. See the License for the
+ # specific language governing permissions and limitations
+ # under the License.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <parent>
+ <groupId>org.apache.stratos</groupId>
+ <artifactId>stratos-components-parent</artifactId>
+ <version>3.0.0-SNAPSHOT</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>org.apache.stratos.throttling.agent</artifactId>
+ <packaging>bundle</packaging>
+ <name>Apache Stratos - Throttling Agent</name>
+
+ <build>
+
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+ <Bundle-Name>${project.artifactId}</Bundle-Name>
+ <Axis2Module>${project.artifactId}-${project.version}</Axis2Module>
+ <ListenerManager-RequiredServices>
+ org.apache.stratos.throttling.agent.ThrottlingAgent
+ </ListenerManager-RequiredServices>
+ <Export-Package>
+ org.apache.stratos.throttling.agent.client,
+ org.apache.stratos.throttling.agent.*,
+ </Export-Package>
+ <Private-Package>
+ !org.apache.stratos.throttling.agent.client,
+ org.apache.stratos.throttling.agent.*,
+ </Private-Package>
+ <Import-Package>
+ org.wso2.carbon.throttling.agent.stub.*;
+ version="${carbon.platform.package.import.version.range}",
+ org.apache.stratos.common.*,
+ org.wso2.carbon.server.*,
+ org.wso2.carbon.registry.core.*;version=1.0.1,
+ org.wso2.carbon.registry.resource.*,
+ !javax.xml.namespace,
+ javax.xml.namespace; version=0.0.0,
+ javax.servlet;version="${imp.pkg.version.javax.servlet}",
+ javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+ org.apache.axiom.*; version="${axiom.osgi.version.range}",
+ *;resolution:=optional
+ </Import-Package>
+ <DynamicImport-Package>*</DynamicImport-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.apache.axis2.wso2</groupId>
+ <artifactId>axis2</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.utils</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.registry.core</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.registry.extensions</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.registry.resource</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.stratos</groupId>
+ <artifactId>org.apache.stratos.common</artifactId>
+ <version>${apache.stratos.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.throttling.agent.stub</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.server</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.wso2.carbon</groupId>
+ <artifactId>org.wso2.carbon.tomcat.ext</artifactId>
+ <version>${carbon.platform.version}</version>
+ </dependency>
+ </dependencies>
+
+</project>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/ThrottlingAgent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/ThrottlingAgent.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/ThrottlingAgent.java
new file mode 100644
index 0000000..b8665e9
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/ThrottlingAgent.java
@@ -0,0 +1,246 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.throttling.agent;
+
+import org.apache.stratos.throttling.agent.cache.TenantThrottlingInfo;
+import org.apache.stratos.throttling.agent.cache.ThrottlingActionInfo;
+import org.apache.stratos.throttling.agent.cache.ThrottlingInfoCache;
+import org.apache.stratos.throttling.agent.cache.ThrottlingInfoCacheUpdaterTask;
+import org.apache.stratos.throttling.agent.client.MultitenancyThrottlingServiceClient;
+import org.apache.stratos.throttling.agent.client.ThrottlingRuleInvoker;
+import org.apache.stratos.throttling.agent.conf.ThrottlingAgentConfiguration;
+import org.apache.stratos.throttling.agent.listeners.PerRegistryRequestListener;
+import org.apache.stratos.throttling.agent.listeners.PerUserAddListener;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.context.CarbonContext;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.config.RegistryContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.MeteringAccessValidationUtils;
+import org.apache.stratos.common.util.StratosConfiguration;
+import org.wso2.carbon.user.core.listener.UserStoreManagerListener;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.io.File;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+public class ThrottlingAgent {
+ private static final Log log = LogFactory.getLog(ThrottlingAgent.class);
+
+ private static final String CONFIG_FILE = "throttling-agent-config.xml";
+ private static final String MANAGER_SERVER_URL_PARAM_NAME = "managerServiceUrl";
+ private static final String USERNAME_PARAM_NAME = "userName";
+ private static final String PASSWORD_PARAM_NAME = "password";
+
+ private ThrottlingAgentConfiguration configuration;
+
+ private RegistryService registryService;
+
+ private RealmService realmService;
+
+ private ConfigurationContextService configurationContextService;
+
+ private ThrottlingInfoCache throttlingInfoCache;
+
+ private ServiceTracker throttlingRuleInvokerTracker = null;
+
+ private ScheduledExecutorService scheduler;
+
+ private BundleContext bundleContext;
+ private StratosConfiguration stratosConfiguration=null;
+
+ public StratosConfiguration getStratosConfiguration() {
+ return stratosConfiguration;
+ }
+
+ public void setStratosConfiguration(StratosConfiguration stratosConfiguration) {
+ this.stratosConfiguration = stratosConfiguration;
+ }
+
+ public ThrottlingAgent(BundleContext bundleContext) throws Exception {
+ this.scheduler = Executors.newScheduledThreadPool(1, new ThrottlingAgentThreadFactory());
+ this.throttlingInfoCache = new ThrottlingInfoCache();
+ this.bundleContext = bundleContext;
+ }
+
+ public void init() throws RegistryException {
+
+ if("true".equals(ServerConfiguration.getInstance().getFirstProperty("EnableMetering"))){
+
+ UserRegistry superTenantGovernanceRegistry = registryService.getGovernanceSystemRegistry();
+
+ scheduler.scheduleAtFixedRate(
+ new ThrottlingInfoCacheUpdaterTask(throttlingInfoCache, superTenantGovernanceRegistry), 2, 15,
+ TimeUnit.MINUTES);
+
+ PerRegistryRequestListener.registerPerRegistryRequestListener(RegistryContext.getBaseInstance());
+ if (bundleContext != null) {
+ bundleContext.registerService(UserStoreManagerListener.class.getName(),
+ new PerUserAddListener(), null);
+ }
+
+ }
+ throttlingRuleInvokerTracker = new ServiceTracker(bundleContext, ThrottlingRuleInvoker.class.getName(),
+ null);
+ throttlingRuleInvokerTracker.open();
+ }
+
+ public ThrottlingInfoCache getThrottlingInfoCache() {
+ return throttlingInfoCache;
+ }
+
+ public void setRegistryService(RegistryService registryService) {
+ this.registryService = registryService;
+ }
+
+ public RegistryService getRegistryService(){
+ return this.registryService;
+ }
+
+ public void setRealmService(RealmService realmService) {
+ this.realmService = realmService;
+ }
+
+ public RealmService getRealmService() {
+ return realmService;
+ }
+
+ public void setConfigurationContextService(ConfigurationContextService configurationContextService) {
+ this.configurationContextService = configurationContextService;
+ }
+
+ public ConfigurationContextService getConfigurationContextService() {
+ return configurationContextService;
+ }
+
+ public void updateThrottlingCacheForTenant() throws Exception {
+ // TODO: Need to refactor this and updater task
+
+ int tenantId = CarbonContext.getCurrentContext().getTenantId();
+
+ String tenantValidationInfoResourcePath =
+ StratosConstants.TENANT_USER_VALIDATION_STORE_PATH +
+ RegistryConstants.PATH_SEPARATOR + tenantId;
+ try {
+ if (registryService.getGovernanceSystemRegistry().resourceExists(tenantValidationInfoResourcePath)) {
+ Resource tenantValidationInfoResource =
+ registryService.getGovernanceSystemRegistry().get(tenantValidationInfoResourcePath);
+ Properties properties = tenantValidationInfoResource.getProperties();
+ Set<String> actions = MeteringAccessValidationUtils.getAvailableActions(properties);
+ for (String action : actions) {
+ String blocked =
+ tenantValidationInfoResource.getProperty(MeteringAccessValidationUtils
+ .generateIsBlockedPropertyKey(action));
+
+ String blockMessage =
+ tenantValidationInfoResource.getProperty(MeteringAccessValidationUtils
+ .generateErrorMsgPropertyKey(action));
+ TenantThrottlingInfo tenantThrottlingInfo = throttlingInfoCache.getTenantThrottlingInfo(tenantId);
+ if (tenantThrottlingInfo == null) {
+ throttlingInfoCache.addTenant(tenantId);
+ tenantThrottlingInfo = throttlingInfoCache.getTenantThrottlingInfo(tenantId);
+ }
+ tenantThrottlingInfo.updateThrottlingActionInfo(action,
+ new ThrottlingActionInfo("true".equals(blocked), blockMessage));
+ }
+ }
+ } catch (RegistryException re) {
+ String msg =
+ "Error while getting throttling info for tenant " + tenantId + ".";
+ log.error(msg, re);
+ }
+ }
+
+ private ThrottlingAgentConfiguration loadThrottlingConfiguration() throws Exception {
+ // it is acceptable that throttling agent file is not present, when the
+ // embedded rule invoker is in use.
+ ThrottlingAgentConfiguration throttlingAgentConfig = null;
+ String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+ StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + CONFIG_FILE;
+ if (new File(configFileName).exists()) {
+ throttlingAgentConfig = new ThrottlingAgentConfiguration(configFileName);
+ } else {
+ log.warn("Throttling agent config file is not present. File name: " + configFileName + ".");
+ }
+
+ return throttlingAgentConfig;
+ }
+
+ public ThrottlingRuleInvoker getThrottlingRuleInvoker() throws Exception {
+ // first check the OSGi service exists, if so return it
+ ThrottlingRuleInvoker embeddedRuleInvoker =
+ (ThrottlingRuleInvoker) throttlingRuleInvokerTracker.getService();
+ if (embeddedRuleInvoker != null) {
+ return embeddedRuleInvoker;
+ }
+
+
+ if (stratosConfiguration == null) {
+ String msg =
+ "Neither embedded nor web service implementation of throttling rule invoker found.";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+ String serverUrl = stratosConfiguration.getManagerServiceUrl();
+ String userName =stratosConfiguration.getAdminUserName() ;
+ String password = stratosConfiguration.getAdminPassword();
+
+ return new MultitenancyThrottlingServiceClient(serverUrl, userName, password);
+ }
+
+ public void executeManagerThrottlingRules(int tenantId) throws Exception {
+ ThrottlingRuleInvoker client = getThrottlingRuleInvoker();
+ client.executeThrottlingRules(tenantId);
+ }
+
+
+ class ThrottlingAgentThreadFactory implements ThreadFactory {
+ private int counter = 0;
+
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "ThrottlingAgentThreadFactory-" + counter++);
+ }
+ }
+
+ public void executeThrottlingRules(int tenantId) {
+ try {
+ executeManagerThrottlingRules(tenantId);
+ updateThrottlingCacheForTenant();
+ } catch (Exception e) {
+ log.error("Error in executing throttling rules");
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/Axis2ConfigurationContextObserverImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/Axis2ConfigurationContextObserverImpl.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/Axis2ConfigurationContextObserverImpl.java
new file mode 100644
index 0000000..9467b61
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/Axis2ConfigurationContextObserverImpl.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.throttling.agent.cache;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+/**
+ * Axis configuration context observer which add and remove lazy loaded/unloaded tenants to throttling information
+ * cache.
+ */
+public class Axis2ConfigurationContextObserverImpl extends AbstractAxis2ConfigurationContextObserver{
+
+ private ThrottlingInfoCache throttlingInfoCache;
+
+ public Axis2ConfigurationContextObserverImpl(ThrottlingInfoCache throttlingInfoCache){
+ this.throttlingInfoCache = throttlingInfoCache;
+ }
+
+ public void createdConfigurationContext(ConfigurationContext configContext) {
+ throttlingInfoCache.addTenant(MultitenantUtils.getTenantId(configContext));
+ }
+
+ public void terminatedConfigurationContext(ConfigurationContext configCtx) {
+ throttlingInfoCache.deleteTenant(MultitenantUtils.getTenantId(configCtx));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/TenantThrottlingInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/TenantThrottlingInfo.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/TenantThrottlingInfo.java
new file mode 100644
index 0000000..6ea5db6
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/TenantThrottlingInfo.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.throttling.agent.cache;
+
+import org.apache.stratos.common.constants.StratosConstants;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class TenantThrottlingInfo {
+ private Map<String, ThrottlingActionInfo> throttlingActionInfoMap = new HashMap<String, ThrottlingActionInfo>();
+
+ public ThrottlingActionInfo getThrottlingActionInfo(String action) {
+ if(throttlingActionInfoMap.get(action) != null){
+ return throttlingActionInfoMap.get(action);
+ }
+ return new ThrottlingActionInfo(false, "");
+ }
+
+ public ThrottlingActionInfo getThrottlingActionInfo(String[] actions) {
+ ThrottlingActionInfo actionInfo = throttlingActionInfoMap.get(StratosConstants.THROTTLING_ALL_ACTION);
+ if (actionInfo != null && actionInfo.isBlocked()) {
+ return actionInfo;
+ }
+
+ for (String action : actions) {
+ actionInfo = throttlingActionInfoMap.get(action);
+ if (actionInfo != null && actionInfo.isBlocked()) {
+ return actionInfo;
+ }
+ }
+
+ return new ThrottlingActionInfo(false, "");
+ }
+
+ public void updateThrottlingActionInfo(String action, ThrottlingActionInfo throttlingActionInfo) {
+ throttlingActionInfoMap.put(action, throttlingActionInfo);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingActionInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingActionInfo.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingActionInfo.java
new file mode 100644
index 0000000..9a09f06
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingActionInfo.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.throttling.agent.cache;
+
+public class ThrottlingActionInfo {
+ private boolean blocked = false;
+
+ private String message = "";
+
+ public ThrottlingActionInfo(boolean blocked, String message) {
+ this.blocked = blocked;
+ this.message = message;
+ }
+
+ public boolean isBlocked() {
+ return blocked;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCache.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCache.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCache.java
new file mode 100644
index 0000000..3bf9f40
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCache.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.throttling.agent.cache;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.api.RegistryService;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.MeteringAccessValidationUtils;
+import org.apache.stratos.throttling.agent.internal.ThrottlingAgentServiceComponent;
+
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * In memory cache which keeps throttling information for active tenants(local to a server instance). Cache is updated
+ * periodically using information retrieved from registry.
+ */
+public class ThrottlingInfoCache {
+
+ private static final Log log = LogFactory.getLog(ThrottlingInfoCache.class);
+
+ private Map<Integer, TenantThrottlingInfo> tenantThrottlingInfoMap =
+ new ConcurrentHashMap<Integer, TenantThrottlingInfo>();
+
+ public void addTenant(int tenantId){
+ if(!tenantThrottlingInfoMap.containsKey(tenantId)){
+ tenantThrottlingInfoMap.put(tenantId, getTenantThrottlingInfoFromRegistry(tenantId));
+ }
+ }
+
+ public void deleteTenant(int tenantId){
+ tenantThrottlingInfoMap.remove(tenantId);
+ }
+
+ public Set<Integer> getActiveTenants(){
+ return tenantThrottlingInfoMap.keySet();
+ }
+
+ public void updateThrottlingActionInfo(int tenantId, String action, ThrottlingActionInfo throttlingActionInfo){
+ // throttlingInfo could never be null if the update and lazy loading logic are correct.
+ TenantThrottlingInfo throttlingInfo = tenantThrottlingInfoMap.get(tenantId);
+ throttlingInfo.updateThrottlingActionInfo(action, throttlingActionInfo);
+ }
+
+ public ThrottlingActionInfo getThrottlingActionInfo(int tenantId, String action){
+ if(tenantThrottlingInfoMap.get(tenantId) != null){
+ return tenantThrottlingInfoMap.get(tenantId).getThrottlingActionInfo(action);
+ }
+
+ // This could happen if user has never perform this action before or throttling info cache updating task
+ // has not executed for this tenant. TODO: Check the validity
+ return null;
+ }
+
+ public TenantThrottlingInfo getTenantThrottlingInfo(int tenantId){
+ if(!tenantThrottlingInfoMap.containsKey(tenantId)){
+ tenantThrottlingInfoMap.put(tenantId, getTenantThrottlingInfoFromRegistry(tenantId));
+ }
+ return tenantThrottlingInfoMap.get(tenantId);
+ }
+
+ private TenantThrottlingInfo getTenantThrottlingInfoFromRegistry (int tenantId) {
+ log.info("Tenant throttling info is not in the cache. Hence, getting it from registry");
+ RegistryService registryService = ThrottlingAgentServiceComponent.getThrottlingAgent().
+ getRegistryService();
+ TenantThrottlingInfo tenantThrottlingInfo = new TenantThrottlingInfo();
+ try{
+ UserRegistry superTenantGovernanceRegistry = (UserRegistry)registryService.getGovernanceSystemRegistry();
+ String tenantValidationInfoResourcePath =
+ StratosConstants.TENANT_USER_VALIDATION_STORE_PATH +
+ RegistryConstants.PATH_SEPARATOR + tenantId;
+
+ if (superTenantGovernanceRegistry.resourceExists(tenantValidationInfoResourcePath)) {
+ Resource tenantValidationInfoResource =
+ superTenantGovernanceRegistry.get(tenantValidationInfoResourcePath);
+ Properties properties = tenantValidationInfoResource.getProperties();
+ Set<String> actions = MeteringAccessValidationUtils.getAvailableActions(properties);
+ for (String action : actions) {
+ String blocked =
+ tenantValidationInfoResource.getProperty(MeteringAccessValidationUtils
+ .generateIsBlockedPropertyKey(action));
+
+ String blockMessage =
+ tenantValidationInfoResource.getProperty(MeteringAccessValidationUtils
+ .generateErrorMsgPropertyKey(action));
+
+ tenantThrottlingInfo.updateThrottlingActionInfo(action,
+ new ThrottlingActionInfo("true".equals(blocked), blockMessage));
+ }
+ }
+ } catch (Exception e){
+ log.error("Error occurred while obtaining governance system registry from registry service", e);
+ }
+
+ return tenantThrottlingInfo;
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCacheUpdaterTask.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCacheUpdaterTask.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCacheUpdaterTask.java
new file mode 100644
index 0000000..3bfdda4
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/cache/ThrottlingInfoCacheUpdaterTask.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.throttling.agent.cache;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.MeteringAccessValidationUtils;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+
+import java.util.Properties;
+import java.util.Set;
+
+public class ThrottlingInfoCacheUpdaterTask implements Runnable {
+ private static final Log log = LogFactory.getLog(ThrottlingInfoCacheUpdaterTask.class);
+
+ private ThrottlingInfoCache cache;
+ private UserRegistry governanceSystemRegistry;
+
+ public ThrottlingInfoCacheUpdaterTask(ThrottlingInfoCache cache, UserRegistry governanceSystemRegistry) {
+ this.cache = cache;
+ this.governanceSystemRegistry = governanceSystemRegistry;
+ }
+
+ public void run() {
+ log.info("Running throttling info cache updater task");
+ Set<Integer> activeTenants = cache.getActiveTenants();
+ for (Integer tenant : activeTenants) {
+ String tenantValidationInfoResourcePath =
+ StratosConstants.TENANT_USER_VALIDATION_STORE_PATH +
+ RegistryConstants.PATH_SEPARATOR + tenant;
+ try {
+ if (governanceSystemRegistry.resourceExists(tenantValidationInfoResourcePath)) {
+ Resource tenantValidationInfoResource =
+ governanceSystemRegistry.get(tenantValidationInfoResourcePath);
+ Properties properties = tenantValidationInfoResource.getProperties();
+ Set<String> actions = MeteringAccessValidationUtils.getAvailableActions(properties);
+ for (String action : actions) {
+ String blocked =
+ tenantValidationInfoResource.getProperty(MeteringAccessValidationUtils
+ .generateIsBlockedPropertyKey(action));
+ if(log.isDebugEnabled()){
+ log.debug("Action: " + action + " blocked: " + blocked + " tenant: " + tenant);
+ }
+
+ String blockMessage =
+ tenantValidationInfoResource.getProperty(MeteringAccessValidationUtils
+ .generateErrorMsgPropertyKey(action));
+ TenantThrottlingInfo tenantThrottlingInfo = cache.getTenantThrottlingInfo(tenant);
+
+ tenantThrottlingInfo.updateThrottlingActionInfo(action,
+ new ThrottlingActionInfo("true".equals(blocked), blockMessage));
+ }
+ }
+ } catch (RegistryException re) {
+ String msg =
+ "Error while getting throttling info for tenant " + tenant + ".";
+ log.error(msg, re);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/MultitenancyThrottlingServiceClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/MultitenancyThrottlingServiceClient.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/MultitenancyThrottlingServiceClient.java
new file mode 100644
index 0000000..40a901e
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/MultitenancyThrottlingServiceClient.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.client;
+
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.wso2.carbon.authenticator.proxy.AuthenticationAdminClient;
+import org.apache.stratos.throttling.agent.internal.ThrottlingAgentServiceComponent;
+import org.wso2.carbon.throttling.agent.stub.services.MultitenancyThrottlingServiceStub;
+
+public class MultitenancyThrottlingServiceClient implements ThrottlingRuleInvoker {
+ MultitenancyThrottlingServiceStub stub;
+
+ public MultitenancyThrottlingServiceClient(String serverUrl, String userName, String password)
+ throws Exception {
+ stub =
+ new MultitenancyThrottlingServiceStub(ThrottlingAgentServiceComponent.getThrottlingAgent().getConfigurationContextService()
+ .getClientConfigContext(), serverUrl + "MultitenancyThrottlingService");
+ ServiceClient client = stub._getServiceClient();
+ Options option = client.getOptions();
+ option.setManageSession(true);
+ String cookie = login(serverUrl, userName, password);
+ option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+ }
+
+ public static String login(String serverUrl, String userName, String password) throws Exception {
+ String sessionCookie = null;
+ try {
+ AuthenticationAdminClient client =
+ new AuthenticationAdminClient(ThrottlingAgentServiceComponent.getThrottlingAgent().getConfigurationContextService()
+ .getClientConfigContext(), serverUrl, null, null, false);
+ // TODO : get the correct IP
+ boolean isLogin = client.login(userName, password, "127.0.0.1");
+ if (isLogin) {
+ sessionCookie = client.getAdminCookie();
+ }
+ } catch (Exception e) {
+ throw new Exception("Error in login to throttling manager. server: " + serverUrl +
+ "username: " + userName + ".", e);
+ }
+ return sessionCookie;
+ }
+
+
+ public void executeThrottlingRules(int tenantId) throws Exception {
+ stub.executeThrottlingRules(tenantId);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/ThrottlingRuleInvoker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/ThrottlingRuleInvoker.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/ThrottlingRuleInvoker.java
new file mode 100644
index 0000000..10bdc8e
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/client/ThrottlingRuleInvoker.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.client;
+
+public interface ThrottlingRuleInvoker {
+ public void executeThrottlingRules(int tenantId) throws Exception;
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/conf/ThrottlingAgentConfiguration.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/conf/ThrottlingAgentConfiguration.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/conf/ThrottlingAgentConfiguration.java
new file mode 100644
index 0000000..b4fb8af
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/conf/ThrottlingAgentConfiguration.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.conf;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.util.CommonUtil;
+
+public class ThrottlingAgentConfiguration {
+ private static final Log log = LogFactory.getLog(ThrottlingAgentConfiguration.class);
+ private static final String CONFIG_NS =
+ "http://wso2.com/carbon/multitenancy/throttling/agent/config";
+ private static final String PARAMTERS_ELEMENT_NAME = "parameters";
+ private static final String PARAMTER_ELEMENT_NAME = "parameter";
+ private static final String PARAMTER_NAME_ATTR_NAME = "name";
+ private Map<String, String> parameters = new HashMap<String, String>();
+
+ public ThrottlingAgentConfiguration(String throttlingConfigFile) throws Exception {
+ try {
+ OMElement meteringConfig =
+ CommonUtil.buildOMElement(new FileInputStream(throttlingConfigFile));
+ deserialize(meteringConfig);
+ } catch (FileNotFoundException e) {
+ String msg = "Unable to find the file: " + throttlingConfigFile + ".";
+ log.error(msg, e);
+ throw new Exception(msg, e);
+ }
+ }
+
+ public void deserialize(OMElement throttlingConfigEle) throws Exception {
+ Iterator meteringConfigChildIt = throttlingConfigEle.getChildElements();
+ while (meteringConfigChildIt.hasNext()) {
+ Object meteringConfigChild = meteringConfigChildIt.next();
+ if (!(meteringConfigChild instanceof OMElement)) {
+ continue;
+ }
+ OMElement meteringConfigChildEle = (OMElement) meteringConfigChild;
+ if (new QName(CONFIG_NS, PARAMTERS_ELEMENT_NAME, "").equals(meteringConfigChildEle
+ .getQName())) {
+ Iterator parametersChildIt = meteringConfigChildEle.getChildElements();
+ while (parametersChildIt.hasNext()) {
+ Object taskConfigChild = parametersChildIt.next();
+ if (!(taskConfigChild instanceof OMElement)) {
+ continue;
+ }
+ OMElement parameterChildEle = (OMElement) taskConfigChild;
+ if (!new QName(CONFIG_NS, PARAMTER_ELEMENT_NAME, "").equals(parameterChildEle
+ .getQName())) {
+ continue;
+ }
+ String parameterName =
+ parameterChildEle.getAttributeValue(new QName(PARAMTER_NAME_ATTR_NAME));
+ String parameterValue = parameterChildEle.getText();
+ parameters.put(parameterName, parameterValue);
+ }
+ }
+ }
+ }
+
+ public Map<String, String> getParameters() {
+ return parameters;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/internal/ThrottlingAgentServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/internal/ThrottlingAgentServiceComponent.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/internal/ThrottlingAgentServiceComponent.java
new file mode 100644
index 0000000..161ae37
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/internal/ThrottlingAgentServiceComponent.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.internal;
+
+import org.apache.stratos.throttling.agent.cache.Axis2ConfigurationContextObserverImpl;
+import org.apache.stratos.throttling.agent.cache.ThrottlingInfoCache;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.apache.stratos.throttling.agent.ThrottlingAgent;
+import org.apache.stratos.throttling.agent.listeners.WebAppRequestListener;
+import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
+import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.apache.stratos.common.util.StratosConfiguration;
+
+import java.util.ArrayList;
+
+/**
+ * @scr.component name="org.wso2.carbon.throttling.agent"
+ * immediate="true"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
+ * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="1..1" policy="dynamic" bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ * @scr.reference name="stratos.config.service"
+ * interface="org.apache.stratos.common.util.StratosConfiguration" cardinality="1..1"
+ * policy="dynamic" bind="setStratosConfigurationService" unbind="unsetStratosConfigurationService"
+ */
+public class ThrottlingAgentServiceComponent {
+ private static Log log = LogFactory.getLog(ThrottlingAgentServiceComponent.class);
+
+ private static ThrottlingAgent throttlingAgent;
+ private static RealmService realmService;
+ private static RegistryService registryService;
+ private static ConfigurationContextService contextService;
+ private static StratosConfiguration stratosConfiguration;
+
+ protected void activate(ComponentContext context) {
+ try {
+ BundleContext bundleContext = context.getBundleContext();
+ throttlingAgent = new ThrottlingAgent(bundleContext);
+ throttlingAgent.setConfigurationContextService(contextService);
+ throttlingAgent.setRealmService(realmService);
+ throttlingAgent.setRegistryService(registryService);
+ throttlingAgent.setStratosConfiguration(stratosConfiguration);
+
+ try {
+ // Throttling agent initialization require registry service.
+ throttlingAgent.init();
+ } catch (RegistryException e) {
+ String errMessage = "Failed to initialize throttling agent.";
+ log.error(errMessage, e);
+ throw new RuntimeException(errMessage, e);
+ }
+
+ if("true".equals(ServerConfiguration.getInstance().getFirstProperty("EnableMetering"))){
+ // Register the Tomcat Valve
+ ArrayList<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>();
+ valves.add(new WebAppRequestListener(throttlingAgent));
+ TomcatValveContainer.addValves(valves);
+
+ registerAxis2ConfigurationContextObserver(bundleContext, throttlingAgent.getThrottlingInfoCache());
+ }else{
+ log.debug("WebAppRequestListener valve was not added because metering is disabled in the configuration");
+ log.debug("Axis2ConfigurationContextObserver was not registered because metering is disabled");
+ }
+
+ registerThrottlingAgent(bundleContext);
+
+ log.debug("Multitenancy Throttling Agent bundle is activated.");
+ } catch (Throwable e) {
+ log.error("Multitenancy Throttling Agent bundle failed activating.", e);
+ }
+
+ }
+
+ private void registerAxis2ConfigurationContextObserver(BundleContext bundleContext, ThrottlingInfoCache cache) {
+ bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
+ new Axis2ConfigurationContextObserverImpl(cache),
+ null);
+ }
+
+ /**
+ * Register throttling agent service that use to update throttling rules when users try to
+ * upgrade down grade usage plans
+ *
+ * @param bundleContext bundle context that need to initialize throttling agent
+ */
+ public void registerThrottlingAgent(BundleContext bundleContext) {
+ try {
+ bundleContext.registerService(ThrottlingAgent.class.getName(),
+ throttlingAgent,
+ null);
+ }
+ catch (Exception e) {
+
+ }
+ }
+
+ protected void deactivate(ComponentContext context) {
+ //Util.uninitializeThrottlingRuleInvokerTracker();
+ log.debug("******* Multitenancy Throttling Agent bundle is deactivated ******* ");
+ }
+
+ protected void setRegistryService(RegistryService registryService) {
+ ThrottlingAgentServiceComponent.registryService = registryService;
+ }
+
+ protected void unsetRegistryService(RegistryService registryService) {
+ ThrottlingAgentServiceComponent.registryService = null;
+ throttlingAgent.setRegistryService(null);
+ }
+
+ protected void setRealmService(RealmService realmService) {
+ ThrottlingAgentServiceComponent.realmService = realmService;
+ }
+
+ protected void unsetRealmService(RealmService realmService) {
+ ThrottlingAgentServiceComponent.realmService = null;
+ throttlingAgent.setRealmService(null);
+ }
+
+ protected void setConfigurationContextService(ConfigurationContextService contextService) {
+ ThrottlingAgentServiceComponent.contextService = contextService;
+
+ //this module is not necessary when we have the WebAppRequestListerner.
+ //It takes care of webapps and services. But this is not working for ESb
+ //When a solution for ESB is found, this module can be engaged again
+ /*try {
+ contextService.getServerConfigContext().getAxisConfiguration().engageModule(
+ "usagethrottling");
+ } catch (AxisFault e) {
+ log.error("Failed to engage usage throttling module", e);
+ }*/
+ }
+
+ protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+ /*try {
+ AxisConfiguration axisConfig =
+ contextService.getServerConfigContext().getAxisConfiguration();
+ axisConfig.disengageModule(axisConfig.getModule("usagethrottling"));
+ } catch (AxisFault e) {
+ log.error("Failed to disengage usage throttling module", e);
+ }*/
+ ThrottlingAgentServiceComponent.contextService = null;
+ throttlingAgent.setConfigurationContextService(null);
+ }
+
+ public static ThrottlingAgent getThrottlingAgent() {
+ return throttlingAgent;
+ }
+
+ protected void setStratosConfigurationService(StratosConfiguration stratosConfigService) {
+ ThrottlingAgentServiceComponent.stratosConfiguration=stratosConfigService;
+ }
+
+ protected void unsetStratosConfigurationService(StratosConfiguration ccService) {
+ ThrottlingAgentServiceComponent.stratosConfiguration = null;
+ throttlingAgent.setStratosConfiguration(null);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerRegistryRequestListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerRegistryRequestListener.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerRegistryRequestListener.java
new file mode 100644
index 0000000..826cc76
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerRegistryRequestListener.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.listeners;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.config.RegistryContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.jdbc.handlers.Handler;
+import org.wso2.carbon.registry.core.jdbc.handlers.HandlerManager;
+import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
+import org.wso2.carbon.registry.core.jdbc.handlers.filters.Filter;
+import org.wso2.carbon.registry.core.jdbc.handlers.filters.URLMatcher;
+import org.wso2.carbon.registry.core.session.CurrentSession;
+import org.apache.stratos.throttling.agent.cache.TenantThrottlingInfo;
+import org.apache.stratos.throttling.agent.cache.ThrottlingActionInfo;
+import org.apache.stratos.throttling.agent.internal.ThrottlingAgentServiceComponent;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+public class PerRegistryRequestListener extends Handler {
+
+ private static final Log log = LogFactory.getLog(PerRegistryRequestListener.class);
+
+ @Override
+ public void put(RequestContext context) throws RegistryException {
+ validateRegistryAction(StratosConstants.THROTTLING_IN_DATA_ACTION);
+ }
+
+ @Override
+ public void importResource(RequestContext context) throws RegistryException {
+ validateRegistryAction(StratosConstants.THROTTLING_IN_DATA_ACTION);
+ }
+
+ @Override
+ public Resource get(RequestContext context) throws RegistryException {
+ validateRegistryAction(StratosConstants.THROTTLING_OUT_DATA_ACTION);
+ return null;
+ }
+
+ @Override
+ public void dump(RequestContext requestContext) throws RegistryException {
+ validateRegistryAction(StratosConstants.THROTTLING_OUT_DATA_ACTION);
+ }
+
+ @Override
+ public void restore(RequestContext requestContext) throws RegistryException {
+ validateRegistryAction(StratosConstants.THROTTLING_IN_DATA_ACTION);
+ }
+
+ private void validateRegistryAction(String action) throws RegistryException {
+ if (CurrentSession.getCallerTenantId() == MultitenantConstants.SUPER_TENANT_ID
+ || CurrentSession.getTenantId() == MultitenantConstants.SUPER_TENANT_ID) {
+ // no limitations for the super tenant
+ return;
+ }
+ if (CarbonConstants.REGISTRY_SYSTEM_USERNAME.equals(CurrentSession.getUser()) ||
+ CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(CurrentSession.getUser())) {
+ // skipping tracking for anonymous and system user
+ return;
+ }
+
+ // called only once per request..
+ if (CurrentSession.getAttribute(StratosConstants.REGISTRY_ACTION_VALIDATED_SESSION_ATTR) != null) {
+ return;
+ }
+ CurrentSession.setAttribute(StratosConstants.REGISTRY_ACTION_VALIDATED_SESSION_ATTR, true);
+
+ int tenantId = CurrentSession.getTenantId();
+
+ TenantThrottlingInfo tenantThrottlingInfo =
+ ThrottlingAgentServiceComponent.getThrottlingAgent().getThrottlingInfoCache()
+ .getTenantThrottlingInfo(tenantId);
+ if(tenantThrottlingInfo!=null){
+ ThrottlingActionInfo actionInfo = tenantThrottlingInfo.getThrottlingActionInfo(action);
+
+ if (actionInfo != null && actionInfo.isBlocked()) {
+ String blockedMsg = actionInfo.getMessage();
+ String msg =
+ "The throttling action is blocked. message: " + blockedMsg + ", action: " +
+ action + ".";
+ log.error(msg);
+ // we are only throwing the blocked exception, as it is a error
+ // message for the user
+ throw new RegistryException(blockedMsg);
+ }
+ }
+ }
+
+ public static void registerPerRegistryRequestListener(RegistryContext registryContext) {
+ HandlerManager handlerManager = registryContext.getHandlerManager();
+ PerRegistryRequestListener storeBandwidthHandler = new PerRegistryRequestListener();
+ URLMatcher anyUrlMatcher = new URLMatcher();
+ anyUrlMatcher.setPattern(".*");
+ String[] applyingFilters =
+ new String[] { Filter.PUT, Filter.IMPORT, Filter.GET, Filter.DUMP, Filter.RESTORE, };
+
+ handlerManager.addHandlerWithPriority(
+ applyingFilters, anyUrlMatcher, storeBandwidthHandler);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerUserAddListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerUserAddListener.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerUserAddListener.java
new file mode 100644
index 0000000..f4ec4be
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/PerUserAddListener.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.listeners;
+
+import org.apache.stratos.throttling.agent.cache.ThrottlingActionInfo;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.throttling.agent.cache.TenantThrottlingInfo;
+import org.apache.stratos.throttling.agent.internal.ThrottlingAgentServiceComponent;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.common.AbstractUserStoreManagerListener;
+import org.wso2.carbon.user.core.listener.AuthorizationManagerListener;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.util.Map;
+
+public class PerUserAddListener extends AbstractUserStoreManagerListener {
+ private static final Log log = LogFactory.getLog(PerUserAddListener.class);
+
+ public int getExecutionOrderId() {
+ return AuthorizationManagerListener.MULTITENANCY_USER_RESTRICTION_HANDLER;
+ }
+
+ @Override
+ public boolean addUser(String userName, Object credential, String[] roleList,
+ Map<String, String> claims, String profileName, UserStoreManager userStoreManager)
+ throws UserStoreException {
+
+ //If this is not a cloud deployment there is no way to run the throttling rules
+ //This means the product is being used in the tenant mode
+ //Therefore we can ommit running the throttling rules
+ if("false".equals(ServerConfiguration.getInstance().getFirstProperty(CarbonConstants.IS_CLOUD_DEPLOYMENT))){
+ log.info("Omitting executing throttling rules becasue this is not a cloud deployment.");
+ return true;
+ }
+ int tenantId = userStoreManager.getTenantId();
+ if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+ return true;
+ }
+ // running the rules invoking the remote throttling manager.
+ String[] users = userStoreManager.listUsers("*", -1);
+ if (users.length <= 1) {
+ // no filtering if the users count < 1
+ return true;
+ }
+
+ try {
+ ThrottlingAgentServiceComponent.getThrottlingAgent().executeManagerThrottlingRules(tenantId);
+ ThrottlingAgentServiceComponent.getThrottlingAgent().updateThrottlingCacheForTenant();
+ } catch (Exception e1) {
+ String msg = "Error in executing the throttling rules in manager.";
+ log.error(msg + " tenantId: " + tenantId + ".", e1);
+ throw new UserStoreException(msg, e1);
+ }
+ TenantThrottlingInfo throttlingInfo = ThrottlingAgentServiceComponent.getThrottlingAgent()
+ .getThrottlingInfoCache().getTenantThrottlingInfo(tenantId);
+ if(throttlingInfo!=null){
+ ThrottlingActionInfo actionInfo = throttlingInfo.getThrottlingActionInfo(StratosConstants.THROTTLING_ADD_USER_ACTION);
+
+ if (actionInfo!=null && actionInfo.isBlocked()) {
+ String blockedMsg = actionInfo.getMessage();
+ String msg = "The add user action is blocked. message: " + blockedMsg + ".";
+ log.error(msg);
+ // we are only throwing the blocked exception, as it is a error message for the user
+ throw new UserStoreException(blockedMsg);
+ }
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ServiceRequestListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ServiceRequestListener.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ServiceRequestListener.java
new file mode 100644
index 0000000..5498b86
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ServiceRequestListener.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.listeners;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.handlers.AbstractHandler;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.core.transports.metering.MeteredServletRequest;
+import org.apache.stratos.throttling.agent.cache.ThrottlingActionInfo;
+import org.apache.stratos.throttling.agent.cache.ThrottlingInfoCache;
+import org.apache.stratos.throttling.agent.internal.ThrottlingAgentServiceComponent;
+
+/**
+ * Checks whether the axis2 operations (service calls) are allowed.
+ */
+public class ServiceRequestListener extends AbstractHandler {
+ private static final Log log = LogFactory.getLog(ServiceRequestListener.class);
+
+ public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {
+ if (log.isDebugEnabled()) {
+ log.debug("Staring throttling handler invocation. Incoming message: " +
+ messageContext.getEnvelope().toString());
+ }
+ AxisService service = messageContext.getAxisService();
+ Parameter param = service.getParameter("adminService");
+
+ if (param != null && "true".equals(param.getValue())) {
+ //We will allow admin services to proceed.
+ return InvocationResponse.CONTINUE;
+ }
+
+ int tenantId = getTenantId(messageContext);
+ if(tenantId <= 0){
+ //We can allow all super tenant actions
+ return InvocationResponse.CONTINUE;
+ }
+
+ ThrottlingInfoCache throttlingInfoCache = ThrottlingAgentServiceComponent.getThrottlingAgent().getThrottlingInfoCache();
+ String[] actions = new String[]{StratosConstants.THROTTLING_SERVICE_IN_BANDWIDTH_ACTION,
+ StratosConstants.THROTTLING_SERVICE_OUT_BANDWIDTH_ACTION,
+ StratosConstants.THROTTLING_SERVICE_REQUEST_ACTION,
+ StratosConstants.THROTTLING_SERVICE_RESPONSE_ACTION
+ };
+ ThrottlingActionInfo actionInfo = throttlingInfoCache.getTenantThrottlingInfo(tenantId).getThrottlingActionInfo(actions);
+
+ if (actionInfo.isBlocked()) {
+ String blockedMsg = actionInfo.getMessage();
+ String msg = "The throttling action is blocked. message: " + blockedMsg;
+ log.error(msg);
+ // we are only throwing the blocked exception, as it is a error message for the user
+ throw new AxisFault(blockedMsg);
+ }
+
+ return InvocationResponse.CONTINUE;
+ }
+
+ private int getTenantId(MessageContext messageContext) {
+ Object obj = messageContext.getProperty("transport.http.servletRequest");
+ if (obj == null) {
+ // TODO: check for cause of the error.
+ log.debug("Servlet request is null. Skip monitoring.");
+ return 0;
+ }
+ if (!(obj instanceof MeteredServletRequest)) {
+ log.debug("HttpServletRequest is not of type MeteredServletRequest. Skip monitoring.");
+ return 0;
+ }
+
+ MeteredServletRequest servletRequest = (MeteredServletRequest) obj;
+ String address = servletRequest.getRequestURI();
+ String servicesPrefix = "/services/t/";
+ if (address != null && address.contains(servicesPrefix)) {
+ int domainNameStartIndex =
+ address.indexOf(servicesPrefix) + servicesPrefix.length();
+ int domainNameEndIndex = address.indexOf('/', domainNameStartIndex);
+ String domainName = address.substring(domainNameStartIndex,
+ domainNameEndIndex == -1 ? address.length() : domainNameEndIndex);
+
+ // return tenant id if domain name is not null
+ if (domainName != null) {
+ try {
+ return ThrottlingAgentServiceComponent.getThrottlingAgent().getRealmService().getTenantManager().getTenantId(domainName);
+ } catch (org.wso2.carbon.user.api.UserStoreException e) {
+ log.error("An error occurred while obtaining the tenant id.", e);
+ }
+ }
+ }
+
+ // return 0 if the domain name is null
+ return 0;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/767082e3/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ThrottlingModule.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ThrottlingModule.java b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ThrottlingModule.java
new file mode 100644
index 0000000..04d956d
--- /dev/null
+++ b/components/org.apache.stratos.throttling.agent/src/main/java/org/apache/stratos/throttling/agent/listeners/ThrottlingModule.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.throttling.agent.listeners;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisDescription;
+import org.apache.axis2.description.AxisModule;
+import org.apache.axis2.modules.Module;
+import org.apache.neethi.Assertion;
+import org.apache.neethi.Policy;
+
+/**
+ *
+ */
+public class ThrottlingModule implements Module {
+
+ public void applyPolicy(Policy arg0, AxisDescription arg1) throws AxisFault {
+ }
+
+ public boolean canSupportAssertion(Assertion arg0) {
+ return true;
+ }
+
+ public void engageNotify(AxisDescription arg0) throws AxisFault {
+ }
+
+ public void init(ConfigurationContext arg0, AxisModule arg1) throws AxisFault {
+ }
+
+ public void shutdown(ConfigurationContext arg0) throws AxisFault {
+ }
+
+}