http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/api/CustomMeteringAgent.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/api/CustomMeteringAgent.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/api/CustomMeteringAgent.java deleted file mode 100644 index 9b63790..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/api/CustomMeteringAgent.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - *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.usage.agent.api; - -import org.apache.stratos.usage.agent.exception.UsageException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.registry.core.*; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.apache.stratos.common.constants.UsageConstants; - -/** - * CustomMeteringAgent is used to get recorded duration, to check whether usage entry exists, - * to persist and retrieve usage. - */ - -public class CustomMeteringAgent { - private static final Log log = LogFactory.getLog(CustomMeteringAgent.class); - private Registry registry; - - /** - * Constructor for the custom metering agent - * - * @param registry governance registry of super tenant - */ - public CustomMeteringAgent(Registry registry) { - this.registry = registry; - } - - /** - * Get recorded durations - * @param measurement the measurement to get the duration - * @return the durations array - * @throws org.apache.stratos.usage.agent.exception.UsageException - */ - public String[] getRecordedDurations(String measurement) throws UsageException { - String[] durations; - String measurementCollectionPath = - UsageConstants.CUSTOM_METERING_PATH + RegistryConstants.PATH_SEPARATOR + - measurement; - try { - Resource resource = registry.get(measurementCollectionPath); - if (!(resource instanceof Collection)) { - String msg = - "The records collection is not a registry collection. path: " + - measurementCollectionPath + "."; - log.error(msg); - throw new UsageException(msg); - } - durations = ((Collection) resource).getChildren(); - } catch (RegistryException e) { - String msg = - "Error in checking the usage entry exists. measurement: " + measurement + "."; - log.error(msg, e); - throw new UsageException(msg, e); - } - return durations; - } - - /** - * Check whether the usage entry exist or not - * - * @param duration the duration (e.g. year month), null for any duration - * @param measurement measurement key - * @return true if usage entry exists - * @throws org.apache.stratos.usage.agent.exception.UsageException - */ - public boolean isUsageEntryExists(String duration, String measurement) - throws UsageException { - if (duration == null) { - duration = UsageConstants.ANY_DURATION; - } - String measurementPath = - UsageConstants.CUSTOM_METERING_PATH + RegistryConstants.PATH_SEPARATOR + - measurement + - RegistryConstants.PATH_SEPARATOR + duration; - try { - if (registry.resourceExists(measurementPath)) { - return true; - } - } catch (RegistryException e) { - String msg = - "Error in checking the usage entry exists. measurement: " + measurement + "."; - log.error(msg, e); - throw new UsageException(msg, e); - } - return false; - } - - /** - * Persist usage of a user - * - * @param duration the duration (e.g. year month), null for any duration - * @param measurement measurement key - * @param value measurement value - * @throws org.apache.stratos.usage.agent.exception.UsageException - */ - public void persistUsage(String duration, String measurement, String value) - throws UsageException { - if (duration == null) { - duration = UsageConstants.ANY_DURATION; - } - Resource measurementResource; - String measurementPath = - UsageConstants.CUSTOM_METERING_PATH + RegistryConstants.PATH_SEPARATOR + - measurement + - RegistryConstants.PATH_SEPARATOR + duration; - try { - measurementResource = registry.newResource(); - ((ResourceImpl) measurementResource).setVersionableChange(false); - // save the measurement value in resource - measurementResource.setContent(value); - registry.put(measurementPath, measurementResource); - } catch (RegistryException e) { - String msg = - "Error in persisting the usage. measurement: " + - measurement + "."; - log.error(msg, e); - throw new UsageException(msg, e); - } - } - - /** - * Retrieve usage of a user - * - * @param duration the duration (e.g. year month), null for any duration - * @param measurement measurement key - * @return measurement value - * @throws org.apache.stratos.usage.agent.exception.UsageException - */ - public String retrieveUsage(String duration, String measurement) - throws UsageException { - String usageValue; - Resource measurementResource; - String measurementPath = - UsageConstants.CUSTOM_METERING_PATH + RegistryConstants.PATH_SEPARATOR + - measurement + - RegistryConstants.PATH_SEPARATOR + duration; - try { - measurementResource = registry.get(measurementPath); - // save the measurement value in resource - byte[] contentBytes = (byte[]) measurementResource.getContent(); - usageValue = new String(contentBytes); - } catch (RegistryException e) { - String msg = - "Error in retrieving the usage. measurement: " + - measurement + "."; - log.error(msg, e); - throw new UsageException(msg, e); - } - return usageValue; - } - - /** - * Add a long value to the usage, if there were no previous entry, this will - * start with value 0 - * - * @param duration the duration (e.g. year month), null for any duration - * @param measurement measurement key - * @param value measurement value - * @return the added measurement value - * @throws org.apache.stratos.usage.agent.exception.UsageException - */ - public long addUsage(String duration, String measurement, long value) - throws UsageException { - if (duration == null) { - duration = UsageConstants.ANY_DURATION; - } - // adding the bandwidth have to be in a transaction - boolean transactionSuccess = false; - try { - registry.beginTransaction(); - if (isUsageEntryExists(duration, measurement)) { - String usageStr = retrieveUsage(duration, measurement); - try { - long storedValue = Long.parseLong(usageStr); - value += storedValue; - } catch (NumberFormatException e) { - String msg = "Error in parsing the integer string: " + usageStr; - log.error(msg, e); - throw new RegistryException(msg, e); - } - } - String valueStr = Long.toString(value); - persistUsage(duration, measurement, valueStr); - transactionSuccess = true; - } catch (RegistryException e) { - String msg = - "Error in invoking the add usage. measurement: " + - measurement + "."; - log.error(msg, e); - throw new UsageException(msg, e); - } finally { - try { - if (transactionSuccess) { - registry.commitTransaction(); - } else { - registry.rollbackTransaction(); - } - } catch (RegistryException e) { - String msg = "Error in commiting/rollbacking the transaction"; - log.error(msg, e); - } - } - return value; - } -}
http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/APIManagerRequestStats.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/APIManagerRequestStats.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/APIManagerRequestStats.java deleted file mode 100644 index 62d33b6..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/APIManagerRequestStats.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - *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.usage.agent.beans; - -public class APIManagerRequestStats { - private int requestCount; - private int responseCount; - private int faultCount; - private long responseTime; - private int tenantId; - private String measurement; - private long value; - - public APIManagerRequestStats() { - requestCount = 0; - responseCount = 0; - faultCount = 0; - responseTime = 0; - measurement = "APICall"; - value = 0; - tenantId = 0; - } - - public String getMeasurement() { - return measurement; - } - - public void setMeasurement(String measurement) { - this.measurement = measurement; - } - - - public long getValue() { - return value; - } - - public void setValue(long value) { - this.value = value; - } - - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public int getRequestCount() { - return requestCount; - } - - public void setRequestCount(int requestCount) { - this.requestCount = requestCount; - } - - public int getResponseCount() { - return responseCount; - } - - public void setResponseCount(int responseCount) { - this.responseCount = responseCount; - } - - public int getFaultCount() { - return faultCount; - } - - public void setFaultCount(int faultCount) { - this.faultCount = faultCount; - } - - public long getResponseTime() { - return responseTime; - } - - public void setResponseTime(long responseTime) { - this.responseTime = responseTime; - } - - -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/BandwidthUsage.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/BandwidthUsage.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/BandwidthUsage.java deleted file mode 100644 index 5d2481d..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/beans/BandwidthUsage.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - *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.usage.agent.beans; - -/** - * the bean class for BandwidthUsage with attributes - * int tenant id, - * String measurement - * long value * - */ - -public class BandwidthUsage { - private int tenantId; - private String measurement; - private long value; - - - public String getMeasurement() { - return measurement; - } - - public BandwidthUsage(int tenantId, String measurement, long value) { - this.tenantId = tenantId; - this.measurement = measurement; - this.value = value; - } - - public long getValue() { - return value; - } - - public void setValue(long value) { - this.value = value; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public int getTenantId() { - return tenantId; - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/config/UsageAgentConfiguration.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/config/UsageAgentConfiguration.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/config/UsageAgentConfiguration.java deleted file mode 100644 index d31ebe1..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/config/UsageAgentConfiguration.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - *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.usage.agent.config; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.impl.builder.StAXOMBuilder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -public class UsageAgentConfiguration { - private static final Log log = LogFactory.getLog(UsageAgentConfiguration.class); - - private static final Integer DEFAULT_NUMBER_OF_RECORDS_PER_RUN = 100; - private static final Integer DEFAULT_EXECUTION_INTERVAL_IN_MILLISECONDS = 100; - private static final Integer DEFAULT_STARTUP_DELAY_IN_MILLISECONDS = 60000; - - private int usageTasksNumberOfRecordsPerExecution = -1; - - private int usageTasksExecutionIntervalInMilliSeconds = -1; - - private int usageTasksStartupDelayInMilliSeconds = -1; - - public UsageAgentConfiguration(File configFile) { - if (configFile.exists()) { - try { - OMElement usageAndThrottlingAgentConfiguration = - new StAXOMBuilder(new FileInputStream(configFile)).getDocumentElement(); - if (usageAndThrottlingAgentConfiguration != null) { - OMElement usageAgent = usageAndThrottlingAgentConfiguration.getFirstChildWithName( - new QName("http://wso2.com/carbon/multitenancy/usage-throttling-agent/config", "UsageAgent")); - if (usageAgent != null) { - OMElement usageDataPersistenceTaskConfig = usageAgent.getFirstChildWithName( - new QName("http://wso2.com/carbon/multitenancy/usage-throttling-agent/config", - "UsageDataPersistenceTask")); - if (usageDataPersistenceTaskConfig != null) { - OMElement numberOfRecordsPerExecutionEle = usageDataPersistenceTaskConfig.getFirstChildWithName( - new QName("http://wso2.com/carbon/multitenancy/usage-throttling-agent/config", - "NumberOfRecordsPerExecution")); - if (numberOfRecordsPerExecutionEle != null && numberOfRecordsPerExecutionEle.getText() != null && - numberOfRecordsPerExecutionEle.getText().length() > 0) { - try { - usageTasksNumberOfRecordsPerExecution = Integer.parseInt(numberOfRecordsPerExecutionEle.getText()); - } catch (NumberFormatException ne) { - log.error("Error while parsing usage persistence task number of records value.", ne); - } - } - - OMElement executionIntervalInMilliSeconds = usageDataPersistenceTaskConfig.getFirstChildWithName( - new QName("http://wso2.com/carbon/multitenancy/usage-throttling-agent/config", - "ExecutionIntervalInMilliSeconds")); - if (executionIntervalInMilliSeconds != null && executionIntervalInMilliSeconds.getText() != null && - executionIntervalInMilliSeconds.getText().length() > 0) { - try { - usageTasksExecutionIntervalInMilliSeconds = - Integer.parseInt(executionIntervalInMilliSeconds.getText()); - } catch (NumberFormatException ne) { - log.error("Error while parsing usage persistence task execution interval value.", ne); - } - } - - OMElement startupDelayInMilliSeconds = usageDataPersistenceTaskConfig.getFirstChildWithName( - new QName("http://wso2.com/carbon/multitenancy/usage-throttling-agent/config", - "StartupDelayInMilliSeconds")); - if (startupDelayInMilliSeconds != null && startupDelayInMilliSeconds.getText() != null && - startupDelayInMilliSeconds.getText().length() > 0) { - try { - usageTasksStartupDelayInMilliSeconds = - Integer.parseInt(startupDelayInMilliSeconds.getText()); - } catch (NumberFormatException ne) { - log.error("Error while parsing usage persistence task startup delay value.", ne); - } - } - } - } - } - - } catch (FileNotFoundException e) { - log.error("Cannot find " + configFile.getAbsolutePath(), e); - } catch (XMLStreamException e) { - log.error("Error reading XML stream of file " + configFile.getAbsolutePath(), e); - } - } - } - - public int getUsageTasksNumberOfRecordsPerExecution() { - return usageTasksNumberOfRecordsPerExecution; - } - - public int getUsageTasksExecutionIntervalInMilliSeconds() { - return usageTasksExecutionIntervalInMilliSeconds; - } - - public int getUsageTasksStartupDelayInMilliSeconds() { - return usageTasksStartupDelayInMilliSeconds; - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/exception/UsageException.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/exception/UsageException.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/exception/UsageException.java deleted file mode 100644 index 06f2dbe..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/exception/UsageException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - *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.usage.agent.exception; - -/** - * UsageException class to handle usage exception - */ -public class UsageException extends Exception { - public UsageException(String msg, Exception e) { - super(msg, e); - } - public UsageException(String msg) { - super(msg); - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/internal/UsageAgentServiceComponent.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/internal/UsageAgentServiceComponent.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/internal/UsageAgentServiceComponent.java deleted file mode 100644 index ea8ca29..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/internal/UsageAgentServiceComponent.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - *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.usage.agent.internal; - -import org.apache.stratos.usage.agent.listeners.UsageStatsAxis2ConfigurationContextObserver; -import org.apache.stratos.usage.agent.util.PublisherUtils; -import org.apache.stratos.usage.agent.util.Util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.base.api.ServerConfigurationService; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.event.core.EventBroker; -import org.wso2.carbon.statistics.services.SystemStatisticsUtil; -import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; -import org.wso2.carbon.utils.ConfigurationContextService; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -/** - * this class is used to activate and deactivate the UsageAgentServiceComponent, set and unset - * Serverconfigurarion, set and unset EventBrokerService. - * - * @scr.component name="org.wso2.carbon.usage.agent" immediate="true" - * @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="0..1" - * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService" - * @scr.reference name="server.configuration" - * interface="org.wso2.carbon.base.api.ServerConfigurationService" cardinality="1..1" - * policy="dynamic" bind="setServerConfiguration" unbind="unsetServerConfiguration" - * @scr.reference name="eventbroker.service" - * interface="org.wso2.carbon.event.core.EventBroker" cardinality="1..1" - * policy="dynamic" bind="setEventBrokerService" unbind="unsetEventBrokerService" - * @scr.reference name="org.wso2.carbon.statistics.services" - * interface="org.wso2.carbon.statistics.services.SystemStatisticsUtil" - * cardinality="0..1" policy="dynamic" bind="setSystemStatisticsUtil" unbind="unsetSystemStatisticsUtil" - */ -public class UsageAgentServiceComponent { - private static Log log = LogFactory.getLog(UsageAgentServiceComponent.class); - - /** - * method to activate UsageAgentServiceComponent - * - * @param context componentContext - */ - protected void activate(ComponentContext context) { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getCurrentContext().setTenantId( - MultitenantConstants.SUPER_TENANT_ID); - PrivilegedCarbonContext.getCurrentContext().getTenantDomain(true); - PrivilegedCarbonContext.getCurrentContext().setUsername( - CarbonConstants.REGISTRY_SYSTEM_USERNAME); - PrivilegedCarbonContext.getCurrentContext().setUserRealm( - Util.getRealmService().getBootstrapRealm()); - - // initialize listeners - // currently we have RegistryUsagePersistingListener only - Util.initializeAllListeners(); - - //initialize persistenceManager for persisting BandwidthUsage - Util.initializePersistenceManager(); - - // create statistic event subscription - Util.createStaticEventSubscription(); - - if("true".equals(ServerConfiguration.getInstance().getFirstProperty("EnableMetering"))){ - //PublisherUtils.defineUsageEventStream(); - - UsageStatsAxis2ConfigurationContextObserver statObserver = new UsageStatsAxis2ConfigurationContextObserver(); - context.getBundleContext().registerService(Axis2ConfigurationContextObserver.class.getName(), statObserver, null); - log.info("Observer to register the module for request statistics publishing was registered"); - } - - // register the request data persistor osgi service so that we can - // store service request bandwidths - // TODO: Remove this and ServiceDataPersistor after fixing ESB metering -// context.getBundleContext().registerService( -// RequestDataPersister.class.getName(), new ServiceDataPersistor(), null); - - log.debug("******* Multitenancy Usage Agent bundle is activated ******* "); - } catch (Throwable e) { - log.error("******* Failed to activate Multitenancy Usage Agent bundle ****", e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - - /** - * method to deactivate bundle - * - * @param context ComponentContext - */ - protected void deactivate(ComponentContext context) { - log.debug("******* Multitenancy Metering Usage Agent bundle is deactivated ******* "); - } - - /** - * method to set RealmService - * - * @param realmService RealmService - */ - protected void setRealmService(RealmService realmService) { - Util.setRealmService(realmService); - } - - /** - * method to unsetRealmService - * - * @param realmService RealmService - */ - - protected void unsetRealmService(RealmService realmService) { - Util.setRealmService(null); - } - - /** - * method to set ConfigurationContextService - * - * @param contextService ConfigurationContextService - */ - protected void setConfigurationContextService(ConfigurationContextService contextService) { - Util.setConfigurationContextService(contextService); - PublisherUtils.setConfigurationContextService(contextService); - } - - /** - * method to unset ConfigurationContextService - * - * @param contextService ConfigurationContextService - */ - protected void unsetConfigurationContextService(ConfigurationContextService contextService) { - Util.setConfigurationContextService(null); - } - - /** - * method to set server configurations - * - * @param serverConfiguration ServerConfiguration - */ - protected void setServerConfiguration(ServerConfigurationService serverConfiguration) { - Util.setServerConfiguration(serverConfiguration); - } - - /** - * method to unset server configurations - * - * @param serverConfiguration ServerConfiguration - */ - protected void unsetServerConfiguration(ServerConfigurationService serverConfiguration) { - Util.setServerConfiguration(null); - } - - /** - * method to set EventBrokerService - * - * @param registryEventBrokerService EventBroker - */ - - protected void setEventBrokerService(EventBroker registryEventBrokerService) { - Util.setEventBrokerService(registryEventBrokerService); - } - - /** - * method to unset EventBrokerService - * - * @param registryEventBrokerService EventBroker - */ - protected void unsetEventBrokerService(EventBroker registryEventBrokerService) { - Util.setEventBrokerService(null); - } - - public static void setSystemStatisticsUtil(SystemStatisticsUtil systemStatisticsUtil){ - Util.setSystemStatisticsUtil(systemStatisticsUtil); - } - - public static void unsetSystemStatisticsUtil(SystemStatisticsUtil systemStatisticsUtil){ - Util.setSystemStatisticsUtil(null); - } - -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsageListener.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsageListener.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsageListener.java deleted file mode 100644 index f84e727..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsageListener.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - *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.usage.agent.listeners; - -import org.apache.stratos.usage.agent.persist.RegistryUsagePersister; -import org.apache.stratos.usage.agent.util.MonitoredReader; -import org.apache.stratos.usage.agent.util.MonitoredWriter; -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.wso2.carbon.registry.core.*; -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.HandlerLifecycleManager; -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.wso2.carbon.registry.core.utils.RegistryUtils; -import org.apache.stratos.common.constants.StratosConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.Writer; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -/** - * Handler that intercept the registry calls - */ -public class RegistryUsageListener extends Handler { - - private static final Log log = LogFactory.getLog(RegistryUsageListener.class); - - public void put(RequestContext context) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - ResourcePath path = context.getResourcePath(); - Resource resource = context.getResource(); - ((ResourceImpl) resource).setPath(path.getCompletePath()); - if (resource instanceof CollectionImpl) { - return; - } - Object contentObj = resource.getContent(); - if (contentObj == null) { - return; - } - int size; - if (contentObj instanceof String) { - size = ((String) contentObj).length(); - } else if (contentObj instanceof byte[]) { - size = ((byte[]) contentObj).length; - } else { - String msg = "Unsupported type for the content."; - log.error(msg); - throw new RegistryException(msg); - } - - - // persisting bandwidth - //RegistryUsagePersister.storeIncomingBandwidth(tenantId, size); - //persisting to registry content addition - RegistryUsagePersister.storeAddContent(tenantId, size); - - //we will pass through, so that normal registry operation will put the resource - } - - public void importResource(RequestContext context) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - -// ResourcePath resourcePath = context.getResourcePath(); - String sourceURL = context.getSourceURL(); - - - // the import resource logic - URL url; - try { - if (sourceURL != null && sourceURL.toLowerCase().startsWith("file:")) { - String msg = "The source URL must not be file in the server's local file system"; - throw new RegistryException(msg); - } - url = new URL(sourceURL); - } catch (MalformedURLException e) { - String msg = "Given source URL " + sourceURL + "is not valid."; - throw new RegistryException(msg, e); - } - - try { - URLConnection uc = url.openConnection(); - InputStream in = uc.getInputStream(); - byte[] inByteArr = RegistryUtils.getByteArray(in); - int size = inByteArr.length; - - // persisting bandwidth - //RegistryUsagePersister.storeIncomingBandwidth(tenantId, size); - - } catch (IOException e) { - - String msg = "Could not read from the given URL: " + sourceURL; - throw new RegistryException(msg, e); - } - } - - public Resource get(RequestContext context) throws RegistryException { - if (CurrentSession.getCallerTenantId() == MultitenantConstants.SUPER_TENANT_ID || - CurrentSession.getTenantId() == MultitenantConstants.SUPER_TENANT_ID) { - // no limitations for the super tenant - return null; - } - if (CarbonConstants.REGISTRY_SYSTEM_USERNAME.equals(CurrentSession.getUser()) || - CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(CurrentSession.getUser())) { - // skipping tracking for anonymous and system user - return null; - } - // called only once per request.. - if (CurrentSession.getAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return null; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - - // get the resource - Resource resource = context.getResource(); - if (resource == null) { - ResourcePath resourcePath = context.getResourcePath(); - Registry registry = context.getRegistry(); - if (registry.resourceExists(resourcePath.getPath())) { - resource = registry.get(resourcePath.getPath()); - context.setResource(resource); - context.setProcessingComplete(true); // nothing else to do. - } - } - if (resource == null) { - return null; - } - if (resource instanceof CollectionImpl) { - return resource; - } - Object contentObj = resource.getContent(); - if (contentObj == null) { - return resource; - } - int size; - if (contentObj instanceof String) { - size = ((String) contentObj).length(); - } else if (contentObj instanceof byte[]) { - size = ((byte[]) contentObj).length; - } else { - String msg = "Unsupported type for the content."; - log.error(msg); - throw new RegistryException(msg); - } - // persisting bandwidth - //RegistryUsagePersister.storeOutgoingBandwidth(tenantId, size); - return resource; - } - - public void dump(RequestContext requestContext) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - long size = requestContext.getBytesWritten(); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - if (size == 0) { - //Still not dumped - Registry registry = requestContext.getRegistry(); - String path = requestContext.getResourcePath().getPath(); - Writer writer = requestContext.getDumpingWriter(); - // we wrap the writer with the monitored writer - MonitoredWriter monitoredWriter = new MonitoredWriter(writer); - registry.dump(path, monitoredWriter); - size = monitoredWriter.getTotalWritten(); - requestContext.setProcessingComplete(true); - } - - // persisting bandwidth - //RegistryUsagePersister.storeOutgoingBandwidth(tenantId, size); - - } - - public void restore(RequestContext requestContext) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - long size = requestContext.getBytesRead(); - - if (size == 0) { - //not restored yet - Registry registry = requestContext.getRegistry(); - String path = requestContext.getResourcePath().getPath(); - Reader reader = requestContext.getDumpingReader(); - // we wrap the reader with the monitored reader - MonitoredReader monitoredReader = new MonitoredReader(reader); - registry.restore(path, monitoredReader); - size = monitoredReader.getTotalRead(); - requestContext.setProcessingComplete(true); - } - // persisting bandwidth - //RegistryUsagePersister.storeIncomingBandwidth(tenantId, size); - - } - - public static void registerRegistryUsagePersistingListener(RegistryContext registryContext) - throws RegistryException { - - //If metering is disabled, we do not need to register the handler - if(!"true".equals(ServerConfiguration.getInstance().getFirstProperty("EnableMetering"))){ - return; - } - - HandlerManager handlerManager = registryContext.getHandlerManager(); - RegistryUsageListener handler = new RegistryUsageListener(); - URLMatcher anyUrlMatcher = new URLMatcher(); - anyUrlMatcher.setPattern(".*"); - String[] applyingFilters = new String[]{ - Filter.PUT, Filter.IMPORT, Filter.GET, Filter.DUMP, Filter.RESTORE, Filter.DELETE}; - - handlerManager.addHandlerWithPriority(applyingFilters, anyUrlMatcher, handler, - HandlerLifecycleManager.DEFAULT_REPORTING_HANDLER_PHASE); - } - - //=========================================================================================== - public void delete(RequestContext context) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - ResourcePath path = context.getResourcePath(); - Resource resource = context.getRegistry().get(path.getCompletePath()); - Object contentObj = resource.getContent(); - if (contentObj == null) { - return; - } - int size = 0; - if (contentObj instanceof String) { - size = ((String) contentObj).length(); - } else if (contentObj instanceof byte[]) { - size = ((byte[]) contentObj).length; - } else if (contentObj instanceof String[]) { - // of type collection - for (String str : (String[]) contentObj) { - size += str.length(); - } - } else { - String msg = "Unsupported type for the content."; - log.error(msg); - throw new RegistryException(msg); - } - RegistryUsagePersister.storeDeleteContent(tenantId, size); - - //we will pass through, so that normal registry operation will put the resource - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsagePersistingListener.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsagePersistingListener.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsagePersistingListener.java deleted file mode 100644 index 8ea0ac1..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/RegistryUsagePersistingListener.java +++ /dev/null @@ -1,311 +0,0 @@ -/* - *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.usage.agent.listeners; - -import org.apache.stratos.usage.agent.persist.BandwidthPersistor; -import org.apache.stratos.usage.agent.util.MonitoredReader; -import org.apache.stratos.usage.agent.util.MonitoredWriter; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.registry.core.*; -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.RequestContext; -import org.wso2.carbon.registry.core.session.CurrentSession; -import org.wso2.carbon.registry.core.utils.RegistryUtils; -import org.apache.stratos.common.constants.StratosConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.Writer; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -/** - * Handler that intercept the registry calls - * Currently this handler is not registered because there is a similar handler RegistryUsageHandler - * After examining properly this class will be deleted. - */ -public class RegistryUsagePersistingListener extends Handler { - - private static final Log log = LogFactory.getLog(RegistryUsagePersistingListener.class); - - public void put(RequestContext context) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - ResourcePath path = context.getResourcePath(); - Resource resource = context.getResource(); - ((ResourceImpl) resource).setPath(path.getCompletePath()); - if (resource instanceof CollectionImpl) { - return; - } - Object contentObj = resource.getContent(); - if (contentObj == null) { - return; - } - int size; - if (contentObj instanceof String) { - size = ((String) contentObj).length(); - } else if (contentObj instanceof byte[]) { - size = ((byte[]) contentObj).length; - } else { - String msg = "Unsupported type for the content."; - log.error(msg); - throw new RegistryException(msg); - } - - - // persisting bandwidth - BandwidthPersistor.storeIncomingBandwidth(tenantId, size); - - //we will pass through, so that normal registry operation will put the resource - } - - public void importResource(RequestContext context) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - -// ResourcePath resourcePath = context.getResourcePath(); - String sourceURL = context.getSourceURL(); - - - // the import resource logic - URL url; - try { - if (sourceURL != null && sourceURL.toLowerCase().startsWith("file:")) { - String msg = "The source URL must not be file in the server's local file system"; - throw new RegistryException(msg); - } - url = new URL(sourceURL); - } catch (MalformedURLException e) { - String msg = "Given source URL " + sourceURL + "is not valid."; - throw new RegistryException(msg, e); - } - - try { - URLConnection uc = url.openConnection(); - InputStream in = uc.getInputStream(); - byte[] inByteArr = RegistryUtils.getByteArray(in); - int size = inByteArr.length; - - // persisting bandwidth - BandwidthPersistor.storeIncomingBandwidth(tenantId, size); - - } catch (IOException e) { - - String msg = "Could not read from the given URL: " + sourceURL; - throw new RegistryException(msg, e); - } - } - - public Resource get(RequestContext context) throws RegistryException { - if (CurrentSession.getCallerTenantId() == MultitenantConstants.SUPER_TENANT_ID || - CurrentSession.getTenantId() == MultitenantConstants.SUPER_TENANT_ID) { - // no limitations for the super tenant - return null; - } - if (CarbonConstants.REGISTRY_SYSTEM_USERNAME.equals(CurrentSession.getUser()) || - CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(CurrentSession.getUser())) { - // skipping tracking for anonymous and system user - return null; - } - // called only once per request.. - if (CurrentSession.getAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return null; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - - // get the resource - Resource resource = context.getResource(); - if (resource == null) { - ResourcePath resourcePath = context.getResourcePath(); - Registry registry = context.getRegistry(); - if (registry.resourceExists(resourcePath.getPath())) { - resource = registry.get(resourcePath.getPath()); - context.setResource(resource); - context.setProcessingComplete(true); // nothing else to do. - } - } - if (resource == null) { - return null; - } - if (resource instanceof CollectionImpl) { - return resource; - } - Object contentObj = resource.getContent(); - if (contentObj == null) { - return resource; - } - int size; - if (contentObj instanceof String) { - size = ((String) contentObj).length(); - } else if (contentObj instanceof byte[]) { - size = ((byte[]) contentObj).length; - } else { - String msg = "Unsupported type for the content."; - log.error(msg); - throw new RegistryException(msg); - } - // persisting bandwidth - BandwidthPersistor.storeOutgoingBandwidth(tenantId, size); - return resource; - } - - public void dump(RequestContext requestContext) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - long size = requestContext.getBytesWritten(); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - - if (size == 0) { - //Still not dumped - Registry registry = requestContext.getRegistry(); - String path = requestContext.getResourcePath().getPath(); - Writer writer = requestContext.getDumpingWriter(); - // we wrap the writer with the monitored writer - MonitoredWriter monitoredWriter = new MonitoredWriter(writer); - registry.dump(path, monitoredWriter); - size = monitoredWriter.getTotalWritten(); - requestContext.setProcessingComplete(true); - } - - // persisting bandwidth - BandwidthPersistor.storeOutgoingBandwidth(tenantId, size); - - } - - public void restore(RequestContext requestContext) 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_USAGE_PERSISTED_SESSION_ATTR) - != null) { - return; - } - CurrentSession.setAttribute(StratosConstants.REGISTRY_USAGE_PERSISTED_SESSION_ATTR, true); - - // pre triggering - int tenantId = CurrentSession.getTenantId(); - long size = requestContext.getBytesRead(); - - if (size == 0) { - //not restored yet - Registry registry = requestContext.getRegistry(); - String path = requestContext.getResourcePath().getPath(); - Reader reader = requestContext.getDumpingReader(); - // we wrap the reader with the monitored reader - MonitoredReader monitoredReader = new MonitoredReader(reader); - registry.restore(path, monitoredReader); - size = monitoredReader.getTotalRead(); - requestContext.setProcessingComplete(true); - } - // persisting bandwidth - BandwidthPersistor.storeIncomingBandwidth(tenantId, size); - - } - - public static void registerRegistryUsagePersistingListener(RegistryContext registryContext) - throws RegistryException { - - //This was commented out because there is a similar class RegistryUsageListener - //After examiming properly this class will be deleted - /*HandlerManager handlerManager = registryContext.getHandlerManager(); - RegistryUsagePersistingListener handler = new RegistryUsagePersistingListener(); - URLMatcher anyUrlMatcher = new URLMatcher(); - anyUrlMatcher.setPattern(".*"); - String[] applyingFilters = new String[]{ - Filter.PUT, Filter.IMPORT, Filter.GET, Filter.DUMP, Filter.RESTORE,}; - - handlerManager.addHandlerWithPriority(applyingFilters, anyUrlMatcher, handler, - HandlerLifecycleManager.DEFAULT_REPORTING_HANDLER_PHASE); - */ - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsInHandler.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsInHandler.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsInHandler.java deleted file mode 100644 index d8ecb66..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsInHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - *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.usage.agent.listeners; - - -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.description.AxisService; -import org.apache.axis2.engine.Handler; -import org.apache.axis2.handlers.AbstractHandler; -import org.apache.stratos.usage.agent.util.PublisherUtils; -import org.apache.stratos.usage.agent.util.Util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.core.util.SystemFilter; -import org.wso2.carbon.statistics.services.util.SystemStatistics; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -public class StatisticsInHandler extends AbstractHandler{ - private static Log log = LogFactory.getLog(StatisticsOutHandler.class); - - public InvocationResponse invoke(MessageContext messageContext) throws AxisFault { - AxisService axisService = messageContext.getAxisService(); - if(axisService== null || SystemFilter.isFilteredOutService(axisService.getAxisServiceGroup()) || - axisService.isClientSide()){ - return InvocationResponse.CONTINUE; - } - - if(Util.getSystemStatisticsUtil()==null){ - return InvocationResponse.CONTINUE; - } - - SystemStatistics systemStatistics = Util.getSystemStatisticsUtil().getSystemStatistics(messageContext); - - int tenantId = MultitenantConstants.INVALID_TENANT_ID; - tenantId = CarbonContext.getCurrentContext().getTenantId(); - - if(tenantId == MultitenantConstants.INVALID_TENANT_ID || - tenantId == MultitenantConstants.SUPER_TENANT_ID) { - return Handler.InvocationResponse.CONTINUE; - } - - try { - PublisherUtils.publish(systemStatistics, tenantId); - } catch (Exception e) { - //Logging the complete stacktrace in debug mode - if(log.isDebugEnabled()){ - log.debug(e); - } - - log.error("Error occurred while publishing request statistics. Full stacktrace available in debug logs. " + e.getMessage()); - } - - return InvocationResponse.CONTINUE; - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsOutHandler.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsOutHandler.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsOutHandler.java deleted file mode 100644 index 9f61518..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/StatisticsOutHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - *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.usage.agent.listeners; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.description.AxisService; -import org.apache.axis2.engine.Handler; -import org.apache.axis2.handlers.AbstractHandler; -import org.apache.stratos.usage.agent.util.Util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.core.util.SystemFilter; -import org.wso2.carbon.statistics.services.util.SystemStatistics; -import org.apache.stratos.usage.agent.util.PublisherUtils; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - - -public class StatisticsOutHandler extends AbstractHandler{ - - private static Log log = LogFactory.getLog(StatisticsOutHandler.class); - - public InvocationResponse invoke(MessageContext messageContext) throws AxisFault { - - - AxisService axisService = messageContext.getAxisService(); - if(axisService== null || SystemFilter.isFilteredOutService(axisService.getAxisServiceGroup()) || - axisService.isClientSide()){ - - PrivilegedCarbonContext.destroyCurrentContext(); - return InvocationResponse.CONTINUE; - } - - if(Util.getSystemStatisticsUtil()==null){ - - PrivilegedCarbonContext.destroyCurrentContext(); - return InvocationResponse.CONTINUE; - } - SystemStatistics systemStatistics = Util.getSystemStatisticsUtil().getSystemStatistics(messageContext); - - int tenantId = MultitenantConstants.INVALID_TENANT_ID; - tenantId = CarbonContext.getCurrentContext().getTenantId(); - - if(tenantId == MultitenantConstants.INVALID_TENANT_ID || - tenantId == MultitenantConstants.SUPER_TENANT_ID) { - - PrivilegedCarbonContext.destroyCurrentContext(); - return Handler.InvocationResponse.CONTINUE; - } - - try { - PublisherUtils.publish(systemStatistics, tenantId); - } catch (Exception e) { - //Logging the complete stacktrace in debug mode - if(log.isDebugEnabled()){ - log.debug(e); - } - - log.error("Error occurred while publishing request statistics. Full stacktrace available in debug logs. " + e.getMessage()); - } - - PrivilegedCarbonContext.destroyCurrentContext(); - return InvocationResponse.CONTINUE; - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/UsageStatsAxis2ConfigurationContextObserver.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/UsageStatsAxis2ConfigurationContextObserver.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/UsageStatsAxis2ConfigurationContextObserver.java deleted file mode 100644 index 152442b..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/UsageStatsAxis2ConfigurationContextObserver.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - *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.usage.agent.listeners; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.engine.AxisConfiguration; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver; - - -public class UsageStatsAxis2ConfigurationContextObserver extends AbstractAxis2ConfigurationContextObserver { - - private static final Log log = LogFactory.getLog(UsageStatsAxis2ConfigurationContextObserver.class); - - @Override - public void createdConfigurationContext(ConfigurationContext configContext) { - - AxisConfiguration axisConfiguration = configContext.getAxisConfiguration(); - int tenantId = PrivilegedCarbonContext.getCurrentContext().getTenantId(false); - try { - axisConfiguration.engageModule("metering"); - } catch (AxisFault axisFault) { - log.error("Could not engage metering module for tenant: " + tenantId, axisFault); - } - - - } - -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringHandler.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringHandler.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringHandler.java deleted file mode 100644 index 09a5f78..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - *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.usage.agent.listeners.axis2; - -import org.apache.stratos.usage.agent.util.Util; -import org.apache.stratos.common.constants.StratosConstants; -import org.wso2.carbon.core.transports.metering.MeteredServletRequest; - -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; - -/** - * this class is used to obtain tenant id from MeteredServletRequest or MessageContext - */ - -public class RequestMeteringHandler extends AbstractHandler { - private static final Log log = LogFactory.getLog(RequestMeteringHandler.class); - - /** - * this method invoke MeteredServletRequest and return a InvocationResponse - * @param messageContext MessageContext - * @return InvocationResponse - * @throws AxisFault - */ - - public InvocationResponse invoke(MessageContext messageContext) throws AxisFault { - if (log.isDebugEnabled()) { - log.debug("Staring metering handler invocation. Incoming message: " + - messageContext.getEnvelope().toString()); - } - AxisService service = messageContext.getAxisService(); - Parameter param = service.getParameter("adminService"); - - 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 InvocationResponse.CONTINUE; - } - if (!(obj instanceof MeteredServletRequest)) { - log.debug("HttpServletRequest is not of type MeteredServletRequest. Skip monitoring."); - return InvocationResponse.CONTINUE; - } - - MeteredServletRequest servletRequest = (MeteredServletRequest) obj; - - if (param != null && "true".equals(param.getValue())) { - servletRequest.setAttribute(StratosConstants.ADMIN_SERVICE_SERVLET_ATTR, "true"); - return InvocationResponse.CONTINUE; - } - servletRequest.setAttribute(StratosConstants.SERVICE_NAME_SERVLET_ATTR, service.getName()); - - int tenantId = getTenantId(servletRequest); - servletRequest.setAttribute(StratosConstants.TENANT_ID_SERVLET_ATTR, tenantId); - - return InvocationResponse.CONTINUE; - } - - /** - * method to get tenant id from MeteredServletRequest - * @param servletRequest MeteredServletRequest - * @return tenant id - */ - - private int getTenantId(MeteredServletRequest servletRequest) { - 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 Util.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/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringModule.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringModule.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringModule.java deleted file mode 100644 index 6d1bb2f..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/listeners/axis2/RequestMeteringModule.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - *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.usage.agent.listeners.axis2; - -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 RequestMeteringModule implements Module { - - public void init(ConfigurationContext configurationContext, AxisModule axisModule) - throws AxisFault { - } - - public void engageNotify(AxisDescription axisDescription) throws AxisFault { - } - - public boolean canSupportAssertion(Assertion assertion) { - return true; - } - - public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault { - } - - public void shutdown(ConfigurationContext configurationContext) throws AxisFault { - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/ee5e9639/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/persist/BandwidthPersistor.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/persist/BandwidthPersistor.java b/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/persist/BandwidthPersistor.java deleted file mode 100644 index d99fd3c..0000000 --- a/components/org.apache.stratos.usage.agent/src/main/java/org/apache/stratos/usage/agent/persist/BandwidthPersistor.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - *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.usage.agent.persist; - -import org.apache.stratos.common.constants.UsageConstants; -import org.apache.stratos.usage.agent.beans.BandwidthUsage; -import org.apache.stratos.usage.agent.util.Util; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -/** - * this class is used to store incoming and outgoing bandwidth - */ - -public class BandwidthPersistor { - - /** - * method to store incoming bandwidth - * @param tenantId tenant id - * @param size value of the incoming bandwidth - */ - - public static void storeIncomingBandwidth(int tenantId, long size) { - if ((MultitenantConstants.SUPER_TENANT_ID!=tenantId) && (size > 0)) { - BandwidthUsage usage = new BandwidthUsage( - tenantId, UsageConstants.REGISTRY_INCOMING_BW, size); - Util.addToPersistingControllerQueue(usage); - } - } - - /** - * method to store outgoingBandwidth - * @param tenantId tenant id - * @param size value of the outgoing bandwidth - */ - public static void storeOutgoingBandwidth(int tenantId, long size) { - if ((MultitenantConstants.SUPER_TENANT_ID!=tenantId) && (size > 0)) { - BandwidthUsage usage = new BandwidthUsage( - tenantId, UsageConstants.REGISTRY_OUTGOING_BW, size); - Util.addToPersistingControllerQueue(usage); - } - } -}
