Commiting changes of Metadata service

This closes #37


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

Branch: refs/heads/4.0.0-grouping
Commit: a495dc130bee3152e92253335ff0f31c260456d9
Parents: 66f92f7
Author: Udara Liyanage <[email protected]>
Authored: Tue Sep 16 11:00:16 2014 +0530
Committer: Udara Liyanage <[email protected]>
Committed: Tue Sep 16 11:20:18 2014 +0530

----------------------------------------------------------------------
 .../org.apache.stratos.metadataservice/pom.xml  | 164 +++++
 .../stratos/metadataservice/Constants.java      |  29 +
 .../stratos/metadataservice/ServiceHolder.java  |  84 +++
 .../apache/stratos/metadataservice/Utils.java   |  44 ++
 .../annotation/AuthorizationAction.java         |  36 ++
 .../annotation/SuperTenantService.java          |  34 ++
 .../context/AuthenticationContext.java          |  40 ++
 .../definition/CartridgeMetaData.java           |  43 ++
 .../definition/PropertyBean.java                |  37 ++
 .../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  |  95 +++
 .../handlers/StratosAuthenticationHandler.java  | 156 +++++
 .../handlers/StratosAuthorizingHandler.java     | 333 ++++++++++
 .../metadataservice/listener/TopologyAgent.java | 112 ++++
 .../listener/TopologyListener.java              | 124 ++++
 .../oauth2/ValidationServiceClient.java         |  65 ++
 .../registry/CarbonRegistry.java                | 187 ++++++
 .../registry/DataRegistryFactory.java           |  36 ++
 .../metadataservice/registry/DataStore.java     |  36 ++
 .../metadataservice/registry/GRegRegistry.java  | 220 +++++++
 .../security/StratosPrincipal.java              |  53 ++
 .../security/StratosSecurityContext.java        |  50 ++
 .../metadataservice/services/MetaDataAdmin.java |  87 +++
 .../stratos/metadataservice/util/ConfUtil.java  |  74 +++
 .../src/main/resources/axis2_client.xml         | 299 +++++++++
 .../META-INF/webapp-classloading.xml            |  35 ++
 .../WEB-INF/cxf-servlet.xml                     |  46 ++
 .../stratosmetadataservice-test/WEB-INF/web.xml |  40 ++
 .../META-INF/webapp-classloading.xml            |  35 ++
 .../WEB-INF/cxf-servlet.xml                     |  79 +++
 .../stratosmetadataservice/WEB-INF/web.xml      |  42 ++
 .../pom.xml                                     | 320 ++++++++++
 .../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                                     |  10 +
 .../modules/distribution/src/assembly/bin.xml   |  12 +
 .../modules/distribution/src/bin/stratos.sh     |   6 +-
 .../src/main/conf/metadataservice.xml           |  37 ++
 .../distribution/src/main/license/LICENSE       |   4 +-
 products/stratos/modules/p2-profile-gen/pom.xml |  27 +-
 products/stratos/pom.xml                        |   1 +
 tools/stratos-installer/conf/setup.conf         |   5 +
 .../all/repository/conf/metadataservice.xml     |  37 ++
 .../config/greg/repository/conf/carbon.xml      | 609 +++++++++++++++++++
 tools/stratos-installer/setup.sh                |  29 +
 tools/stratos-installer/start-servers.sh        |   7 +-
 53 files changed, 4335 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.metadataservice/pom.xml 
