You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by is...@apache.org on 2013/07/10 18:51:52 UTC

[17/45] fixing component version issues and adding currently refactored components to the parent pom

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
new file mode 100644
index 0000000..607aa27
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
@@ -0,0 +1,58 @@
+/*
+ * 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.common.constants;
+
+public class UsageConstants {
+    final public static String ANY_DURATION = "anyDuration";
+
+    public static final String SYSTEM_METERING_PATH =
+            "/repository/components/org.wso2.carbon.system-metering";
+
+    public static final String CUSTOM_METERING_PATH =
+        "/repository/components/org.wso2.carbon.system-metering";
+
+    // the measurements
+    final public static String CAPACITY_USAGE = "capacity-usage";
+    
+    final public static String SERVICE_REQUEST_COUNT = "serviceRequestCount";
+    final public static String SERVICE_RESPONSE_COUNT = "serviceResponseCount";
+    final public static String SERVICE_FAULT_COUNT = "serviceFaultCount";
+    
+    public static final String BANDWIDTH_KEY_PATTERN = "%Bandwidth%";
+    public static final String REGISTRY_BANDWIDTH = "RegistryBandwidth";
+    public static final String SERVICE_BANDWIDTH = "ServiceBandwidth";
+    public static final String WEBAPP_BANDWIDTH = "WebappBandwidth";
+    public static final String IN_LABLE = "-In";
+    public static final String OUT_LABLE = "-Out";
+    public static final String REGISTRY_CONTENT_BANDWIDTH = "ContentBandwidth";
+    
+    final public static String REGISTRY_INCOMING_BW = REGISTRY_BANDWIDTH + IN_LABLE;
+    final public static String REGISTRY_OUTGOING_BW = REGISTRY_BANDWIDTH + OUT_LABLE;
+    final public static String REGISTRY_TOTAL_BW = "registry-total-bw-usage";
+    final public static String NUMBER_OF_USERS = "number-of-users";
+
+    final public static String SERVICE_INCOMING_BW = SERVICE_BANDWIDTH + IN_LABLE;
+    final public static String SERVICE_OUTGOING_BW = SERVICE_BANDWIDTH + OUT_LABLE;
+    final public static String SERVICE_TOTAL_BW = "serviceRequestTotalBw";
+    
+    final public static String WEBAPP_INCOMING_BW = WEBAPP_BANDWIDTH + IN_LABLE;
+    final public static String WEBAPP_OUTGOING_BW = WEBAPP_BANDWIDTH + OUT_LABLE;
+
+    final public static String API_CALL_COUNT = "apiCallCount";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java
new file mode 100644
index 0000000..8be9f89
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java
@@ -0,0 +1,42 @@
+/*
+ * 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.common.exception;
+
+/**
+ * This class is defined as the general Exception implementation for Stratos. This can be used
+ * within Stratos components when handling exceptions.
+ */
+public class StratosException extends Exception{
+
+    public StratosException() {
+    }
+
+    public StratosException(String message) {
+        super(message);
+    }
+
+    public StratosException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public StratosException(Throwable cause) {
+        super(cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
new file mode 100644
index 0000000..e43c9a6
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
@@ -0,0 +1,139 @@
+/*
+ * 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.common.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.packages.PackageInfoHolder;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.common.util.StratosConfiguration;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+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.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+/**
+ * @scr.component name="apache.stratos.common" 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"
+ */
+public class CloudCommonServiceComponent {
+
+    private static Log log = LogFactory.getLog(CloudCommonServiceComponent.class);
+
+    private static BundleContext bundleContext;
+    private static RealmService realmService;
+    private static RegistryService registryService;
+    private static PackageInfoHolder packageInfos;
+
+    protected void activate(ComponentContext context) {
+        try {
+            bundleContext = context.getBundleContext();
+            if (CommonUtil.getStratosConfig() == null) {
+                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
+                CommonUtil.setStratosConfig(stratosConfig);
+            }
+
+            // Loading the EULA
+            if (CommonUtil.getEula() == null) {
+                String eula = CommonUtil.loadTermsOfUsage();
+                CommonUtil.setEula(eula);
+            }
+            
+			packageInfos = new PackageInfoHolder();
+			context.getBundleContext().registerService(
+					PackageInfoHolder.class.getName(), packageInfos, null);
+
+            //Register manager configuration OSGI service
+            try {
+                StratosConfiguration stratosConfiguration = CommonUtil.loadStratosConfiguration();
+                bundleContext.registerService(StratosConfiguration.class.getName(), stratosConfiguration, null);
+                if (log.isDebugEnabled()) {
+                    log.debug("******* Cloud Common Service bundle is activated ******* ");
+                }
+            } catch (Exception ex) {
+                String msg = "An error occurred while initializing Cloud Common Service as an OSGi Service";
+                log.error(msg, ex);
+            }
+        } catch (Throwable e) {
+            log.error("Error in activating Cloud Common Service Component" + e.toString());
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Tenant Core bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        CloudCommonServiceComponent.registryService = registryService;
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        CloudCommonServiceComponent.realmService = realmService;
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        setRealmService(null);
+    }
+
+    public static BundleContext getBundleContext() {
+        return bundleContext;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getConfigSystemRegistry(tenantId);
+    }
+
+	public static PackageInfoHolder getPackageInfos() {
+		return packageInfos;
+	}
+
+    
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
new file mode 100644
index 0000000..4a9a316
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
@@ -0,0 +1,43 @@
+/*
+ * 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.common.listeners;
+
+
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+
+public interface TenantMgtListener {
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException;
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException;
+
+    public void onTenantRename(int tenantId, String oldDomainName, 
+                             String newDomainName)throws StratosException;
+    
+    public void onTenantInitialActivation(int tenantId) throws StratosException;
+    
+    public void onTenantActivation(int tenantId) throws StratosException;
+    
+    public void onTenantDeactivation(int tenantId) throws StratosException;
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
+                                         String newPlan) throws StratosException;
+    
+    public int getListenerOrder();
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
new file mode 100644
index 0000000..f20a6cd
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
@@ -0,0 +1,111 @@
+/*
+ * 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.common.packages;
+
+/*
+ * Deserialize following XML
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="multitenancy-free">
+        <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+        <users>
+            <limit>5</limit>
+            <charge>0</charge> <!-- charge per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit> <!--mb per user -->
+        </resourceVolume>
+        <bandwidth>
+            <limit>1000</limit> <!-- mb per user -->
+            <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-small">
+        ...
+    </package>
+</packages>
+ */
+public class PackageInfo {
+	
+	private String name;
+	private int usersLimit;
+	private int subscriptionCharge;
+	private int chargePerUser;
+	private int resourceVolumeLimit;
+	private int bandwidthLimit;
+	private int bandwidthOveruseCharge;
+
+	
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public int getUsersLimit() {
+		return usersLimit;
+	}
+
+	public void setUsersLimit(int usersLimit) {
+		this.usersLimit = usersLimit;
+	}
+
+	public int getSubscriptionCharge() {
+		return subscriptionCharge;
+	}
+
+	public void setSubscriptionCharge(int subscriptionCharge) {
+		this.subscriptionCharge = subscriptionCharge;
+	}
+
+	public int getChargePerUser() {
+		return chargePerUser;
+	}
+
+	public void setChargePerUser(int chargePerUser) {
+		this.chargePerUser = chargePerUser;
+	}
+
+	public int getResourceVolumeLimit() {
+		return resourceVolumeLimit;
+	}
+
+	public void setResourceVolumeLimit(int resourceVolumeLimit) {
+		this.resourceVolumeLimit = resourceVolumeLimit;
+	}
+
+	public int getBandwidthLimit() {
+		return bandwidthLimit;
+	}
+
+	public void setBandwidthLimit(int bandwidthLimit) {
+		this.bandwidthLimit = bandwidthLimit;
+	}
+
+	public int getBandwidthOveruseCharge() {
+		return bandwidthOveruseCharge;
+	}
+
+	public void setBandwidthOveruseCharge(int bandwidthOveruseCharge) {
+		this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+	}
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
new file mode 100644
index 0000000..68fc5da
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
@@ -0,0 +1,164 @@
+/*
+ * 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.common.packages;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.util.CommonUtil;
+import org.jaxen.JaxenException;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class PackageInfoHolder {
+    private static Log log = LogFactory.getLog(PackageInfoHolder.class);
+    private static final String PACKAGE_DESCRIPTION_CONFIG = "multitenancy-packages.xml";
+    private static final String PACKAGE_DESCRIPTION_CONFIG_NS =
+            "http://wso2.com/carbon/multitenancy/billing/pacakges";
+    
+    List<PackageInfo> multitenancyPackages = new ArrayList<PackageInfo>();
+
+    public PackageInfoHolder() throws StratosException {
+        multitenancyPackages = deserializePackageDescriptionConfig();
+    }
+
+    public List<PackageInfo> getMultitenancyPackages() {
+        return multitenancyPackages;
+    }
+
+    /*
+     * Deserialize following XML
+    <packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+        <package name="multitenancy-free">
+            <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+            <users>
+                <limit>5</limit>
+                <charge>0</charge> <!-- charge per month -->
+            </users>
+            <resourceVolume>
+                <limit>10</limit> <!--mb per user -->
+            </resourceVolume>
+            <bandwidth>
+                <limit>1000</limit> <!-- mb per user -->
+                <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+            </bandwidth>
+        </package>
+        <package name="multitenancy-small">
+            ...
+        </package>
+    </packages>
+     */
+    private List<PackageInfo> deserializePackageDescriptionConfig() throws StratosException {
+        String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                PACKAGE_DESCRIPTION_CONFIG;
+        
+        OMElement packageConfigs;
+        try {
+            packageConfigs = CommonUtil.buildOMElement(new FileInputStream(configFilePath));
+        } catch (Exception e) {
+            String msg = "Error in deserializing the packageConfigs file: " + configFilePath + ".";
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+
+        @SuppressWarnings("unchecked")
+        Iterator<OMElement> packageConfigsChildsIt = packageConfigs.getChildElements();
+        while (packageConfigsChildsIt.hasNext()) {
+            OMElement packageConfigEle = packageConfigsChildsIt.next();
+            if (!new QName(PACKAGE_DESCRIPTION_CONFIG_NS, "package").equals(
+                    packageConfigEle.getQName())) {
+                continue;
+            }
+            
+            PackageInfo multitenancyPackage = new PackageInfo();
+            String packageName = packageConfigEle.getAttributeValue(new QName("name"));
+            String subscriptionCharge = getPackageConfigValue("subscriptionCharge", packageConfigEle);
+            String usersLimit = getPackageConfigValue("users.limit", packageConfigEle);
+            String usersCharge = getPackageConfigValue("users.charge", packageConfigEle);
+
+            String resourceVolumeLimit =
+                    getPackageConfigValue("resourceVolume.limit", packageConfigEle);
+            String resourceVolumeOveruseCharge =
+                    getPackageConfigValue("resourceVolume.overuseCharge", packageConfigEle);
+            String bandwidthLimit = getPackageConfigValue("bandwidth.limit", packageConfigEle);
+            String bandwidthOveruseCharge =
+                    getPackageConfigValue("bandwidth.overuseCharge", packageConfigEle);
+            int usersLimitInt = -1;
+            if (!usersLimit.equals("unlimited")) {
+                usersLimitInt = Integer.parseInt(usersLimit);
+            }
+            int resourceVolumeLimitInt = -1;
+            if (!resourceVolumeLimit.equals("unlimited")) {
+                resourceVolumeLimitInt = Integer.parseInt(resourceVolumeLimit);
+            }
+            int bandwidthLimitInt = -1;
+            if (!bandwidthLimit.equals("unlimited")) {
+                bandwidthLimitInt = Integer.parseInt(bandwidthLimit);
+            }
+
+            multitenancyPackage.setName(packageName);
+            //In the PackageInfo class subscriptionCharge, chargeperUser and bandwidthOverUsageCharge
+            //are declared as Integers. I think it is better to change them to float. If somebody
+            //enters a float value to the conf file it will cause an exception here
+            multitenancyPackage.setSubscriptionCharge(Integer.parseInt(subscriptionCharge));
+            multitenancyPackage.setUsersLimit(usersLimitInt);
+       //   multitenancyPackage.setChargePerUser(Integer.parseInt(usersCharge));
+            multitenancyPackage.setResourceVolumeLimit(resourceVolumeLimitInt);
+            multitenancyPackage.setBandwidthLimit(bandwidthLimitInt);
+          //  multitenancyPackage.setBandwidthOveruseCharge(Integer.parseInt(bandwidthOveruseCharge));
+
+            multitenancyPackages.add(multitenancyPackage);
+        }
+        return multitenancyPackages;
+    }
+
+    private String getPackageConfigValue(String key, OMElement packageNode) throws StratosException {
+        String qualifiedKey = "ns:" + key.replaceAll("\\.", "/ns:");
+        AXIOMXPath xpathExpression;
+        try {
+            xpathExpression = new AXIOMXPath(qualifiedKey);
+            xpathExpression.addNamespace("ns", PACKAGE_DESCRIPTION_CONFIG_NS);
+            List valueNodes = xpathExpression.selectNodes(packageNode);
+            if (valueNodes.isEmpty()) {
+                if (log.isDebugEnabled()) {
+                    String msg = "No results found parsing package configuration for key: " + 
+                            qualifiedKey + ".";
+                    log.debug(msg);
+                }
+                return null;
+            }
+            OMElement valueNode = (OMElement) valueNodes.get(0);
+            return valueNode.getText();
+        } catch (JaxenException e) {
+            String msg = "Error in retrieving the key: " + qualifiedKey + ".";
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
new file mode 100644
index 0000000..6ace99f
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
@@ -0,0 +1,35 @@
+/*
+ * 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.common.services;
+
+import org.apache.stratos.common.internal.CloudCommonServiceComponent;
+import org.apache.stratos.common.packages.PackageInfo;
+
+import java.util.List;
+
+
+public class PackageInfoService {
+
+	public PackageInfo[] getPackageInfos() throws Exception {
+		List<PackageInfo> list = CloudCommonServiceComponent.getPackageInfos().
+		                                                     getMultitenancyPackages();
+		PackageInfo[] packageInfos = list.toArray(new PackageInfo[list.size()]);
+		return packageInfos;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
new file mode 100644
index 0000000..d151df9
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
@@ -0,0 +1,278 @@
+/*
+ * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed 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.common.util;
+/*
+ * 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.
+ */
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/*
+ * This class handles the parameters that are input during the registration
+ * which later are
+ * stored as claims.
+ * 
+ * Current claims are:
+ * First Name - GIVEN_NAME
+ * Last Name - SURNAME
+ */
+public class ClaimsMgtUtil {
+
+    private static final Log log = LogFactory.getLog(ClaimsMgtUtil.class);
+
+    /* Methods to get the first and last names from the getNames() */
+    /**
+     * gets first name
+     * 
+     * @param realmService realmService
+     * @param tenantId
+     *            tenant id
+     * @return first name
+     * @throws Exception
+     *             if error in getting the first name
+     */
+    public static String getFirstName(RealmService realmService, int tenantId)throws Exception {
+        String names[] = getNames(realmService, tenantId);
+        return names[0];
+    }
+
+    /**
+     * gets last name
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return last name
+     * @throws Exception
+     *             if error in getting the last name
+     */
+    public static String getLastName(RealmService realmService, int tenantId) throws Exception {
+        String names[] = getNames(realmService, tenantId);
+        return names[1];
+    }
+
+    /**
+     * Gets the first name of a tenant admin to address him/her in the
+     * notifications
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant Id
+     * @return first name / calling name
+     * @throws Exception
+     *             if unable to retrieve the admin name
+     */
+    public static String[] getNames(RealmService realmService, int tenantId) throws Exception {
+        String[] names = new String[2];
+        String firstname = "", lastname = "";
+        try {
+            firstname = getFirstNamefromUserStoreManager(realmService, tenantId);
+        } catch (Exception ignore) {
+            if (log.isDebugEnabled()) {
+                // Not exceptions,due to the existence of tenants with no full name.
+                String msg = "Unable to get the firstname from the user store manager";
+                log.debug(msg, ignore);
+            }
+        }
+        if (firstname != null && !firstname.trim().equals("")) {
+            lastname = getLastNamefromUserStoreManager(realmService, tenantId);
+            if ((lastname != null) && (!lastname.trim().equals(""))) {
+                names[0] = firstname;
+                names[1] = lastname;
+            } else {
+                // no last name - fullname was considered givenname;
+                names = getNamesfromFullName(realmService, firstname);
+            }
+        } else { 
+            // Work around for old tenants - where even full name is not input.
+            if (log.isDebugEnabled()) {
+                log.debug("First name is not available");
+            }
+            try {
+                firstname = getAdminUserNameFromTenantId(realmService, tenantId);
+                names[0] = firstname;
+                names[1] = lastname;
+            } catch (Exception e) {
+                String msg = "Unable to get the admin Name from the user store manager";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        }
+        return names;
+    }
+
+    /**
+     * Method to get the name of the admin user given the tenant id
+     * 
+     * @param tenantId
+     *            tenant id
+     * @return admin user name
+     * @throws Exception
+     *             UserStoreException
+     */
+    public static String getAdminUserNameFromTenantId(RealmService realmService, int tenantId)
+                                                                                              throws Exception {
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return realmService.getBootstrapRealmConfiguration().getAdminUserName();
+        }
+        String tenantAdminName ="";
+        try {
+            if (realmService.getTenantManager().getTenant(tenantId) != null) {
+                tenantAdminName = realmService.getTenantManager().getTenant(tenantId).getAdminName();
+            }
+        } catch (org.wso2.carbon.user.api.UserStoreException e) {
+            String msg = "Unable to retrieve the admin name for the tenant with the tenant Id: " +
+                         tenantId;
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        return tenantAdminName;
+    }
+
+    /**
+     * Let's split the givenname into two.
+     * 
+     * @param fullName
+     *            full name of the tenant admin
+     * @return first name
+     */
+    public static String[] getNamesfromFullName(RealmService realmService, String fullName) {
+        String[] names = new String[0];
+
+        if (!fullName.trim().equals("")) {
+            names = fullName.split(" ", 2); // split by space.
+        }
+        return names; // first entry as the calling name.
+    }
+
+    /**
+     * Get the claims from the user store manager
+     * 
+     * @param tenant
+     *            tenant information
+     * @param tenantId
+     *            tenantId
+     * @param claim
+     *            claim name
+     * @return claim value
+     * @throws org.wso2.carbon.user.core.UserStoreException
+     *             exception in getting the user store manager
+     */
+    public static String getClaimfromUserStoreManager(RealmService realmService, int tenantId,
+                                                      String claim) throws UserStoreException {
+        UserStoreManager userStoreManager = null;
+        String claimValue = "";
+        try {
+            if (realmService.getTenantUserRealm(tenantId) != null) {
+                userStoreManager =
+                        (UserStoreManager) realmService.getTenantUserRealm(tenantId)
+                                .getUserStoreManager();
+            }
+
+        } catch (Exception e) {
+            String msg = "Error retrieving the user store manager for the tenant";
+            log.error(msg, e);
+            throw new UserStoreException(msg, e);
+        }
+        try {
+            if (userStoreManager != null) {
+                claimValue =
+                        userStoreManager.getUserClaimValue(
+                                getAdminUserNameFromTenantId(realmService, tenantId), claim,
+                                UserCoreConstants.DEFAULT_PROFILE);
+            }
+            return claimValue;
+        } catch (Exception e) {
+            String msg = "Unable to retrieve the claim for the given tenant";
+            log.error(msg, e);
+            throw new UserStoreException(msg, e);
+        }
+    }
+
+    /**
+     * Gets first name from the user store manager
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return first name
+     * @throws UserStoreException
+     *             , if error in getting the claim GIVEN_NAME
+     */
+    public static String getFirstNamefromUserStoreManager(RealmService realmService,
+                                                          int tenantId) throws UserStoreException {
+        try {
+            return getClaimfromUserStoreManager(realmService, tenantId,
+                                                UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
+        } catch (Exception e) {
+            String msg = "First Name not found for the tenant";
+            log.debug(msg, e);
+            return ""; // returns empty string
+        }
+    }
+
+    /**
+     * Gets last name from the user store manager
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return last name
+     * @throws UserStoreException
+     *             , if error in getting the claim SURNAME
+     */
+    public static String getLastNamefromUserStoreManager(RealmService realmService,
+                                                         int tenantId) throws UserStoreException {
+        String lastname = "";
+        try {
+            lastname = getClaimfromUserStoreManager(realmService, tenantId,
+                                                    UserCoreConstants.ClaimTypeURIs.SURNAME);
+        } catch (Exception e) {
+            String msg = "Last Name not found for the tenant";
+            log.debug(msg, e);
+        }
+        return lastname; // returns empty string, if couldn't get last name from
+                         // userStore manager
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
new file mode 100644
index 0000000..4108973
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
@@ -0,0 +1,200 @@
+/*
+ * 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.common.util;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.config.CloudServiceConfig;
+import org.apache.stratos.common.config.CloudServicesDescConfig;
+import org.apache.stratos.common.config.PermissionConfig;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.mgt.UserMgtConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+public class CloudServicesUtil {
+
+    private static final Log log = LogFactory.getLog(CloudServicesUtil.class);
+    // TODO protect using Java security
+
+    public static void activateAllServices(CloudServicesDescConfig cloudServicesDesc, int tenantId) throws Exception {
+
+        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
+                                                                          cloudServicesDesc.getCloudServiceConfigs().
+                                                                                            values();
+        if (cloudServiceConfigList != null) {
+            for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
+                if (cloudServiceConfig.isDefaultActive()) {
+                    String cloudServiceName = cloudServiceConfig.getName();
+                    try {
+                        if (!CloudServicesUtil.isCloudServiceActive(cloudServiceName, tenantId)) {
+                            CloudServicesUtil.setCloudServiceActive(true,
+                                                                    cloudServiceName,
+                                                                    tenantId,
+                                                                    cloudServicesDesc.getCloudServiceConfigs().
+                                                                                      get(cloudServiceName));
+                        }
+                    } catch (Exception e) {
+                        String msg = "Error in activating the cloud service at the tenant" +
+                                     "creation. tenant id: " + tenantId + ", service name: " +
+                                     cloudServiceName;
+                        log.error(msg, e);
+                        throw new UserStoreException(msg, e);
+                    }
+                }
+            }
+        }     
+    }
+
+    public static void activateOriginalAndCompulsoryServices(CloudServicesDescConfig cloudServicesDesc,
+                                                             String originalService,
+                                                             int tenantId) throws Exception {
+
+        Map<String, CloudServiceConfig> cloudServiceConfigs =
+                                                              cloudServicesDesc.getCloudServiceConfigs();
+        if (CloudServicesUtil.isServiceNameValid(cloudServicesDesc, originalService)) {
+            if (!CloudServicesUtil.isCloudServiceActive(originalService, tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true, originalService, tenantId,
+                                                        cloudServiceConfigs.get(originalService));
+                log.info("Successfully activated the " + originalService + " for the tenant " +
+                         tenantId);
+            }
+            // register the compulsory services
+            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_IDENTITY_SERVICE,
+                                                        tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true,
+                                                        StratosConstants.CLOUD_IDENTITY_SERVICE,
+                                                        tenantId,
+                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_IDENTITY_SERVICE));
+            }
+            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_GOVERNANCE_SERVICE,
+                                                        tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true,
+                                                        StratosConstants.CLOUD_GOVERNANCE_SERVICE,
+                                                        tenantId,
+                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_GOVERNANCE_SERVICE));
+            }
+        } else {
+            log.warn("Unable to activate the " + originalService + " for the tenant " + tenantId);
+        }
+
+    }
+
+    public static void setCloudServiceActive(boolean active,
+                                             String cloudServiceName,
+                                             int tenantId, CloudServiceConfig cloudServiceConfig)
+                                                                                                 throws Exception {
+        if (cloudServiceConfig.getLabel() == null) {
+            // for the non-labled services, we are not setting/unsetting the
+            // service active
+            return;
+        }
+
+        UserRegistry govRegistry =
+                CloudCommonServiceComponent.getGovernanceSystemRegistry(
+                        MultitenantConstants.SUPER_TENANT_ID);
+        UserRegistry configRegistry = CloudCommonServiceComponent.getConfigSystemRegistry(tenantId);
+        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+                                      RegistryConstants.PATH_SEPARATOR + tenantId +
+                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+        
+        Resource cloudServiceInfoResource;
+        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
+            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
+        } else {
+            cloudServiceInfoResource = govRegistry.newCollection();
+        }
+        cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
+                                             active ? "true" : "false");
+        govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);
+
+        // then we will copy the permissions
+        List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
+        for (PermissionConfig permissionConfig : permissionConfigs) {
+            String path = permissionConfig.getPath();
+            String name = permissionConfig.getName();
+            if (active) {
+                if (!configRegistry.resourceExists(path)) {
+                    Collection collection = configRegistry.newCollection();
+                    collection.setProperty(UserMgtConstants.DISPLAY_NAME, name);
+                    configRegistry.put(path, collection);
+                }
+            } else {
+                if (configRegistry.resourceExists(path)) {
+                    configRegistry.delete(path);
+                }
+            }
+        }
+    }
+
+    public static boolean isCloudServiceActive(String cloudServiceName,
+                                               int tenantId) throws Exception {
+        UserRegistry govRegistry = CloudCommonServiceComponent.getGovernanceSystemRegistry(
+                                                                                           MultitenantConstants.SUPER_TENANT_ID);
+        return isCloudServiceActive(cloudServiceName, tenantId, govRegistry);
+    }
+
+    public static boolean isCloudServiceActive(String cloudServiceName,
+                                               int tenantId, UserRegistry govRegistry)
+                                                                                      throws Exception {
+        // The cloud manager is always active
+        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
+            return true;
+        }
+
+        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+                                      RegistryConstants.PATH_SEPARATOR + tenantId +
+                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+        Resource cloudServiceInfoResource;
+        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
+            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
+            String isActiveStr =
+                                 cloudServiceInfoResource.getProperty(
+                                                         StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
+            return "true".equals(isActiveStr);
+        }
+        return false;
+    }
+
+    public static boolean isServiceNameValid(CloudServicesDescConfig cloudServicesDesc,
+                                               String cloudServiceName) {
+        if(cloudServiceName == null) {
+            return false;
+        }
+        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
+                cloudServicesDesc.getCloudServiceConfigs().values();
+        if (cloudServiceName.equals(StratosConstants.CLOUD_MANAGER_SERVICE)) {
+            return false;
+        }
+        for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
+            if (cloudServiceConfig.getName().equals(cloudServiceName)) {
+                return true;
+            }
+        }
+        return false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java
new file mode 100644
index 0000000..8adf1e4
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java
@@ -0,0 +1,623 @@
+/*
+ * 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.common.util;
+
+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 org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.registry.core.ActionConstants;
+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 org.wso2.carbon.registry.core.utils.AccessControlConstants;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.AuthorizationManager;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.DateFormat;
+import java.text.DateFormatSymbols;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.regex.Pattern;
+
+/**
+ * Common Utility methods for Stratos.
+ * Now this class has been growing with several util methods - Should refactor accordingly.
+ */
+public class CommonUtil {
+    private static final Log log = LogFactory.getLog(CommonUtil.class);
+    private static StratosConfiguration stratosConfig;
+    private static String eula;
+
+
+    private static final String ILLEGAL_CHARACTERS_FOR_EMAIL =
+            ".*[\\(\\)\\<\\>\\,\\;\\:\\\\\\\"\\[\\]].*";
+    private static final String EMAIL_FILTER_STRING = "^[^@]+@[^@.]+\\.[^@]*\\w\\w$";
+    private static Pattern emailFilterPattern = Pattern.compile(EMAIL_FILTER_STRING);
+    private static Pattern illegalCharactersPatternForEmail = Pattern
+            .compile(ILLEGAL_CHARACTERS_FOR_EMAIL);
+
+    public static StratosConfiguration getStratosConfig() {
+        return stratosConfig;
+    }
+
+    public static void setStratosConfig(StratosConfiguration stratosConfig) {
+        CommonUtil.stratosConfig = stratosConfig;
+    }
+
+    public static String getEula() {
+        return eula;
+    }
+
+    public static void setEula(String eula) {
+        CommonUtil.eula = eula;
+    }
+
+    /**
+     * Checks whether the email validation is mandatory from the configuration file.
+     *
+     * @return true, if the email validation is mandatory to login. Default is false.
+     */
+    public static boolean isEmailValidationMandatory() {
+        boolean isEmailValidationMandatory = false; //false by default.
+        if (stratosConfig != null) {   //make sure the configuration exists.
+            isEmailValidationMandatory = stratosConfig.getEmailValidationRequired();
+        }
+        return isEmailValidationMandatory;
+    }
+
+    /**
+     * Checks whether the email sending is enabled from the configuration file.
+     *
+     * @return true, if the email sending is disabled. By default, this is disabled, and tenant
+     * activation is done without any email sending.
+     */
+    public static boolean isTenantManagementEmailsDisabled() {
+        boolean isEmailsDisabled = true; //true by default.
+        if (stratosConfig != null) {   //make sure the configuration exists.
+            isEmailsDisabled = stratosConfig.isEmailsDisabled();
+        }
+        return isEmailsDisabled;
+    }
+
+    public static String getSuperAdminEmail() {
+        return stratosConfig.getSuperAdminEmail();
+    }
+
+    public static String getAdminUserName() {
+        return stratosConfig.getAdminUserName();
+    }
+    
+    public static String getAdminPassword() {
+        return stratosConfig.getAdminPassword();
+    }
+
+    public static boolean isTenantActivationModerated() {
+        return stratosConfig.isTenantActivationModerated();
+    }
+
+    public static boolean isChargedOnRegistration() {
+        return stratosConfig.isChargeOnRegistration();
+    }
+
+    /**
+     * Checks whether it is for the public cloud setup or Mars.
+     *
+     * @return true, if it is not for the private cloud setups. Default is true.
+     */
+    public static boolean isPublicCloudSetup() {
+        boolean isPublicCloudSetup = true;  // true by default.
+        if (stratosConfig != null) { //make sure the configuration exists.
+            isPublicCloudSetup = stratosConfig.isPublicCloudSetup();
+        }
+        return isPublicCloudSetup;
+    }
+
+    /**
+     * Gets the notification email address of the admin upon the tenant creation.
+     *
+     * @return notification email address for the tenant creations.
+     */
+    public static String getNotificationEmailAddress() {
+        String notificationEmailAddress = "";
+        if (stratosConfig != null) {
+            notificationEmailAddress = stratosConfig.getNotificationEmail();
+            try {
+                validateEmail(notificationEmailAddress);
+            } catch (Exception e) {
+                if (log.isWarnEnabled()) {
+                    log.warn("Invalid Email Address provided for tenant creation notification. " +
+                             "Please check whether the parameter NotificationEmail" +
+                             " is set properly in " +
+                             StratosConstants.STRATOS_CONF_FILE, e);
+                }
+                return "";
+            }
+        }
+        return notificationEmailAddress;
+    }
+
+    public static String getMonthString(Calendar calendar) {
+        int currentMonth = calendar.get(Calendar.MONTH);
+
+        String[] monthArr = new DateFormatSymbols().getMonths();
+        String month = monthArr[currentMonth];
+        return calendar.get(Calendar.YEAR) + "-" + month;
+    }
+
+    public static String getMonthString(int relativeMonth) {
+        Calendar newCalendar = Calendar.getInstance();
+        newCalendar.add(Calendar.MONTH, relativeMonth);
+
+        return CommonUtil.getMonthString(newCalendar);
+    }
+
+    public static Date getDateFromMonthString(String yearMonth) throws ParseException {
+        DateFormat yearMonthFormat = new SimpleDateFormat("yyyy-MMM");
+        return yearMonthFormat.parse(yearMonth);
+    }
+
+    public static String getCurrentMonthString() {
+        Calendar newCalendar = Calendar.getInstance();
+
+        return CommonUtil.getMonthString(newCalendar);
+    }
+
+
+    public static void setAnonAuthorization(String path, UserRealm userRealm)
+            throws RegistryException {
+
+        if (userRealm == null) {
+            return;
+        }
+
+        try {
+            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
+            String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;
+
+            accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
+            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
+
+        } catch (UserStoreException e) {
+            String msg = "Could not set authorizations for the " + path + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg);
+        }
+    }
+
+    public static void denyAnonAuthorization(String path, UserRealm userRealm)
+            throws RegistryException {
+        if (userRealm == null) {
+            return;
+        }
+
+        try {
+            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
+            RealmConfiguration realmConfig;
+            try {
+                realmConfig = userRealm.getRealmConfiguration();
+            } catch (UserStoreException e) {
+                String msg = "Failed to retrieve realm configuration.";
+                log.error(msg, e);
+                throw new RegistryException(msg, e);
+            }
+
+            String everyoneRole = realmConfig.getEveryOneRoleName();
+
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.GET);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
+            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
+
+        } catch (UserStoreException e) {
+            String msg = "Could not clear authorizations for the " + path + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg);
+        }
+    }
+
+    /**
+     * builds the OMElement from the given inputStream
+     *
+     * @param inputStream, given input - inputStream
+     * @return OMElement
+     * @throws Exception, if building OMElement from the inputStream failed.
+     */
+    public static OMElement buildOMElement(InputStream inputStream) throws Exception {
+        XMLStreamReader parser;
+        try {
+            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+        } catch (XMLStreamException e) {
+            String msg = "Error in initializing the parser to build the OMElement.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        // create the builder
+        StAXOMBuilder builder = new StAXOMBuilder(parser);
+        // get the root element (in this case the envelope)
+
+        return builder.getDocumentElement();
+    }
+
+
+    /**
+     * validates the email
+     *
+     * @param email - email address
+     * @throws Exception, if validation failed
+     */
+    public static void validateEmail(String email) throws Exception {
+        if (email == null) {
+            String msg = "Provided email value is null.";
+            log.warn(msg);
+            throw new Exception(msg);
+        }
+        email = email.trim();
+        if ("".equals(email)) {
+            String msg = "Provided email value is empty.";
+            log.warn(msg);
+            throw new Exception(msg);
+        }
+        if (illegalCharactersPatternForEmail.matcher(email).matches()) {
+            String msg = "Wrong characters in the email.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        if (!emailFilterPattern.matcher(email).matches()) {
+            String msg = "Invalid email address is provided.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * @param name     validate the name.
+     * @param variable entry name.
+     * @throws Exception if empty
+     */
+    public static void validateName(String name, String variable) throws Exception {
+        if (name.trim().equals("")) {
+            String msg = variable + " is not provided.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * validates domain from the successkey
+     *
+     * @param governanceSystemRegistry - The governance system registry
+     * @param domain                   - tenant domain
+     * @param successKey               - successkey
+     * @return true, if successfully validated
+     * @throws RegistryException, if validation failed
+     */
+    public static boolean validateDomainFromSuccessKey(UserRegistry governanceSystemRegistry,
+                                                       String domain, String successKey)
+            throws RegistryException {
+        String domainValidatorInfoPath =
+                StratosConstants.DOMAIN_VALIDATOR_INFO_PATH + RegistryConstants.PATH_SEPARATOR +
+                domain + RegistryConstants.PATH_SEPARATOR +
+                StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+        if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
+            Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
+            String actualSuccessKey = resource.getProperty("successKey");
+            if (actualSuccessKey != null && successKey != null &&
+                actualSuccessKey.trim().equals(successKey.trim())) {
+                // the domain is correct
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Returns the configurations from the stratos configuration file.
+     *
+     * @return stratos configurations
+     */
+    public static StratosConfiguration loadStratosConfiguration() {
+        // gets the configuration file name from the StratosConstants.
+        String StratosConfigFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                StratosConstants.STRATOS_CONF_FILE;
+        return loadStratosConfiguration(StratosConfigFileName);
+    }
+
+    /**
+     * Loads the given Stratos Configuration file.
+     *
+     * @param configFilename Name of the configuration file
+     * @return the stratos configuration data.
+     */
+    private static StratosConfiguration loadStratosConfiguration(String configFilename) {
+        StratosConfiguration config = new StratosConfiguration();
+        File configFile = new File(configFilename);
+        if (configFile.exists()) {
+            FileInputStream inputStream = null;
+            try {
+                inputStream = new FileInputStream(configFile);
+                XMLStreamReader parser =
+                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+                StAXOMBuilder builder = new StAXOMBuilder(parser);
+                OMElement documentElement = builder.getDocumentElement();
+                Iterator it = documentElement.getChildElements();
+                while (it.hasNext()) {
+                    OMElement element = (OMElement) it.next();
+
+                    if ("DisableTenantManagementEmails".equals(element.getLocalName())) {
+                        String disableEmails = element.getText();
+                        // by default, make the email validation mandatory.
+                        boolean isEmailsDisabled = true;
+                        if (disableEmails.trim().equalsIgnoreCase("false")) {
+                            isEmailsDisabled = false;
+                        }
+                        config.setEmailsDisabled(isEmailsDisabled);
+                    }
+                    // Checks whether Email Validation is mandatory to log in and use the registered
+                    // tenants.
+                    else if ("EmailValidationMandatoryForLogin".equals(element.getLocalName())) {
+                        String emailValidation = element.getText();
+                        //by default, make the email validation not mandatory.
+                        boolean isEmailValidationRequired = false;
+                        if (emailValidation.trim().equalsIgnoreCase("true")) {
+                            isEmailValidationRequired = true;
+                        }
+                        config.setEmailValidationRequired(isEmailValidationRequired);
+                    } else if ("ChargeOnRegistration".equals(element.getLocalName())) {
+                        String chargeOnRegistration = element.getText();
+                        boolean isChargedOnRegistration = false;
+                        if (chargeOnRegistration.trim().equalsIgnoreCase("true")) {
+                            isChargedOnRegistration = true;
+                        }
+                        config.setChargeOnRegistration(isChargedOnRegistration);
+                    } else if ("NotificationEmail".equals(element.getLocalName())) {
+                        config.setNotificationEmail(element.getText());
+                    } else if ("SuperAdminEmail".equals(element.getLocalName())) {
+                        config.setSuperAdminEmail(element.getText());
+                    } else if ("TenantActivationModerated".equals(element.getLocalName())){
+                        String isTenantActivationModerated = element.getText();
+                        boolean tenantActivationModerated = false;
+                        if (isTenantActivationModerated.trim().equalsIgnoreCase("true")) {
+                            tenantActivationModerated = true;
+                        }
+                        config.setTenantActivationModerated(tenantActivationModerated);
+                    }
+                    //Checks whether it is public cloud deployment.
+                    else if ("StratosPublicCloudSetup".equals(element.getLocalName())) {
+                        String cloudSetup = element.getText();
+                        //by default, make the email validation mandatory.
+                        boolean isStratosPublicCloudSetup = true;
+                        if (cloudSetup.trim().equalsIgnoreCase("false")) {
+                            isStratosPublicCloudSetup = false;
+                        }
+                        config.setPublicCloudSetup(isStratosPublicCloudSetup);
+                        //Setting the paypal url
+                    } else if ("PaypalUrl".equals(element.getLocalName())) {
+                        String paypalUrl = element.getText();
+                        config.setPaypalUrl(paypalUrl);
+                    } else if ("SkipSummaryGenerator".equals(element.getLocalName())) {
+                        String summaryGenerator = element.getText();
+                        boolean skipSummaryGenerator = false;
+                        if (summaryGenerator.trim().equalsIgnoreCase("true")) {
+                            skipSummaryGenerator = true;
+                        }
+                        config.setSkipSummaryGenerator(skipSummaryGenerator);
+                    }
+                    else if ("PaypalAPIUsername".equals(element.getLocalName())) {
+                        config.setPaypalAPIUsername(element.getText());
+                    } else if ("PaypalAPIPassword".equals(element.getLocalName())) {
+                        config.setPaypalAPIPassword(element.getText());
+                    } else if ("PaypalAPISignature".equals(element.getLocalName())) {
+                        config.setPaypalAPISignature(element.getText());
+                    }else if ("PaypalEnvironment".equals(element.getLocalName())){
+                        config.setPaypalEnvironment(element.getText());
+                    }else if("FinanceNotificationEmail".equals(element.getLocalName())){
+                        config.setFinanceNotificationEmail(element.getText());    
+                    }else if("UsagePlanUrl".equals(element.getLocalName())){
+                        config.setUsagePlanURL(element.getText());
+                    }else if("PaidJIRAUrl".equals(element.getLocalName())) {
+                        config.setPaidJIRAUrl(element.getText());
+                    }else if("PaidJIRAProject".equals(element.getLocalName())) {
+                        config.setPaidJIRAProject(element.getText());
+                    }else if("ForumUrl".equals(element.getLocalName())) {
+                        config.setForumUrl(element.getText());
+                    }else if("PaidUserGroup".equals(element.getLocalName())) {
+                        config.setPaidUserGroup(element.getText());
+                    }else if("NonpaidUserGroup".equals(element.getLocalName())) {
+                        config.setNonpaidUserGroup(element.getText());
+                    } else if("SupportInfoUrl".equals(element.getLocalName())) {
+                        config.setSupportInfoUrl(element.getText());
+                    }else if("IncidentCustomFieldId".equals(element.getLocalName())) {
+                        config.setIncidentCustomFieldId(element.getText());
+                    } else if("IncidentImpactCustomFieldId".equals(element.getLocalName())) {
+                        config.setIncidentImpactCustomFieldId(element.getText());
+                    } else if ("GoogleAnalyticsURL".equals(element.getLocalName())) {
+                        config.setGoogleAnalyticsURL(element.getText());
+                    } else if("StratosEventListener".equals(element.getLocalName())) {
+                        populateEventListenerProperties(config, element);
+                    } else if ("managerServiceUrl".equals(element.getLocalName())) {
+                        config.setManagerServiceUrl(element.getText());
+                    } else if ("adminUserName".equals(element.getLocalName())) {
+                        config.setAdminUserName(element.getText());
+                    } else if ("adminPassword".equals(element.getLocalName())) {
+                        config.setAdminPassword(element.getText());
+                    } else if("SSOLoadingMessage".equals(element.getLocalName())){
+                        config.setSsoLoadingMessage(element.getText());
+                    }
+                }
+                return config;
+            } catch (Exception e) {
+                String msg = "Error in loading Stratos Configurations File: " + configFilename + ".";
+                log.error(msg, e);
+                return config; //returns the default configurations, if the file could not be loaded.
+            } finally {
+                if (inputStream != null) {
+                    try {
+                        inputStream.close();
+                    } catch (IOException e) {
+                        log.error("Could not close the Configuration File " + configFilename);
+                    }
+                }
+            }
+        }
+        log.error("Unable to locate the stratos configurations file. " +
+                  "Default Settings will be used.");
+        return config; // return the default configuratiosn, if the file not found.
+    }
+    
+    
+    private static void populateEventListenerProperties(StratosConfiguration config,
+                                                        OMElement element) throws RegistryException {
+        config.setStratosEventListenerName(element.getAttributeValue(new QName("class")));
+        Iterator<?> ite =
+                          element.getChildrenWithName(new QName("Property"));
+        while (ite.hasNext()) {
+            OMElement propElem = (OMElement) ite.next();
+            String propName = propElem.getAttributeValue(new QName("name"));
+            String propValue = propElem.getText();
+            config.setStratosEventListenerProperty(propName, propValue);
+        }
+    }
+
+    /**
+     * Loading the EULA.
+     * ultimately we shall be loading the eula from the web page itself.
+     * But loading from file should be there to customize the EULA based on the private deployments,
+     * etc.
+     *
+     * @return eula
+     */
+    public static String loadTermsOfUsage() {
+        // currently loads from the file; gets the eula file name from the StratosConstants.
+        String StratosEULAFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                StratosConstants.STRATOS_EULA;
+        return loadTermsOfUsage(StratosEULAFileName);
+    }
+
+    private static String loadTermsOfUsage(String eulaFile) {
+        String eula = StratosConstants.STRATOS_EULA_DEFAULT_TEXT;
+        File configFile = new File(eulaFile);
+        if (configFile.exists()) {
+            FileInputStream inputStream = null;
+            try {
+                inputStream = new FileInputStream(configFile);
+                XMLStreamReader parser =
+                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+                StAXOMBuilder builder = new StAXOMBuilder(parser);
+                OMElement documentElement = builder.getDocumentElement();
+                Iterator it = documentElement.getChildElements();
+                while (it.hasNext()) {
+                    OMElement element = (OMElement) it.next();
+
+                    //Checks whether Email Validation is mandatory for tenant registration complete.
+                    if ("EULA".equalsIgnoreCase(element.getLocalName())) {
+                        eula = element.getText();
+                    }
+                }
+                return eula;
+            } catch (Exception e) {
+                String msg = "Error in loading Stratos Terms and Conditions File.";
+                log.error(msg, e);
+                return eula; //returns the default text, if the file could not be loaded.
+            } finally {
+                if (inputStream != null) {
+                    try {
+                        inputStream.close();
+                    } catch (IOException e) {
+                        log.error("Could not close the EULA File " + eulaFile);
+                    }
+                }
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Unable to locate the stratos EULA file. Default value will be used.");
+        }
+        return eula; // return the default, if the file not found.
+    }
+
+
+    /**
+     * method to check whether a domain name is available to register given a domain name
+     * @param tenantDomain, domain name
+     * @return true, if the domain is available to register
+     * @throws Exception, if checking the existence of the tenant is failed.
+     */
+    public static boolean isDomainNameAvailable(String tenantDomain) throws Exception {
+
+        TenantManager tenantManager = CloudCommonServiceComponent.getTenantManager();
+          // The registry reserved words are checked first.
+          if (tenantDomain.equals("atom") || tenantDomain.equals("registry")
+                  || tenantDomain.equals("resource")) {
+              String msg = "You can not use a registry reserved word:" + tenantDomain +
+                           ":as a tenant domain. Please choose a different one.";
+              log.error(msg);
+              throw new Exception(msg);
+          }
+
+          int tenantId;
+          try {
+              tenantId = tenantManager.getTenantId(tenantDomain);
+          } catch (UserStoreException e) {
+              String msg = "Error in getting the tenant id for the given domain  " +
+                           tenantDomain + ".";
+              log.error(msg);
+              throw new Exception(msg, e);
+          }
+
+          // check a tenant with same domain exist.
+          if ((tenantId != MultitenantConstants.INVALID_TENANT_ID && tenantId != MultitenantConstants.SUPER_TENANT_ID) ||
+                  tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
+              String msg =
+                           "A tenant with same domain already exist. " +
+                                   "Please use a different domain name. tenant domain: " +
+                                   tenantDomain + ".";
+              log.info(msg);
+              return false;
+          }
+          return true;
+      }
+}
+
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
new file mode 100644
index 0000000..4dc269e
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
@@ -0,0 +1,53 @@
+/*
+ * 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.common.util;
+
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+public class MeteringAccessValidationUtils {
+
+	public static final String ERROR_MSG_PROPERTY_KEY_POST_FIX = "error_msg";
+	public static final String IS_BLOCKED_PROPERTY_KEY_POST_FIX = "is_blocked";
+
+	public static String generateIsBlockedPropertyKey(String action) {
+		return action + "_" + IS_BLOCKED_PROPERTY_KEY_POST_FIX;
+	}
+
+	public static String generateErrorMsgPropertyKey(String action) {
+		return action + "_" + ERROR_MSG_PROPERTY_KEY_POST_FIX;
+	}
+
+	public static Set<String> getAvailableActions(Properties properties) {
+		Set propertyKeys = properties.keySet();
+		Set<String> actions = new HashSet<String>();
+		for (Object propertyKeyObj : propertyKeys) {
+			String propertyKey = (String) propertyKeyObj;
+			if (propertyKey.endsWith(IS_BLOCKED_PROPERTY_KEY_POST_FIX)) {
+			    // -1 for the length of the '_'
+				String action =
+				        propertyKey.substring(0, propertyKey.length() -
+				                IS_BLOCKED_PROPERTY_KEY_POST_FIX.length() - 1);
+				actions.add(action);
+			}
+		}
+		return actions;
+	}
+}