Renaming org.apache.stratos.metadataservice to 
org.apache.stratos.metadata.service


Project: http://git-wip-us.apache.org/repos/asf/stratos/repo
Commit: http://git-wip-us.apache.org/repos/asf/stratos/commit/958a3100
Tree: http://git-wip-us.apache.org/repos/asf/stratos/tree/958a3100
Diff: http://git-wip-us.apache.org/repos/asf/stratos/diff/958a3100

Branch: refs/heads/master
Commit: 958a3100a833e4de7f8fdb710099c44469853936
Parents: 60bca14
Author: Imesh Gunaratne <[email protected]>
Authored: Sun Jan 25 11:02:18 2015 +0530
Committer: Imesh Gunaratne <[email protected]>
Committed: Sun Jan 25 11:02:19 2015 +0530

----------------------------------------------------------------------
 .../org.apache.stratos.metadata.service/pom.xml | 162 +++++++++
 .../stratos/metadata/service/Constants.java     |  28 ++
 .../stratos/metadata/service/ServiceHolder.java |  84 +++++
 .../apache/stratos/metadata/service/Utils.java  |  44 +++
 .../service/annotation/AuthorizationAction.java |  36 ++
 .../service/annotation/SuperTenantService.java  |  34 ++
 .../service/context/AuthenticationContext.java  |  40 +++
 .../service/definition/ApplicationBean.java     |  70 ++++
 .../service/definition/CartridgeMetaData.java   |  36 ++
 .../service/definition/ClusterBean.java         |  59 ++++
 .../service/definition/NewProperty.java         |  68 ++++
 .../service/definition/PropertyBean.java        |  61 ++++
 .../service/exception/MetadataException.java    |   9 +
 .../service/exception/RestAPIException.java     |  70 ++++
 ...tractAuthenticationAuthorizationHandler.java |  56 ++++
 .../CookieBasedAuthenticationHandler.java       |  94 ++++++
 .../service/handlers/CustomExceptionMapper.java |  47 +++
 .../CustomThrowableExceptionMapper.java         |  44 +++
 .../handlers/GenericExceptionMapper.java        |  54 +++
 .../metadata/service/handlers/OAuthHandler.java | 133 ++++++++
 .../handlers/StratosAuthenticationHandler.java  | 156 +++++++++
 .../handlers/StratosAuthorizingHandler.java     | 322 ++++++++++++++++++
 .../service/oauth2/ValidationServiceClient.java |  65 ++++
 .../service/registry/CarbonRegistry.java        | 191 +++++++++++
 .../service/registry/DataRegistryFactory.java   |  33 ++
 .../metadata/service/registry/DataStore.java    |  41 +++
 .../service/security/StratosPrincipal.java      |  53 +++
 .../security/StratosSecurityContext.java        |  50 +++
 .../service/services/MetaDataAdmin.java         | 195 +++++++++++
 .../stratos/metadata/service/util/ConfUtil.java |  76 +++++
 .../src/main/resources/axis2_client.xml         | 299 +++++++++++++++++
 .../META-INF/webapp-classloading.xml            |  35 ++
 .../metadata-test/WEB-INF/cxf-servlet.xml       |  46 +++
 .../main/webapp/metadata-test/WEB-INF/web.xml   |  40 +++
 .../metadata/META-INF/webapp-classloading.xml   |  35 ++
 .../webapp/metadata/WEB-INF/cxf-servlet.xml     |  81 +++++
 .../src/main/webapp/metadata/WEB-INF/web.xml    |  39 +++
 .../org.apache.stratos.metadataservice/pom.xml  | 162 ---------
 .../stratos/metadataservice/Constants.java      |  28 --
 .../stratos/metadataservice/ServiceHolder.java  |  84 -----
 .../apache/stratos/metadataservice/Utils.java   |  44 ---
 .../annotation/AuthorizationAction.java         |  36 --
 .../annotation/SuperTenantService.java          |  34 --
 .../context/AuthenticationContext.java          |  40 ---
 .../definition/ApplicationBean.java             |  70 ----
 .../definition/CartridgeMetaData.java           |  36 --
 .../metadataservice/definition/ClusterBean.java |  59 ----
 .../metadataservice/definition/NewProperty.java |  68 ----
 .../definition/PropertyBean.java                |  61 ----
 .../exception/MetadataException.java            |   9 -
 .../exception/RestAPIException.java             |  70 ----
 ...tractAuthenticationAuthorizationHandler.java |  56 ----
 .../CookieBasedAuthenticationHandler.java       |  94 ------
 .../handlers/CustomExceptionMapper.java         |  47 ---
 .../CustomThrowableExceptionMapper.java         |  44 ---
 .../handlers/GenericExceptionMapper.java        |  54 ---
 .../metadataservice/handlers/OAuthHandler.java  | 133 --------
 .../handlers/StratosAuthenticationHandler.java  | 156 ---------
 .../handlers/StratosAuthorizingHandler.java     | 333 -------------------
 .../oauth2/ValidationServiceClient.java         |  65 ----
 .../registry/CarbonRegistry.java                | 191 -----------
 .../registry/DataRegistryFactory.java           |  33 --
 .../metadataservice/registry/DataStore.java     |  41 ---
 .../security/StratosPrincipal.java              |  53 ---
 .../security/StratosSecurityContext.java        |  50 ---
 .../metadataservice/services/MetaDataAdmin.java | 195 -----------
 .../stratos/metadataservice/util/ConfUtil.java  |  76 -----
 .../src/main/resources/axis2_client.xml         | 299 -----------------
 .../META-INF/webapp-classloading.xml            |  35 --
 .../metadata-test/WEB-INF/cxf-servlet.xml       |  46 ---
 .../main/webapp/metadata-test/WEB-INF/web.xml   |  40 ---
 .../metadata/META-INF/webapp-classloading.xml   |  35 --
 .../webapp/metadata/WEB-INF/cxf-servlet.xml     |  81 -----
 .../src/main/webapp/metadata/WEB-INF/web.xml    |  39 ---
 components/pom.xml                              |   2 +-
 .../pom.xml                                     | 316 ++++++++++++++++++
 .../src/main/resources/p2.inf                   |  23 ++
 .../src/main/resources/tomcat/context.xml       |  36 ++
 .../tomcat/webapp-classloading-environments.xml |  68 ++++
 .../resources/tomcat/webapp-classloading.xml    |  33 ++
 .../pom.xml                                     | 316 ------------------
 .../src/main/resources/p2.inf                   |  23 --
 .../src/main/resources/tomcat/context.xml       |  36 --
 .../tomcat/webapp-classloading-environments.xml |  68 ----
 .../resources/tomcat/webapp-classloading.xml    |  33 --
 features/manager/pom.xml                        |   2 +-
 .../pom.xml                                     |  47 ++-
 products/stratos/modules/p2-profile-gen/pom.xml |  12 +-
 88 files changed, 3492 insertions(+), 3506 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.metadata.service/pom.xml 