b/components/org.apache.stratos.metadataservice/pom.xml
new file mode 100644
index 0000000..9b05574
--- /dev/null
+++ b/components/org.apache.stratos.metadataservice/pom.xml
@@ -0,0 +1,164 @@
+<!-- 
+  #  Licensed to the Apache Software Foundation (ASF) under one
+  #  or more contributor license agreements.  See the NOTICE file
+  #  distributed with this work for additional information
+  #  regarding copyright ownership.  The ASF licenses this file
+  #  to you under the Apache License, Version 2.0 (the
+  #  "License"); you may not use this file except in compliance
+  #  with the License.  You may obtain a copy of the License at
+  #  
+  #  http://www.apache.org/licenses/LICENSE-2.0
+  #  
+  #  Unless required by applicable law or agreed to in writing,
+  #  software distributed under the License is distributed on an
+  #  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  #  KIND, either express or implied.  See the License for the
+  #  specific language governing permissions and limitations
+  #  under the License.
+  -->
+<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.0.0</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.metadataservice</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>stratosmetadataservice-test</appName>
+            </properties>
+        </profile>
+        <profile>
+            <id>prod</id>
+            <activation>
+                <activeByDefault>true</activeByDefault>
+            </activation>
+            <properties>
+                <appName>stratosmetadataservice</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>stratosmetadataservice</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>4.2.0</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>4.2.0</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
+            <version>4.2.0</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.tenant.mgt</artifactId>
+            <version>${project.version}</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.registry.ws.client</artifactId>
+                        <version>4.2.0</version>
+                         <scope>provided</scope>
+               </dependency>
+               
+                 <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.ws.stub</artifactId>
+            <version>4.2.0</version>
+             <scope>provided</scope>
+        </dependency>
+       
+        
+    </dependencies>
+</project>

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

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/ServiceHolder.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/ServiceHolder.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/ServiceHolder.java
new file mode 100644
index 0000000..9b43ca4
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.TenantBillingService;
+import org.apache.stratos.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/Utils.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/Utils.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/Utils.java
new file mode 100644
index 0000000..42b100a
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice;
+
+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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/annotation/AuthorizationAction.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/annotation/AuthorizationAction.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/annotation/AuthorizationAction.java
new file mode 100644
index 0000000..a6c8765
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/annotation/SuperTenantService.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/annotation/SuperTenantService.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/annotation/SuperTenantService.java
new file mode 100644
index 0000000..761faa4
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/context/AuthenticationContext.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/context/AuthenticationContext.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/context/AuthenticationContext.java
new file mode 100644
index 0000000..7adbff6
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/context/AuthenticationContext.java
@@ -0,0 +1,40 @@
+package org.apache.stratos.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/CartridgeMetaData.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/CartridgeMetaData.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/CartridgeMetaData.java
new file mode 100644
index 0000000..dfecee4
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/CartridgeMetaData.java
@@ -0,0 +1,43 @@
+package org.apache.stratos.metadataservice.definition;
+
+import java.util.List;
+
+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 List<PropertyBean> property;
+
+       @Override
+       public String toString() {
+
+               return "applicationName: " + applicationName + ", displayName: 
" + displayName +
+                      ", description: " + description + ", type: " + type + ", 
provider: " + provider +
+                      ", host: " + host + ", Version: " + version + ", 
property: " + getProperties();
+       }
+
+       private String getProperties() {
+
+               StringBuilder propertyBuilder = new StringBuilder();
+               if (property != null) {
+                       for (PropertyBean propertyBean : property) {
+                               propertyBuilder.append(propertyBean.toString());
+                       }
+               }
+               return propertyBuilder.toString();
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/PropertyBean.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/PropertyBean.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/PropertyBean.java
new file mode 100644
index 0000000..ae4fcf8
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/definition/PropertyBean.java
@@ -0,0 +1,37 @@
+/*
+ * 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.metadataservice.definition;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "property")
+public class PropertyBean {
+
+       public String hostname;
+
+       public String username;
+       public String password;
+
+       @Override
+       public String toString() {
+               return " [ hostname: " + hostname + ", username: " + username + 
", password: " + password +
+                      "] ";
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/exception/RestAPIException.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/exception/RestAPIException.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/exception/RestAPIException.java
new file mode 100644
index 0000000..df43cc0
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/AbstractAuthenticationAuthorizationHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/AbstractAuthenticationAuthorizationHandler.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/AbstractAuthenticationAuthorizationHandler.java
new file mode 100644
index 0000000..93bf904
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CookieBasedAuthenticationHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CookieBasedAuthenticationHandler.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CookieBasedAuthenticationHandler.java
new file mode 100644
index 0000000..da50e3e
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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.metadataservice.Utils;
+import org.apache.stratos.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomExceptionMapper.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomExceptionMapper.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomExceptionMapper.java
new file mode 100644
index 0000000..0731c99
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.handlers;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+
+import org.apache.stratos.metadataservice.Utils;
+import org.apache.stratos.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomThrowableExceptionMapper.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomThrowableExceptionMapper.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomThrowableExceptionMapper.java
new file mode 100644
index 0000000..fd0e2a5
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/CustomThrowableExceptionMapper.java
@@ -0,0 +1,44 @@
+package org.apache.stratos.metadataservice.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.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/GenericExceptionMapper.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/GenericExceptionMapper.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/GenericExceptionMapper.java
new file mode 100644
index 0000000..4d2fadb
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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.metadataservice.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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/OAuthHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/OAuthHandler.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/OAuthHandler.java
new file mode 100644
index 0000000..4dc5573
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/OAuthHandler.java
@@ -0,0 +1,95 @@
+/*
+ * 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.metadataservice.handlers;
+
+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.impl.HttpHeadersImpl;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.stratos.metadataservice.context.AuthenticationContext;
+import org.apache.stratos.metadataservice.oauth2.ValidationServiceClient;
+import 
org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
+
+/**
+ * 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 {
+       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 {
+                       OAuth2TokenValidationResponseDTO respDTO;
+                       ValidationServiceClient validationServiceClient =
+                                                                         new 
ValidationServiceClient(
+                                                                               
                      oauthValidationEndpoint,
+                                                                               
                      username,
+                                                                               
                      password);
+                       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();
+                               respDTO = 
validationServiceClient.validateAuthenticationRequest(accessToken); // TODO
+                                                                               
                              // :
+                                                                               
                              // send
+                                                                               
                              // scope
+                                                                               
                              // params
+                               boolean valid = respDTO.getValid();
+                               if (!valid) {
+                                       // authorization failure..
+                                       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;
+       }
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthenticationHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthenticationHandler.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthenticationHandler.java
new file mode 100644
index 0000000..fd83b8e
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/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.metadataservice.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.metadataservice.ServiceHolder;
+import org.apache.stratos.metadataservice.Utils;
+import org.apache.stratos.metadataservice.context.AuthenticationContext;
+import org.apache.stratos.metadataservice.security.StratosSecurityContext;
+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/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthorizingHandler.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthorizingHandler.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthorizingHandler.java
new file mode 100644
index 0000000..429399f
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/handlers/StratosAuthorizingHandler.java
@@ -0,0 +1,333 @@
+/*
+ * 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.metadataservice.handlers;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+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.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.metadataservice.Utils;
+import org.apache.stratos.metadataservice.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;
+
+/**
+ * {@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.metadataservice.annotation.AuthorizationAction";
+       private static final String TENANT_ANNOTATION_CLASS_NAME =
+                                                                  
"org.apache.stratos.metadataservice.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" }));
+       }
+
+       @Override
+       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
+        * property 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;
+       }
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyAgent.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyAgent.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyAgent.java
new file mode 100644
index 0000000..b8fe918
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyAgent.java
@@ -0,0 +1,112 @@
+package org.apache.stratos.metadataservice.listener;
+
+/*
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.event.Event;
+import org.apache.stratos.messaging.event.topology.MemberSuspendedEvent;
+import org.apache.stratos.messaging.event.topology.MemberTerminatedEvent;
+import 
org.apache.stratos.messaging.listener.topology.MemberSuspendedEventListener;
+import 
org.apache.stratos.messaging.listener.topology.MemberTerminatedEventListener;
+import 
org.apache.stratos.messaging.message.receiver.topology.TopologyEventReceiver;
+import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;
+import org.apache.stratos.metadataservice.services.MetaDataAdmin;
+
+/**
+ * Cartridge agent runnable.
+ */
+public class TopologyAgent implements Runnable {
+
+       private static final Log log = LogFactory.getLog(TopologyAgent.class);
+
+       private boolean terminated;
+
+       @Override
+       public void run() {
+               if (log.isInfoEnabled()) {
+                       log.info("Topology agent started");
+               }
+
+               // Start topology event receiver thread
+               registerTopologyEventListeners();
+
+       }
+
+       protected void registerTopologyEventListeners() {
+               if (log.isDebugEnabled()) {
+                       log.debug("Starting topology event message receiver 
thread");
+               }
+               TopologyEventReceiver topologyEventReceiver = new 
TopologyEventReceiver();
+
+               topologyEventReceiver.addEventListener(new 
MemberTerminatedEventListener() {
+                       @Override
+                       protected void onEvent(Event event) {
+                               try {
+                                       log.info("Member terminated event 
received");
+                                       TopologyManager.acquireReadLock();
+                                       if (log.isDebugEnabled()) {
+                                               log.debug("Member terminated 
event received");
+                                       }
+                                       MemberTerminatedEvent 
memberTerminatedEvent = (MemberTerminatedEvent) event;
+                                       System.out.println("Terminated event 
:::::::::::::::::::: " +
+                                                          
memberTerminatedEvent.getServiceName());
+                                       new 
MetaDataAdmin().removeCartridgeMetaDataDetails("appA", "php");
+
+                               } catch (Exception e) {
+                                       if (log.isErrorEnabled()) {
+                                               log.error("Error processing 
member terminated event", e);
+                                       }
+                               } finally {
+                                       TopologyManager.releaseReadLock();
+                               }
+                       }
+               });
+
+               topologyEventReceiver.addEventListener(new 
MemberSuspendedEventListener() {
+                       @Override
+                       protected void onEvent(Event event) {
+                               try {
+                                       log.info("Member suspended event 
received");
+                                       TopologyManager.acquireReadLock();
+                                       if (log.isDebugEnabled()) {
+                                               log.debug("Member suspended 
event received");
+                                       }
+                                       MemberSuspendedEvent 
memberSuspendedEvent = (MemberSuspendedEvent) event;
+                                       // 
extensionHandler.onMemberSuspendedEvent(memberSuspendedEvent);
+                               } catch (Exception e) {
+                                       if (log.isErrorEnabled()) {
+                                               log.error("Error processing 
member suspended event", e);
+                                       }
+                               } finally {
+                                       TopologyManager.releaseReadLock();
+                               }
+                       }
+               });
+
+               Thread thread = new Thread(topologyEventReceiver);
+               thread.start();
+               if (log.isDebugEnabled()) {
+                       log.info("Cartridge Agent topology receiver thread 
started");
+               }
+       }
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyListener.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyListener.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyListener.java
new file mode 100644
index 0000000..2f09d3d
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/listener/TopologyListener.java
@@ -0,0 +1,124 @@
+package org.apache.stratos.metadataservice.listener;
+
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.event.Event;
+import org.apache.stratos.messaging.event.topology.MemberStartedEvent;
+import org.apache.stratos.messaging.event.topology.MemberSuspendedEvent;
+import org.apache.stratos.messaging.event.topology.MemberTerminatedEvent;
+import 
org.apache.stratos.messaging.listener.topology.MemberStartedEventListener;
+import 
org.apache.stratos.messaging.listener.topology.MemberSuspendedEventListener;
+import 
org.apache.stratos.messaging.listener.topology.MemberTerminatedEventListener;
+import 
org.apache.stratos.messaging.message.receiver.topology.TopologyEventReceiver;
+import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;
+import org.apache.stratos.metadataservice.services.MetaDataAdmin;
+
+public class TopologyListener implements ServletContextListener {
+
+       private static final Log log = 
LogFactory.getLog(TopologyListener.class);
+
+       private TopologyAgent topologyThread = null;
+       private Thread thread = null;
+
+       @Override
+       public void contextInitialized(ServletContextEvent arg0) {
+               log.info("Topology literner started....");
+               if (topologyThread == null) {
+                       // load default agent
+                       topologyThread = new TopologyAgent();
+                       if (log.isDebugEnabled()) {
+                               log.debug("Loading default Cartridge Agent.");
+                       }
+               }
+               // start agent
+               thread = new Thread(topologyThread);
+               thread.start();
+
+       }
+
+       @Override
+       public void contextDestroyed(ServletContextEvent arg0) {
+               thread.stop();
+       }
+
+       protected void registerTopologyEventListeners() {
+               if (log.isDebugEnabled()) {
+                       log.debug("Starting topology event message receiver 
thread");
+               }
+               TopologyEventReceiver topologyEventReceiver = new 
TopologyEventReceiver();
+
+               topologyEventReceiver.addEventListener(new 
MemberTerminatedEventListener() {
+                       @Override
+                       protected void onEvent(Event event) {
+                               try {
+                                       TopologyManager.acquireReadLock();
+                                       if (log.isDebugEnabled()) {
+                                               log.debug("Member terminated 
event received");
+                                       }
+                                       MemberTerminatedEvent 
memberTerminatedEvent = (MemberTerminatedEvent) event;
+                                       System.out.println("Terminated event 
:::::::::::::::::::: " +
+                                                          
memberTerminatedEvent.getServiceName());
+                                       new 
MetaDataAdmin().removeCartridgeMetaDataDetails("appA", "php");
+
+                                       // 
extensionHandler.onMemberTerminatedEvent(memberTerminatedEvent);
+                               } catch (Exception e) {
+                                       if (log.isErrorEnabled()) {
+                                               log.error("Error processing 
member terminated event", e);
+                                       }
+                               } finally {
+                                       TopologyManager.releaseReadLock();
+                               }
+                       }
+               });
+
+               topologyEventReceiver.addEventListener(new 
MemberSuspendedEventListener() {
+                       @Override
+                       protected void onEvent(Event event) {
+                               try {
+                                       TopologyManager.acquireReadLock();
+                                       if (log.isDebugEnabled()) {
+                                               log.debug("Member suspended 
event received");
+                                       }
+                                       MemberSuspendedEvent 
memberSuspendedEvent = (MemberSuspendedEvent) event;
+                                       // 
extensionHandler.onMemberSuspendedEvent(memberSuspendedEvent);
+                               } catch (Exception e) {
+                                       if (log.isErrorEnabled()) {
+                                               log.error("Error processing 
member suspended event", e);
+                                       }
+                               } finally {
+                                       TopologyManager.releaseReadLock();
+                               }
+                       }
+               });
+
+               topologyEventReceiver.addEventListener(new 
MemberStartedEventListener() {
+                       @Override
+                       protected void onEvent(Event event) {
+                               try {
+                                       TopologyManager.acquireReadLock();
+                                       if (log.isDebugEnabled()) {
+                                               log.debug("Member started event 
received");
+                                       }
+                                       MemberStartedEvent memberStartedEvent = 
(MemberStartedEvent) event;
+                                       // 
extensionHandler.onMemberStartedEvent(memberStartedEvent);
+                               } catch (Exception e) {
+                                       if (log.isErrorEnabled()) {
+                                               log.error("Error processing 
member started event", e);
+                                       }
+                               } finally {
+                                       TopologyManager.releaseReadLock();
+                               }
+                       }
+               });
+
+               Thread thread = new Thread(topologyEventReceiver);
+               thread.start();
+               if (log.isDebugEnabled()) {
+                       log.info("Cartridge Agent topology receiver thread 
started");
+               }
+       }
+
+}

http://git-wip-us.apache.org/repos/asf/stratos/blob/a495dc13/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/oauth2/ValidationServiceClient.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/oauth2/ValidationServiceClient.java
 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/oauth2/ValidationServiceClient.java
new file mode 100644
index 0000000..dbc8947
--- /dev/null
+++ 
b/components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/oauth2/ValidationServiceClient.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.metadataservice.oauth2;
+
+import java.rmi.RemoteException;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
+import 
org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
+import 
org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
+
+/**
+ * Service class wrapper for OAuthTokenValidation endpoint.
+ */
+public class ValidationServiceClient {
+       private OAuth2TokenValidationServiceStub stub = null;
+       private static final Log log = 
LogFactory.getLog(OAuth2TokenValidationServiceStub.class);
+
+       public ValidationServiceClient(String backendServerURL, String 
username, String password)
+                                                                               
                 throws Exception {
+               String serviceURL = backendServerURL + 
"OAuth2TokenValidationService";
+               try {
+                       stub = new OAuth2TokenValidationServiceStub(serviceURL);
+                       CarbonUtils.setBasicAccessSecurityHeaders(username, 
password, true,
+                                                                 
stub._getServiceClient());
+               } catch (AxisFault e) {
+                       log.error("Error initializing OAuth2 Client");
+                       throw new Exception("Error initializing OAuth Client", 
e);
+               }
+       }
+
+       public OAuth2TokenValidationResponseDTO 
validateAuthenticationRequest(String accessToken)
+                                                                               
                 throws Exception {
+               OAuth2TokenValidationRequestDTO oauthReq = new 
OAuth2TokenValidationRequestDTO();
+               oauthReq.setAccessToken(accessToken);
+               oauthReq.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE);
+               try {
+                       return stub.validate(oauthReq);
+               } catch (RemoteException e) {
+                       log.error("Error while validating OAuth2 request");
+                       throw new Exception("Error while validating OAuth2 
request", e);
+               }
+       }
+
+}

Reply via email to