b/components/org.apache.stratos.metadata.service/pom.xml
new file mode 100644
index 0000000..0daf649
--- /dev/null
+++ b/components/org.apache.stratos.metadata.service/pom.xml
@@ -0,0 +1,162 @@
+<!-- 
+  #  Licensed to the Apache Software Foundation (ASF) under one
+  #  or more contributor license agreements.  See the NOTICE file
+  #  distributed with this work for additional information
+  #  regarding copyright ownership.  The ASF licenses this file
+  #  to you under the Apache License, Version 2.0 (the
+  #  "License"); you may not use this file except in compliance
+  #  with the License.  You may obtain a copy of the License at
+  #  
+  #  http://www.apache.org/licenses/LICENSE-2.0
+  #  
+  #  Unless required by applicable law or agreed to in writing,
+  #  software distributed under the License is distributed on an
+  #  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  #  KIND, either express or implied.  See the License for the
+  #  specific language governing permissions and limitations
+  #  under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/maven-v4_0_0.xsd";>
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>4.1.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.metadata.service</artifactId>
+    <packaging>war</packaging>
+    <name>Apache Stratos - Meta Data Service</name>
+
+    <profiles>
+        <profile>
+            <id>test</id>
+            <activation>
+                <property>
+                    <name>env</name>
+                    <value>test</value>
+                </property>
+            </activation>
+            <properties>
+                <appName>metadata-test</appName>
+            </properties>
+        </profile>
+        <profile>
+            <id>prod</id>
+            <activation>
+                <activeByDefault>true</activeByDefault>
+            </activation>
+            <properties>
+                <appName>metadata</appName>
+            </properties>
+        </profile>
+    </profiles>
+
+
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.5</source>
+                    <target>1.5</target>
+                </configuration>
+                <version>2.3.2</version>
+            </plugin>
+            <plugin>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>2.2</version>
+                <configuration>
+                    <webResources>
+                        <resource>
+                            <!-- this is relative to the pom.xml directory -->
+                            <directory>src/main/webapp/${appName}</directory>
+                        </resource>
+                    </webResources>
+                    <warName>metadata</warName>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-bundle</artifactId>
+            <version>2.7.7</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>${wso2carbon.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>${wso2carbon.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
+            <version>${wso2carbon.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.tenant.mgt</artifactId>
+            <version>2.2.2</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.manager</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            
<artifactId>org.apache.stratos.cloud.controller.service.stub</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.autoscaler.service.stub</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.messaging</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ntask.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.ws.stub</artifactId>
+            <version>${wso2carbon.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.nimbusds.wso2</groupId>
+            <artifactId>nimbus-jose-jwt</artifactId>
+            <version>2.26.1.wso2v2</version>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Constants.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Constants.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Constants.java
new file mode 100644
index 0000000..0027a47
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Constants.java
@@ -0,0 +1,28 @@
+/*
+ * 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.metadata.service;
+
+/**
+ * Global constants used in this module
+ */
+public class Constants {
+
+    public static final String METADATASERVICE_CONFIG_FILE_NAME = 
"metadataservice.xml";
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/ServiceHolder.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/ServiceHolder.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/ServiceHolder.java
new file mode 100644
index 0000000..4a6a8cc
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/ServiceHolder.java
@@ -0,0 +1,84 @@
+/*
+ * 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.metadata.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.TenantBillingService;
+import org.wso2.carbon.tenant.mgt.core.TenantPersistor;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * Some of the admin services needs objects with states inside the runtime.
+ * There are
+ * two mechanisms to get those kind of objects. Either with singleton with or
+ * via OSGi
+ * services. OSGi services mechanism is preferred. This is a helper class for
+ * doing that.
+ */
+public class ServiceHolder {
+       private static Log log = LogFactory.getLog(ServiceHolder.class);
+
+       public static TenantManager getTenantManager() {
+               PrivilegedCarbonContext carbonContext =
+                                                       
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+               RealmService realmService = (RealmService) 
carbonContext.getOSGiService(RealmService.class);
+               return realmService.getTenantManager();
+       }
+
+       public static TenantBillingService getBillingService() {
+               PrivilegedCarbonContext carbonContext =
+                                                       
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+               TenantBillingService tenantBillingService =
+                                                           
(TenantBillingService) carbonContext.getOSGiService(TenantBillingService.class);
+               return tenantBillingService;
+       }
+
+       public static RealmService getRealmService() {
+               PrivilegedCarbonContext carbonContext =
+                                                       
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+               RealmService realmService = (RealmService) 
carbonContext.getOSGiService(RealmService.class);
+               return realmService;
+       }
+
+       public static RegistryService getRegistryService() {
+               PrivilegedCarbonContext carbonContext =
+                                                       
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+               RegistryService registryService =
+                                                 (RegistryService) 
carbonContext.getOSGiService(RegistryService.class);
+               return registryService;
+       }
+
+       public static TenantPersistor getTenantPersistor() {
+               TenantPersistor tenantPersistor = new TenantPersistor();
+               return tenantPersistor;
+       }
+
+       public static ConfigurationContextService getConfigurationContext() {
+               PrivilegedCarbonContext carbonContext =
+                                                       
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+               ConfigurationContextService configurationContextService =
+                                                                         
(ConfigurationContextService) 
carbonContext.getOSGiService(ConfigurationContextService.class);
+               return configurationContextService;
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Utils.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Utils.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Utils.java
new file mode 100644
index 0000000..951bc59
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/Utils.java
@@ -0,0 +1,44 @@
+/**
+ * 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.metadata.service;
+
+public class Utils {
+
+       public static String buildMessage(int errorCode, String errorMessage) {
+               String jsonResponse =
+                                     "{\"Error\":{" + " \"errorCode\": \" " + 
errorCode + "\"," +
+                                             " \"errorMessage\": \" " + 
errorMessage + "\"" + "}" + "}";
+               return jsonResponse;
+       }
+
+       public static String buildMessage(String errorMessage) {
+               String jsonResponse =
+                                     "{\"Error\":{" + " \"errorCode\": \" " + 
-1234 + "\"," +
+                                             " \"errorMessage\": \" " + 
errorMessage + "\"" + "}" + "}";
+               return jsonResponse;
+       }
+
+       public static String buildAuthenticationSuccessMessage(String 
jSessionId) {
+               String jsonResponse =
+                                     "{\"Success\":{" + " \"sessionId\": \"" + 
jSessionId + "\"" + "}" +
+                                             "}";
+               return jsonResponse;
+       }
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/AuthorizationAction.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/AuthorizationAction.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/AuthorizationAction.java
new file mode 100644
index 0000000..16a8d14
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/AuthorizationAction.java
@@ -0,0 +1,36 @@
+/*
+ * 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.metadata.service.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Carbon kernel handles permissions by means of permission strings.
+ * Permission strings are defined at the operation level. Here the admin
+ * service developer has to specify authorization requirements using
+ * the below annotation
+ */
+@Retention(value = RetentionPolicy.RUNTIME)
+@Target(value = ElementType.METHOD)
+public @interface AuthorizationAction {
+       String[] value();
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/SuperTenantService.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/SuperTenantService.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/SuperTenantService.java
new file mode 100644
index 0000000..df75adc
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/annotation/SuperTenantService.java
@@ -0,0 +1,34 @@
+/*
+ * 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.metadata.service.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * In Carbon admin authorization framework there are super-tenant only
+ * admin services. We use below annotation to mark such admin services.
+ */
+@Retention(value = RetentionPolicy.RUNTIME)
+@Target(value = ElementType.METHOD)
+public @interface SuperTenantService {
+       boolean value();
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/context/AuthenticationContext.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/context/AuthenticationContext.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/context/AuthenticationContext.java
new file mode 100644
index 0000000..d975ae1
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/context/AuthenticationContext.java
@@ -0,0 +1,40 @@
+package org.apache.stratos.metadata.service.context;
+
+/*
+ * 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.
+ */
+
+public class AuthenticationContext {
+       // maintaining the authenticated state in threadLocal. We want to skip
+       // subsequent authentication handlers
+       // once a request get authenticated by a handler.
+       private static final ThreadLocal<Boolean> authenticated = new 
ThreadLocal<Boolean>() {
+               @Override
+               protected Boolean initialValue() {
+                       return false;
+               }
+       };
+
+       public static boolean isAthenticated() {
+               return authenticated.get();
+       }
+
+       public static void setAuthenticated(boolean isAuthenticated) {
+               authenticated.set(isAuthenticated);
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ApplicationBean.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ApplicationBean.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ApplicationBean.java
new file mode 100644
index 0000000..84ad76d
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ApplicationBean.java
@@ -0,0 +1,70 @@
+/**
+ * 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.metadata.service.definition;
+
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.ArrayList;
+import java.util.List;
+
+@XmlRootElement(name="applications")
+public class ApplicationBean {
+    private String appId;
+    private List<ClusterBean> clusters;
+
+    public ApplicationBean(){
+        this.clusters = new ArrayList<ClusterBean>();
+    }
+
+    public ApplicationBean(String appId){
+        this.appId = appId;
+        this.clusters = new ArrayList<ClusterBean>();
+    }
+
+    public String getAppId() {
+        return appId;
+    }
+
+    public void setAppId(String appId) {
+        this.appId = appId;
+    }
+
+    public List<ClusterBean> getClusters() {
+        return clusters;
+    }
+
+    public ClusterBean getCluster(String clusterId){
+
+        for(ClusterBean clusterBean : clusters){
+            if(clusterBean.getClusterId().equals(clusterId)){
+                return clusterBean;
+            }
+        }
+
+        return null;
+    }
+
+    public void setClusters(List<ClusterBean> clusters) {
+        this.clusters = clusters;
+    }
+
+    public void addCluster(ClusterBean cluster){
+        this.clusters.add(cluster);
+    }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/CartridgeMetaData.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/CartridgeMetaData.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/CartridgeMetaData.java
new file mode 100644
index 0000000..dec5739
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/CartridgeMetaData.java
@@ -0,0 +1,36 @@
+package org.apache.stratos.metadata.service.definition;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "cartridgeMetaData")
+public class CartridgeMetaData {
+       public String applicationName;
+
+       public String displayName;
+
+       public String description;
+
+       public String type;
+
+       public String provider;
+
+       public String host;
+
+       public String version;
+
+       public String properties;
+
+       @Override
+       public String toString() {
+
+               return "applicationName: " + applicationName + ", displayName: 
" + displayName +
+                      ", description: " + description + ", type: " + type + ", 
provider: " + provider +
+                      ", host: " + host + ", Version: " + version + ", 
properties: " + properties;
+       }
+
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ClusterBean.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ClusterBean.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ClusterBean.java
new file mode 100644
index 0000000..7ac81f3
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/ClusterBean.java
@@ -0,0 +1,59 @@
+package org.apache.stratos.metadata.service.definition;
+/**
+ * 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 javax.xml.bind.annotation.XmlRootElement;
+import java.util.ArrayList;
+import java.util.List;
+
+@XmlRootElement(name="clusters")
+public class ClusterBean {
+
+    private String clusterId;
+    private List<NewProperty> properties;
+
+    public ClusterBean(){
+        this.setProperties(new ArrayList<NewProperty>());
+    }
+
+    public ClusterBean(String id){
+        this.setClusterId(id);
+        this.setProperties(new ArrayList<NewProperty>());
+    }
+
+    public String getClusterId() {
+        return clusterId;
+    }
+
+    public void setClusterId(String clusterId) {
+        this.clusterId = clusterId;
+    }
+
+    public List<NewProperty> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(List<NewProperty> properties) {
+        this.properties = properties;
+    }
+
+    public void addProperty(NewProperty property){
+        this.properties.add(property);
+    }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/NewProperty.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/NewProperty.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/NewProperty.java
new file mode 100644
index 0000000..b933d97
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/NewProperty.java
@@ -0,0 +1,68 @@
+/**
+ * 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.metadata.service.definition;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@XmlRootElement(name="properties")
+public class NewProperty implements Serializable{
+
+    private String key;
+    private List<String> values = new ArrayList<String>();
+
+    public NewProperty(){}
+    public NewProperty(String key, String value){
+        this.key=key;
+        this.values.add(value);
+    }
+    
+    public String getKey() {
+        return key;
+    }
+
+    public void setKey(String key) {
+        this.key = key;
+    }
+
+    public String[] getValues(){
+        String[] values = new String[this.values.size()];
+        values = this.values.toArray(values);
+        return values;
+    }
+
+    public void setValues(String[] values) {
+        this.values.addAll(Arrays.asList(values));
+    }
+
+
+    public void setValues(String value) {
+        this.values.add(value);
+    }
+
+    public void addValue(String value){
+        this.values.add(value);
+    }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/PropertyBean.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/PropertyBean.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/PropertyBean.java
new file mode 100644
index 0000000..06f293d
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/definition/PropertyBean.java
@@ -0,0 +1,61 @@
+/*
+ * 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.metadata.service.definition;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "properties")
+public class PropertyBean {
+
+       private String hostname;
+
+       private String username;
+       private String password;
+
+       public String getHostname() {
+               return hostname;
+       }
+
+       public void setHostname(String hostname) {
+               this.hostname = hostname;
+       }
+
+       public String getUsername() {
+               return username;
+       }
+
+       public void setUsername(String username) {
+               this.username = username;
+       }
+
+       public String getPassword() {
+               return password;
+       }
+
+       public void setPassword(String password) {
+               this.password = password;
+       }
+
+       @Override
+       public String toString() {
+               return " [hostname: " + getHostname() + ", username: " + 
getUsername() + ", password: " + getPassword() +
+                               "]";
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/MetadataException.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/MetadataException.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/MetadataException.java
new file mode 100644
index 0000000..4b14fd0
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/MetadataException.java
@@ -0,0 +1,9 @@
+package org.apache.stratos.metadata.service.exception;
+
+
+public class MetadataException extends Exception {
+
+    public MetadataException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/RestAPIException.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/RestAPIException.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/RestAPIException.java
new file mode 100644
index 0000000..edb9a59
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/exception/RestAPIException.java
@@ -0,0 +1,70 @@
+/*
+ * 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.metadata.service.exception;
+
+import javax.ws.rs.core.Response;
+
+public class RestAPIException extends Exception {
+
+       private static final long serialVersionUID = 1L;
+
+       private String message;
+       private Response.Status httpStatusCode;
+
+       public RestAPIException() {
+               super();
+       }
+
+       public RestAPIException(String message, Throwable cause) {
+               super(message, cause);
+               this.message = message;
+       }
+
+       public RestAPIException(Response.Status httpStatusCode, String message, 
Throwable cause) {
+               super(message, cause);
+               this.message = message;
+               this.httpStatusCode = httpStatusCode;
+       }
+
+       public RestAPIException(String message) {
+               super(message);
+               this.message = message;
+       }
+
+       public RestAPIException(Response.Status httpStatusCode, String message) 
{
+               super(message);
+               this.message = message;
+               this.httpStatusCode = httpStatusCode;
+       }
+
+       public RestAPIException(Throwable cause) {
+               super(cause);
+       }
+
+       @Override
+       public String getMessage() {
+               return message;
+       }
+
+       public Response.Status getHTTPStatusCode() {
+               return httpStatusCode;
+       }
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/AbstractAuthenticationAuthorizationHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/AbstractAuthenticationAuthorizationHandler.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/AbstractAuthenticationAuthorizationHandler.java
new file mode 100644
index 0000000..f96bc69
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/AbstractAuthenticationAuthorizationHandler.java
@@ -0,0 +1,56 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.metadata.service.handlers;
+
+import java.util.List;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.impl.HttpHeadersImpl;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.stratos.metadata.service.context.AuthenticationContext;
+
+public abstract class AbstractAuthenticationAuthorizationHandler implements 
RequestHandler {
+       private final Log log = 
LogFactory.getLog(AbstractAuthenticationAuthorizationHandler.class);
+
+       @Override
+       public Response handleRequest(Message message, ClassResourceInfo 
classResourceInfo) {
+               HttpHeaders headers = new HttpHeadersImpl(message);
+               List<String> authHeader = 
headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
+               if (log.isDebugEnabled()) {
+                       log.debug("Executing " + this.getClass());
+               }
+               if (!AuthenticationContext.isAthenticated() && authHeader != 
null &&
+                   authHeader.size() > 0 && 
canHandle(authHeader.get(0).trim().split(" ")[0])) {
+                       return handle(message, classResourceInfo);
+               }
+               // give the control to the next handler
+               return null;
+
+       }
+
+       protected abstract boolean canHandle(String authHeaderPrefix);
+
+       protected abstract Response handle(Message message, ClassResourceInfo 
classResourceInfo);
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CookieBasedAuthenticationHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CookieBasedAuthenticationHandler.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CookieBasedAuthenticationHandler.java
new file mode 100644
index 0000000..39bbaa5
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CookieBasedAuthenticationHandler.java
@@ -0,0 +1,94 @@
+/*
+ * 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.metadata.service.handlers;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.stratos.metadata.service.Utils;
+import org.apache.stratos.metadata.service.context.AuthenticationContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+
+/*
+ * authenticate an incoming request using the session availability. Session is
+ * first established using the
+ * basic auth authentication. This handler will be the last to get executed in
+ * the current handler chain. Hence failure
+ * too provide a session would result in an authentication failure.
+ */
+public class CookieBasedAuthenticationHandler implements RequestHandler {
+       private final Log log = 
LogFactory.getLog(CookieBasedAuthenticationHandler.class);
+
+       @Override
+       public Response handleRequest(Message message, ClassResourceInfo 
classResourceInfo) {
+               if (AuthenticationContext.isAthenticated()) {
+                       return null;
+               }
+
+               HttpServletRequest httpServletRequest = (HttpServletRequest) 
message.get("HTTP.REQUEST");
+               HttpSession httpSession = httpServletRequest.getSession(false);
+               if (httpSession != null && isUserLoggedIn(httpSession)) { // if 
sesion
+                                                                             
// is
+                                                                             
// avaialble
+                       String userName = (String) 
httpSession.getAttribute("userName");
+                       String tenantDomain = (String) 
httpSession.getAttribute("tenantDomain");
+                       int tenantId = (Integer) 
httpSession.getAttribute("tenantId");
+                       // the following will get used by the authorization 
handler..
+                       PrivilegedCarbonContext carbonContext =
+                                                               
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+                       carbonContext.setUsername(userName);
+                       carbonContext.setTenantDomain(tenantDomain);
+                       carbonContext.setTenantId(tenantId);
+
+                       AuthenticationContext.setAuthenticated(true);
+                       if (log.isDebugEnabled()) {
+                               log.debug("authenticated using the " +
+                                         
CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
+                                         userName + "tenantDomain : " + 
tenantDomain + " tenantId : " + tenantId);
+                       }
+                       return null;
+
+               }
+               return 
Response.status(Response.Status.FORBIDDEN).type(MediaType.APPLICATION_JSON)
+                              .entity(Utils.buildMessage("The endpoint 
requires authentication")).build();
+       }
+
+       /*
+        * if the userName and tenantDomain is present in the session, we 
conclude
+        * this as an authenticated session.
+        * Thos params get set by the AuthenticationAdmin endpoint.
+        */
+       private boolean isUserLoggedIn(HttpSession httpSession) {
+               String userName = (String) httpSession.getAttribute("userName");
+               String tenantDomain = (String) 
httpSession.getAttribute("tenantDomain");
+               Integer tenantId = (Integer) 
httpSession.getAttribute("tenantId");
+               if (userName != null && tenantDomain != null && tenantId != 
null) {
+                       return true;
+               }
+               return false;
+       }
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomExceptionMapper.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomExceptionMapper.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomExceptionMapper.java
new file mode 100644
index 0000000..7e58c5d
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomExceptionMapper.java
@@ -0,0 +1,47 @@
+/**
+ * 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.metadata.service.handlers;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+
+import org.apache.stratos.metadata.service.Utils;
+import org.apache.stratos.metadata.service.exception.RestAPIException;
+
+public class CustomExceptionMapper implements 
ExceptionMapper<RestAPIException> {
+       @Override
+       public Response toResponse(RestAPIException restAPIException) {
+               // if no specific error message specified, spitting out a 
generaic error
+               // message
+               String errorMessage =
+                                     (restAPIException.getMessage() != null)
+                                                                            ? 
restAPIException.getMessage()
+                                                                            : 
"Error while fullfilling the request";
+               // if no specific error specified we are throwing the bad 
request http
+               // status code by default
+               Response.Status httpStatus =
+                                            
(restAPIException.getHTTPStatusCode() != null)
+                                                                               
           ? restAPIException.getHTTPStatusCode()
+                                                                               
           : Response.Status.BAD_REQUEST;
+               return 
Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON)
+                              
.entity(Utils.buildMessage(httpStatus.getStatusCode(), errorMessage))
+                              .build();
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomThrowableExceptionMapper.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomThrowableExceptionMapper.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomThrowableExceptionMapper.java
new file mode 100644
index 0000000..8db8df6
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/CustomThrowableExceptionMapper.java
@@ -0,0 +1,44 @@
+package org.apache.stratos.metadata.service.handlers;
+
+/*
+ * 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 javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.metadata.service.Utils;
+
+public class CustomThrowableExceptionMapper implements 
ExceptionMapper<Throwable> {
+       private static Log log = 
LogFactory.getLog(CustomThrowableExceptionMapper.class);
+
+       @Override
+       public Response toResponse(Throwable throwable) {
+               if (log.isDebugEnabled()) {
+                       log.debug("Internal server error", throwable);
+               }
+
+               return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+                              .type(MediaType.APPLICATION_JSON)
+                              
.entity(Utils.buildMessage(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
+                                                         "Internal server 
error")).build();
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/GenericExceptionMapper.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/GenericExceptionMapper.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/GenericExceptionMapper.java
new file mode 100644
index 0000000..97016f8
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/GenericExceptionMapper.java
@@ -0,0 +1,54 @@
+/*
+ * 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.metadata.service.handlers;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.metadata.service.Utils;
+
+/*
+ * This class maps any exception thrown by the server, which is not mapped by a
+ * specifi exception mapper
+ * in to an appropriate format
+ */
+public class GenericExceptionMapper implements 
ExceptionMapper<WebApplicationException> {
+       private static Log log = 
LogFactory.getLog(GenericExceptionMapper.class);
+
+       @Override
+       public Response toResponse(WebApplicationException 
webApplicationException) {
+               if (log.isDebugEnabled()) {
+                       log.debug("Internal erver error", 
webApplicationException);
+               }
+               // if no specific error message specified, spitting out a 
generaic error
+               // message
+               String errorMessage =
+                                     (webApplicationException.getMessage() != 
null)
+                                                                               
    ? webApplicationException.getMessage()
+                                                                               
    : "Internal server error";
+               return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+                              .type(MediaType.APPLICATION_JSON)
+                              
.entity(Utils.buildMessage(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
+                                                         
errorMessage)).build();
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/OAuthHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/OAuthHandler.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/OAuthHandler.java
new file mode 100644
index 0000000..33d3b31
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/OAuthHandler.java
@@ -0,0 +1,133 @@
+/*
+ * 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.metadata.service.handlers;
+
+import com.nimbusds.jose.JWSVerifier;
+import com.nimbusds.jose.crypto.RSASSAVerifier;
+import com.nimbusds.jwt.SignedJWT;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.jaxrs.impl.HttpHeadersImpl;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.stratos.metadata.service.context.AuthenticationContext;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.wso2.carbon.core.util.KeyStoreManager;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import java.security.interfaces.RSAPublicKey;
+
+
+/**
+ * This class responsible for OAuth based authentication/authorization. A 
client
+ * has to bring a valid OAuth token from a
+ * a OAuth provider. This class intercept the request and calls the
+ * OAuthTokenValidation endpoint of the provider.
+ */
+public class OAuthHandler extends AbstractAuthenticationAuthorizationHandler {
+    public static final String BEARER = "Bearer ";
+    public static final String APPLICATION = "application";
+    private static Log log = LogFactory.getLog(OAuthHandler.class);
+    private static String SUPPORTED_AUTHENTICATION_TYPE = "Bearer";
+    private static String oauthValidationEndpoint;
+    private static String username;
+    private static String password;
+
+    public void setOauthValidationEndpoint(String oauthValidationEndpoint) {
+        OAuthHandler.oauthValidationEndpoint = oauthValidationEndpoint;
+    }
+
+    public void setUsername(String username) {
+        OAuthHandler.username = username;
+    }
+
+    public void setPassword(String password) {
+        OAuthHandler.password = password;
+    }
+
+    @Override
+    public boolean canHandle(String authHeaderPrefix) {
+        return SUPPORTED_AUTHENTICATION_TYPE.equals(authHeaderPrefix);
+    }
+
+    @Override
+    public Response handle(Message message, ClassResourceInfo 
classResourceInfo) {
+        try {
+            HttpHeaders httpHeaders = new HttpHeadersImpl(message);
+            String header = 
httpHeaders.getRequestHeaders().getFirst("Authorization");
+            // if the authorization token has Bearer..
+            if (header.startsWith(BEARER)) {
+                String accessToken = header.substring(7).trim();
+                boolean valid;
+                String appId = extractAppIdFromIdToken(accessToken);
+                String requestUrl = (String) message.get(Message.REQUEST_URI);
+                String basePath = (String) message.get(Message.BASE_PATH);
+                String requestedAppId = 
extractApplicationIdFromUrl(requestUrl, basePath);
+
+                if(org.apache.commons.lang3.StringUtils.isEmpty(appId) || 
org.apache.commons.lang3.StringUtils.isEmpty(requestedAppId)){
+                    valid = false;
+                }else{
+                    valid = appId.equals(requestedAppId);
+                }
+
+                if (!valid) {
+                    return Response.status(Response.Status.FORBIDDEN).build();
+                }
+            }
+        } catch (Exception e) {
+            log.error("Error while validating access token", e);
+            return Response.status(Response.Status.FORBIDDEN).build();
+        }
+
+        AuthenticationContext.setAuthenticated(true);
+        return null;
+    }
+
+    private String extractApplicationIdFromUrl(String url, String basePath) {
+        String appId = null;
+        String segments[] = url.split("/");
+        for (int i = 0; i < segments.length; i++) {
+            if (APPLICATION.equals(segments[i])) {
+                appId = segments[i + 1];
+                break;
+            }
+        }
+        return appId;
+    }
+
+    private String extractAppIdFromIdToken(String token) {
+        String appId = null;
+        KeyStoreManager keyStoreManager = 
KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
+        try {
+            keyStoreManager.getDefaultPrimaryCertificate();
+            JWSVerifier verifier =
+                    new RSASSAVerifier((RSAPublicKey) 
keyStoreManager.getDefaultPublicKey());
+            SignedJWT jwsObject = SignedJWT.parse(token);
+            if (jwsObject.verify(verifier)) {
+               appId = jwsObject.getJWTClaimsSet().getStringClaim("appId");
+            }
+
+        } catch (Exception e) {
+            String message = "Could not extract application id from id token";
+            log.error(message, e);
+        }
+        return appId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthenticationHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthenticationHandler.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthenticationHandler.java
new file mode 100644
index 0000000..53749b8
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthenticationHandler.java
@@ -0,0 +1,156 @@
+/*
+ * 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.metadata.service.handlers;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.configuration.security.AuthorizationPolicy;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.security.SecurityContext;
+import org.apache.stratos.metadata.service.ServiceHolder;
+import org.apache.stratos.metadata.service.security.StratosSecurityContext;
+import org.apache.stratos.metadata.service.Utils;
+import org.apache.stratos.metadata.service.context.AuthenticationContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.util.AnonymousSessionUtil;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.api.UserRealm;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+/**
+ * Here we are doing the request authentication within a {@link 
RequestHandler}.
+ * The request handlers
+ * are get invoked just before the actual method invocation. This 
authentication
+ * handler make use
+ * of HTTP basic auth headers as the authentication mechanism.
+ */
+public class StratosAuthenticationHandler extends 
AbstractAuthenticationAuthorizationHandler {
+       private static Log log = 
LogFactory.getLog(StratosAuthenticationHandler.class);
+       private static String SUPPORTED_AUTHENTICATION_TYPE = "Basic";
+
+       @Override
+       public boolean canHandle(String authHeaderPrefix) {
+               return SUPPORTED_AUTHENTICATION_TYPE.equals(authHeaderPrefix);
+       }
+
+       /**
+        * Authenticate the user against the user store. Once authenticate, 
populate
+        * the {@link org.wso2.carbon.context.CarbonContext} to be used by the
+        * downstream code.
+        * 
+        * @param message
+        * @param classResourceInfo
+        * @return
+        */
+       @Override
+       public Response handle(Message message, ClassResourceInfo 
classResourceInfo) {
+               // If Mutual SSL is enabled
+               HttpServletRequest request = (HttpServletRequest) 
message.get("HTTP.REQUEST");
+               Object certObject = 
request.getAttribute("javax.servlet.request.X509Certificate");
+
+               AuthorizationPolicy policy = 
message.get(AuthorizationPolicy.class);
+               String username = policy.getUserName().trim();
+               String password = policy.getPassword().trim();
+
+               // sanity check
+               if ((username == null) || username.equals("")) {
+                       log.error("username is seen as null/empty values.");
+                       return Response.status(Response.Status.UNAUTHORIZED)
+                                      .header("WWW-Authenticate", 
"Basic").type(MediaType.APPLICATION_JSON)
+                                      .entity(Utils.buildMessage("Username 
cannot be null")).build();
+               } else if (certObject == null && ((password == null) || 
password.equals(""))) {
+                       log.error("password is seen as null/empty values.");
+                       return Response.status(Response.Status.UNAUTHORIZED)
+                                      .header("WWW-Authenticate", 
"Basic").type(MediaType.APPLICATION_JSON)
+                                      .entity(Utils.buildMessage("password 
cannot be null")).build();
+               }
+
+               try {
+                       RealmService realmService = 
ServiceHolder.getRealmService();
+                       RegistryService registryService = 
ServiceHolder.getRegistryService();
+                       String tenantDomain = 
MultitenantUtils.getTenantDomain(username);
+                       int tenantId = 
realmService.getTenantManager().getTenantId(tenantDomain);
+
+                       UserRealm userRealm = null;
+                       if (certObject == null) {
+                               userRealm =
+                                           
AnonymousSessionUtil.getRealmByTenantDomain(registryService,
+                                                                               
        realmService, tenantDomain);
+                               if (userRealm == null) {
+                                       log.error("Invalid domain or 
unactivated tenant login");
+                                       // is this the correct HTTP code for 
this scenario ? (401)
+                                       return 
Response.status(Response.Status.UNAUTHORIZED)
+                                                      
.header("WWW-Authenticate", "Basic")
+                                                      
.type(MediaType.APPLICATION_JSON)
+                                                      
.entity(Utils.buildMessage("Tenant not found")).build();
+                               }
+                       }
+                       username = 
MultitenantUtils.getTenantAwareUsername(username);
+                       if (certObject != null ||
+                           
userRealm.getUserStoreManager().authenticate(username, password)) { // if
+                                                                               
                    // authenticated
+
+                               // setting the correct tenant info for 
downstream code..
+                               PrivilegedCarbonContext carbonContext =
+                                                                       
PrivilegedCarbonContext.getThreadLocalCarbonContext();
+                               carbonContext.setTenantDomain(tenantDomain);
+                               carbonContext.setTenantId(tenantId);
+                               carbonContext.setUsername(username);
+                               // populate the secuirtyContext of 
authenticated user
+                               SecurityContext securityContext = new 
StratosSecurityContext(username);
+                               message.put(SecurityContext.class, 
securityContext);
+
+                               // set the authenticated flag and let the 
request to continue
+                               AuthenticationContext.setAuthenticated(true);
+                               if (log.isDebugEnabled()) {
+                                       log.debug("authenticated using the " +
+                                                 
CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
+                                                 username + "tenantDomain : " 
+ tenantDomain + " tenantId : " +
+                                                 tenantId);
+                               }
+                               return null;
+                       } else {
+                               log.warn("unable to authenticate the request");
+                               // authentication failed, request the 
authetication, add the
+                               // realm name if needed to the value of 
WWW-Authenticate
+                               return 
Response.status(Response.Status.UNAUTHORIZED)
+                                              .header("WWW-Authenticate", 
"Basic")
+                                              .type(MediaType.APPLICATION_JSON)
+                                              
.entity(Utils.buildMessage("Authentication failed. Please "
+                                                                         + 
"check your username/password"))
+                                              .build();
+                       }
+               } catch (Exception exception) {
+                       log.error("Authentication failed", exception);
+                       // server error in the eyes of the client. Hence 5xx 
HTTP code.
+                       return 
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+                                      .type(MediaType.APPLICATION_JSON)
+                                      .entity(Utils.buildMessage("Unexpected 
error. Please contact the system admin"))
+                                      .build();
+               }
+
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/958a3100/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthorizingHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthorizingHandler.java
 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthorizingHandler.java
new file mode 100644
index 0000000..5b1c9a4
--- /dev/null
+++ 
b/components/org.apache.stratos.metadata.service/src/main/java/org/apache/stratos/metadata/service/handlers/StratosAuthorizingHandler.java
@@ -0,0 +1,322 @@
+/*
+ * 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.metadata.service.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.common.util.ClassHelper;
+import org.apache.cxf.frontend.MethodDispatcher;
+import org.apache.cxf.interceptor.security.AccessDeniedException;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.service.Service;
+import org.apache.cxf.service.model.BindingOperationInfo;
+import org.apache.stratos.metadata.service.Utils;
+import org.apache.stratos.metadata.service.context.AuthenticationContext;
+import org.wso2.carbon.context.CarbonContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.user.api.AuthorizationManager;
+import org.wso2.carbon.user.api.UserRealm;
+import org.wso2.carbon.user.api.UserStoreException;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.*;
+
+/**
+ * {@link StratosAuthorizingHandler} authorize resource requests. It collects
+ * expected permission
+ * details using annotations present in the service bean. This particular
+ * implementation is inspired
+ * by the {@link org.apache.cxf.jaxrs.security.SimpleAuthorizingFilter}
+ */
+public class StratosAuthorizingHandler implements RequestHandler {
+    private final Log log = LogFactory.getLog(StratosAuthorizingHandler.class);
+
+    private static String SUPPORTED_AUTHENTICATION_TYPE = "Basic";
+    private static final String AUTHORIZATION_ANNOTATION_CLASS_NAME =
+            
"org.apache.stratos.metadata.service.annotation.AuthorizationAction";
+    private static final String TENANT_ANNOTATION_CLASS_NAME =
+            
"org.apache.stratos.metadata.service.annotation.SuperTenantService";
+    private static final String ACTION_ON_RESOURCE = "ui.execute";
+    private static final Set<String> SKIP_METHODS;
+    private Map<String, String> authorizationActionMap = 
Collections.emptyMap();
+    private Set<String> superTenantServiceSet = Collections.emptySet();
+
+    static {
+        SKIP_METHODS = new HashSet<String>();
+        SKIP_METHODS.addAll(Arrays.asList(new String[]{"wait", "notify", 
"notifyAll", "equals",
+                "toString", "hashCode"}));
+    }
+
+    public Response handleRequest(Message message, ClassResourceInfo 
resourceClass) {
+        try {
+            AuthenticationContext.setAuthenticated(false); // TODO : fix this
+            // properly
+            String userName = 
CarbonContext.getThreadLocalCarbonContext().getUsername();
+            String tenantDomain = 
CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
+            int tenantId = 
CarbonContext.getThreadLocalCarbonContext().getTenantId();
+            if (log.isDebugEnabled()) {
+                log.debug("authorizing the action using" +
+                        StratosAuthorizingHandler.class.getName());
+                log.debug("username :" + userName);
+                log.debug("tenantDomain" + tenantDomain);
+                log.debug("tenantId :" + tenantId);
+            }
+            Method targetMethod = getTargetMethod(message);
+            if (!authorize(userName, tenantDomain, tenantId, targetMethod)) {
+                log.warn("User :" + userName + "trying to perform 
unauthrorized action" +
+                        " against the resource :" + targetMethod);
+                return Response.status(Response.Status.FORBIDDEN)
+                        .type(MediaType.APPLICATION_JSON)
+                        .entity(Utils.buildMessage("The user does not have 
required permissions to "
+                                + "perform this operation")).build();
+            }
+            return null;
+
+        } catch (Exception exception) {
+            log.error("Unexpected error occured while REST api, authorization 
process", exception);
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+                    .type(MediaType.APPLICATION_JSON)
+                    .entity(Utils.buildMessage("Unexpected error. Please 
contact the system admin"))
+                    .build();
+        }
+    }
+
+    private boolean authorize(String userName, String tenantDomain, int 
tenantId,
+                              Method targetMethod) throws Exception {
+        // first we try to see whether this is a super.tenant only operation
+        if (superTenantServiceSet.contains(targetMethod.getName()) &&
+                !isCurrentUserSuperTenant(tenantDomain, tenantId)) {
+            return false;
+        }
+        // authorize using permissionString given as annotation in the service
+        // class
+        String permissionString = 
authorizationActionMap.get(targetMethod.getName());
+
+        // get the authorization manager for this tenant..
+        UserRealm userRealm = 
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
+        AuthorizationManager authorizationManager = 
userRealm.getAuthorizationManager();
+
+        boolean isAuthorized =
+                isAuthorized(authorizationManager, userName, permissionString,
+                        ACTION_ON_RESOURCE);
+        return isAuthorized;
+
+    }
+
+    private boolean isCurrentUserSuperTenant(String tenantDomain, int 
tenantId) {
+        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain) 
&&
+                MultitenantConstants.SUPER_TENANT_ID == tenantId) {
+            return true;
+        }
+        return false;
+    }
+
+    private boolean isAuthorized(AuthorizationManager authorizationManager, 
String username,
+                                 String permissionString, String action) 
throws UserStoreException {
+        boolean isAuthorized = false;
+        String[] resourceIds = permissionString.trim().split(",");
+        for (String resourceId : resourceIds) {
+            if (authorizationManager.isUserAuthorized(username, resourceId, 
action)) {
+                isAuthorized = true;
+                break;
+            }
+        }
+        return isAuthorized;
+    }
+
+    /**
+     * Here we are getting the target invocation method. The method get set as 
a
+     * properties in the
+     * message by the
+     * {@link org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor}
+     *
+     * @param message incoming message
+     * @return
+     */
+    protected Method getTargetMethod(Message message) {
+        BindingOperationInfo bop = 
message.getExchange().get(BindingOperationInfo.class);
+        if (bop != null) {
+            MethodDispatcher md =
+                    (MethodDispatcher) message.getExchange().get(Service.class)
+                            .get(MethodDispatcher.class.getName());
+            return md.getMethod(bop);
+        }
+        Method method = (Method) message.get("org.apache.cxf.resource.method");
+        if (method != null) {
+            return method;
+        }
+        log.error("The requested resource is not found. Please check the 
resource path etc..");
+        throw new AccessDeniedException("Method is not available : 
Unauthorized");
+    }
+
+    /**
+     * The instance of the secured bean get injected by the IOC framework
+     *
+     * @param securedObject
+     */
+    public void setSecuredObject(Object securedObject) {
+        Class<?> clazz = ClassHelper.getRealClass(securedObject);
+        authorizationActionMap = getAuthorizationActionMap(clazz);
+        superTenantServiceSet = getSuperTenantServiceSet(clazz);
+
+    }
+
+    private Set<String> getSuperTenantServiceSet(Class<?> clazz) {
+        Set<String> superTenantServiceSet = new HashSet<String>();
+        findSuperTenantServices(clazz, superTenantServiceSet);
+        return superTenantServiceSet;
+    }
+
+    private Map<String, String> getAuthorizationActionMap(Class<?> clazz) {
+        Map<String, String> authorizationActionMap = new HashMap<String, 
String>();
+        findAuthorizationActions(clazz, authorizationActionMap);
+        return authorizationActionMap;
+    }
+
+    /**
+     * Goes through the class hierarchy and find the authorization annotations
+     * attached to a certain
+     * method.
+     *
+     * @param clazz                  class to be scanned
+     * @param authorizationActionMap the map to be populated
+     */
+    private void findAuthorizationActions(Class<?> clazz, Map<String, String> 
authorizationActionMap) {
+        if (clazz == null || clazz == Object.class) {
+            return;
+        }
+        String classAuthorizationActionsAllowed =
+                getAuthorizationActions(clazz.getAnnotations(),
+                        AUTHORIZATION_ANNOTATION_CLASS_NAME);
+        for (Method m : clazz.getMethods()) {
+            if (SKIP_METHODS.contains(m.getName())) {
+                continue;
+            }
+            String methodAuthorizationActionsAllowed =
+                    getAuthorizationActions(m.getAnnotations(),
+                            AUTHORIZATION_ANNOTATION_CLASS_NAME);
+            String authorizationActions =
+                    methodAuthorizationActionsAllowed != null
+                            ? methodAuthorizationActionsAllowed
+                            : classAuthorizationActionsAllowed;
+            if (authorizationActions != null) {
+                authorizationActionMap.put(m.getName(), authorizationActions);
+            }
+        }
+        if (!authorizationActionMap.isEmpty()) {
+            return;
+        }
+
+        findAuthorizationActions(clazz.getSuperclass(), 
authorizationActionMap);
+
+        if (!authorizationActionMap.isEmpty()) {
+            return;
+        }
+
+        for (Class<?> interfaceCls : clazz.getInterfaces()) {
+            findAuthorizationActions(interfaceCls, authorizationActionMap);
+        }
+    }
+
+    /**
+     * Goes through the class hierarchy and figure out the supertenant
+     * annotations coupled with operations/methods.
+     *
+     * @param clazz
+     * @param superTenantServiceSet
+     */
+    private void findSuperTenantServices(Class<?> clazz, Set<String> 
superTenantServiceSet) {
+        if (clazz == null || clazz == Object.class) {
+            return;
+        }
+        for (Method m : clazz.getMethods()) {
+            if (SKIP_METHODS.contains(m.getName())) {
+                continue;
+            }
+            boolean isSuperTenantService =
+                    getSuperTenantServices(m.getAnnotations(),
+                            TENANT_ANNOTATION_CLASS_NAME);
+            if (isSuperTenantService) {
+                superTenantServiceSet.add(m.getName());
+            }
+        }
+        if (!superTenantServiceSet.isEmpty()) {
+            return;
+        }
+
+        findSuperTenantServices(clazz.getSuperclass(), superTenantServiceSet);
+
+        if (!superTenantServiceSet.isEmpty()) {
+            return;
+        }
+
+        for (Class<?> interfaceCls : clazz.getInterfaces()) {
+            findSuperTenantServices(interfaceCls, superTenantServiceSet);
+        }
+    }
+
+    private boolean getSuperTenantServices(Annotation[] annotations,
+                                           String tenantAnnotationClassName) {
+        for (Annotation ann : annotations) {
+            if 
(ann.annotationType().getName().equals(tenantAnnotationClassName)) {
+                try {
+                    Method valueMethod = 
ann.annotationType().getMethod("value", new Class[]{});
+                    boolean isSuperTenantService =
+                            (Boolean) valueMethod.invoke(ann,
+                                    new Object[]{});
+                    return isSuperTenantService;
+                } catch (Exception ex) {
+                    // ignore
+                }
+                break;
+            }
+        }
+        return false;
+    }
+
+    private String getAuthorizationActions(Annotation[] annotations,
+                                           String 
authorizationAnnotationClassName) {
+        for (Annotation ann : annotations) {
+            if 
(ann.annotationType().getName().equals(authorizationAnnotationClassName)) {
+                try {
+                    Method valueMethod = 
ann.annotationType().getMethod("value", new Class[]{});
+                    String[] permissions = (String[]) valueMethod.invoke(ann, 
new Object[]{});
+                    StringBuilder sb = new StringBuilder();
+                    for (int i = 0; i < permissions.length; i++) {
+                        sb.append(permissions[i]);
+                        if (i + 1 < permissions.length) {
+                            sb.append(",");
+                        }
+                    }
+                    return sb.toString();
+                } catch (Exception ex) {
+                    // ignore
+                }
+                break;
+            }
+        }
+        return null;
+    }
+}

Reply via email to