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

[01/10] Apache Stratos Cloud Controller Component refactoring

Updated Branches:
  refs/heads/master 64777babf -> 35006acc9


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java
deleted file mode 100644
index 1c693bd..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.jclouds.compute.domain.NodeMetadata;
-
-/**
- * 
- * Holds runtime data of an IaaS
- */
-public class IaasContext implements Serializable{
-	
-    private static final long serialVersionUID = 3370272526949562217L;
-
-	private String type;
-	
-	private List<String> nodeIds;
-	
-	private Map<String, String> nodeToPublicIp;
-	
-	private transient Map<String, NodeMetadata> nodes;
-	
-	private List<String> toBeRemovedNodeIds;
-	
-	private int currentInstanceCount = 0;
-	
-	public IaasContext(String iaasType) {
-		this.type = iaasType;
-		nodeToPublicIp = new HashMap<String, String>();
-		nodeIds = new ArrayList<String>();
-		nodes = new HashMap<String, NodeMetadata>();
-		toBeRemovedNodeIds = new ArrayList<String>();
-    }
-
-	public Map<String, String> getNodeToPublicIp() {
-		return nodeToPublicIp;
-	}
-	
-	public Map<String, NodeMetadata> getNodes() {
-		return nodes;
-	}
-	
-	public void setToBeRemovedNodeIds(List<String> list) {
-		this.toBeRemovedNodeIds = list;
-	}
-	
-	public List<String> getAllNodeIds() {
-		List<String> allNodeIds = new ArrayList<String>(nodeIds);
-		allNodeIds.addAll(toBeRemovedNodeIds);
-		return allNodeIds;
-	}
-	
-	public List<String> getNodeIds() {
-		return nodeIds;
-	}
-	
-	public List<String> getToBeRemovedNodeIds() {
-		return toBeRemovedNodeIds;
-	}
-	
-	public boolean didISpawn(String nodeId) {
-		if(nodeIds.contains(nodeId) || toBeRemovedNodeIds.contains(nodeId)){
-			return true;
-		}
-		return false;
-	}
-	
-	public void addNodeId(String nodeId) {
-		nodeIds.add(nodeId);
-	}
-	
-	public void addNodeToPublicIp(String nodeId, String publicIp) {
-		nodeToPublicIp.put(nodeId, publicIp);
-	}
-	
-	public void addToBeRemovedNodeId(String nodeId) {
-		toBeRemovedNodeIds.add(nodeId);
-	}
-	
-	public void removeNodeId(String nodeId) {
-		if(nodeIds.remove(nodeId)){
-			toBeRemovedNodeIds.add(nodeId);
-		}
-	}
-	
-	public void removeToBeRemovedNodeId(String nodeId) {
-		toBeRemovedNodeIds.remove(nodeId);
-	}
-	
-	public void setNodeIds(List<String> nodeIds) {
-		this.nodeIds = nodeIds;
-	}
-	
-	public String lastlySpawnedNode() {
-		return nodeIds.get(nodeIds.size()-1);
-	}
-	
-	public void addNodeMetadata(NodeMetadata node) {
-	    if(nodes == null){
-	        nodes = new HashMap<String, NodeMetadata>();
-	    }
-		nodes.put(node.getId(), node);
-	}
-	
-    public void removeNodeMetadata(NodeMetadata node) {
-        if (nodes != null) {
-            nodes.remove(node.getId());
-        }
-    }
-	
-	public void removeNodeIdToPublicIp(String nodeId){
-		nodeToPublicIp.remove(nodeId);
-	}
-	
-	public NodeMetadata getNode(String nodeId) {
-	    if(nodes == null) {
-	        return null;
-	    }
-		return nodes.get(nodeId);
-	}
-	
-	public String getPublicIp(String nodeId){
-		return nodeToPublicIp.get(nodeId);
-	}
-
-	public String getType() {
-        return type;
-    }
-
-	public void setType(String type) {
-        this.type = type;
-    }
-
-	public int getCurrentInstanceCount() {
-	    return currentInstanceCount;
-    }
-
-	public void incrementCurrentInstanceCountByOne() {
-	    this.currentInstanceCount += 1;
-    }
-	
-	public void decrementCurrentInstanceCountByOne() {
-	    this.currentInstanceCount -= 1;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java
deleted file mode 100644
index 99ae511..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.Template;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
-
-/**
- * This is the basic data structure which holds an IaaS specific details.
- * NOTE: If you add a new attribute, please assign it in the constructor too.
- */
-public class IaasProvider implements Serializable{
-   
-    private static final long serialVersionUID = -940288190885166118L;
-
-	/**
-     * Unique id to identify this IaaS provider.
-     */
-    private String type;
-    
-    /**
-     * Fully qualified class name of an implementation of {@link Iaas}
-     */
-    private String className;
-    
-    /**
-     * human description of this IaaS provider
-     */
-    private String name;
-    
-    /**
-     * Property map of this IaaS provider.
-     */
-    private Map<String, String> properties = new HashMap<String, String>();
-    
-    /**
-     * Image identifier.
-     */
-    private String image;
-    
-    /**
-     * Max instance limit that an IaaS can spawn.
-     */
-    private int maxInstanceLimit = -1;
-    
-    /**
-     * Scale up order and scale down order of the IaaS.
-     */
-    private int scaleUpOrder = -1, scaleDownOrder = -1;
-    
-    private String provider, identity, credential;
-    
-    private transient ComputeService computeService;
-    
-    private transient Template template;
-    
-    private byte[] payload;
-    
-    /** 
-     * Corresponding {@link Iaas} implementation
-     */
-    private transient Iaas iaas;
-    
-    public IaasProvider(){}
-    
-    public IaasProvider(IaasProvider anIaasProvider){
-    	this.type = anIaasProvider.getType();
-    	this.name = anIaasProvider.getName();
-    	this.className = anIaasProvider.getClassName();
-    	this.properties = anIaasProvider.getProperties();
-    	this.image = anIaasProvider.getImage();
-    	this.scaleUpOrder = anIaasProvider.getScaleUpOrder();
-    	this.scaleDownOrder = anIaasProvider.getScaleDownOrder();
-    	this.provider = anIaasProvider.getProvider();
-    	this.identity = anIaasProvider.getIdentity();
-    	this.credential = anIaasProvider.getCredential();
-    	this.computeService = anIaasProvider.getComputeService();
-    	this.template = anIaasProvider.getTemplate();
-    	this.payload = anIaasProvider.getPayload();
-    	this.iaas = anIaasProvider.getIaas();
-    	this.maxInstanceLimit = anIaasProvider.getMaxInstanceLimit();
-    }
-    
-    public String getType() {
-        return type;
-    }
-    
-    public void setType(String id) {
-        this.type = id;
-    }
-    
-    public String getProperty(String key) {
-        return properties.get(key);
-    }
-
-    public Map<String, String> getProperties() {
-        return properties;
-    }
-    
-    public void setProperty(String key, String value) {
-        
-        if(key != null && value != null){
-            properties.put(key, value);
-        }
-    }
-
-    public void setProperties(Map<String, String> properties) {
-        this.properties = properties;
-    }
-
-    public String getImage() {
-        return image;
-    }
-
-    public void setImage(String image) {
-        this.image = image;
-    }
-
-    public int getScaleUpOrder() {
-        return scaleUpOrder;
-    }
-
-    public void setScaleUpOrder(int scaleUpOrder) {
-        this.scaleUpOrder = scaleUpOrder;
-    }
-
-    public int getScaleDownOrder() {
-        return scaleDownOrder;
-    }
-
-    public void setScaleDownOrder(int scaleDownOrder) {
-        this.scaleDownOrder = scaleDownOrder;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getProvider() {
-        return provider;
-    }
-
-    public void setProvider(String provider) {
-        this.provider = provider;
-    }
-
-    public String getIdentity() {
-        return identity;
-    }
-
-    public void setIdentity(String identity) {
-        this.identity = identity;
-    }
-
-    public String getCredential() {
-        return credential;
-    }
-
-    public void setCredential(String credential) {
-        this.credential = credential;
-    }
-
-    public ComputeService getComputeService() {
-        return computeService;
-    }
-
-    public void setComputeService(ComputeService computeService) {
-        this.computeService = computeService;
-    }
-
-    public Template getTemplate() {
-        return template;
-    }
-
-    public void setTemplate(Template template) {
-        this.template = template;
-    }
-    
-    
-
-    public boolean equals(Object o) {
-        if(o instanceof IaasProvider){
-            return ((IaasProvider) o).getType().equals(this.getType());
-        }
-        
-        return false;
-    }
-    
-    public int hashCode() {
-        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
-            append(type).
-            toHashCode();
-    }
-    
-    public IaasProvider copy(){
-		return new IaasProvider(this);
-	}
-
-    public String getClassName() {
-        return className;
-    }
-
-    public void setClassName(String className) {
-        this.className = className;
-    }
-
-    public byte[] getPayload() {
-        return payload;
-    }
-
-    public void setPayload(byte[] payload) {
-        this.payload = payload;
-    }
-
-    public Iaas getIaas() {
-        return iaas;
-    }
-
-    public void setIaas(Iaas iaas) {
-        this.iaas = iaas;
-    }
-    
-    public void reset(){
-//    	nodeIds = new ArrayList<String>();
-//    	nodes = new HashMap<String, NodeMetadata>();
-//    	toBeRemovedNodeIds = new ArrayList<String>();
-    }
-
-	public int getMaxInstanceLimit() {
-	    return this.maxInstanceLimit;
-    }
-
-	public void setMaxInstanceLimit(int maxInstanceLimit) {
-	    this.maxInstanceLimit = maxInstanceLimit;
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java
deleted file mode 100644
index 53649a8..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.Serializable;
-
-public class PortMapping implements Serializable{
-	
-    private static final long serialVersionUID = -5387564414633460306L;
-	private String protocol;
-	private String port;
-	private String proxyPort;
-	
-	public PortMapping(){
-		
-	}
-	
-	public PortMapping(String protocol, String port, String proxyPort){
-		this.protocol = protocol;
-		this.port = port;
-		this.proxyPort = proxyPort;
-	}
-
-	public String getProtocol() {
-    	return protocol;
-    }
-
-	public void setProtocol(String protocol) {
-    	this.protocol = protocol;
-    }
-
-	public String getPort() {
-    	return port;
-    }
-
-	public void setPort(String port) {
-    	this.port = port;
-    }
-
-	public String getProxyPort() {
-    	return proxyPort;
-    }
-
-	public void setProxyPort(String proxyPort) {
-    	this.proxyPort = proxyPort;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java
deleted file mode 100644
index 88c5d92..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-/**
- * Had to wrap {@link Property} array using a class, since there's a bug in current 
- * stub generation.
- */
-public class Properties {
-
-	private Property[] properties;
-
-	public Property[] getProperties() {
-	    return properties;
-    }
-
-	public void setProperties(Property[] properties) {
-	    this.properties = properties;
-    }
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java
deleted file mode 100644
index 63dac14..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.util;
-/**
- * Holds a property 
- */
-public class Property {
-	
-	private String name;
-	private String value;
-	
-	public Property(){
-		
-	}
-	
-	public Property(String name, String value){
-		this.setName(name);
-		this.setValue(value);
-	}
-
-	public String getName() {
-	    return name;
-    }
-
-	public void setName(String name) {
-	    this.name = name;
-    }
-
-	public String getValue() {
-	    return value;
-    }
-
-	public void setValue(String value) {
-	    this.value = value;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java
deleted file mode 100644
index 4e589ae..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.wso2.carbon.lb.common.conf.structure.Node;
-import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-
-/**
- * We keep information regarding a service (i.e. a cartridge instance)
- * in this object.
- */
-public class ServiceContext implements Serializable{
-
-    private static final long serialVersionUID = -6740964802890082678L;
-    private File file;
-	private String domainName;
-    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
-    private String tenantRange;
-    private String hostName;
-    private String payloadFilePath;
-    private String cartridgeType;
-    private Cartridge cartridge;
-    private byte[] payload;
-    /**
-     * Key - Value pair.
-     */
-    private Map<String, String> properties = new HashMap<String, String>();
-    /**
-     * Key - IaaS Type
-     * Value - {@link IaasContext} object
-     */
-    private Map<String, IaasContext> iaasCtxts = new HashMap<String, IaasContext>();
-	
-    public Map<String, IaasContext> getIaasCtxts() {
-    	return iaasCtxts;
-    }
-
-	public String getDomainName() {
-        return domainName;
-    }
-    
-    public boolean setDomainName(String domainName) {
-        if (!"".equals(domainName)) {
-            this.domainName = domainName;
-            return true;
-        }
-        
-        return false;
-    }
-    
-    public void setProperty(String key, String value) {
-        properties.put(key, value);
-    }
-    
-    public String getProperty(String key) {
-        
-        if(properties.containsKey(key)){
-            return properties.get(key);
-        }
-        
-        return "";
-    }
-
-    public Map<String, String> getProperties() {
-        return properties;
-    }
-
-    public void setProperties(Map<String, String> properties) {
-        this.properties = properties;
-    }
-    
-    public String getSubDomainName() {
-        return subDomainName;
-    }
-
-    public void setSubDomainName(String subDomainName) {
-        if(subDomainName == null || "".equals(subDomainName)){
-            return;
-        }
-        this.subDomainName = subDomainName;
-    }
-
-    public Cartridge getCartridge() {
-        return cartridge;
-    }
-
-    public void setCartridge(Cartridge cartridge) {
-        this.cartridge = cartridge;
-    }
-
-	public String getTenantRange() {
-	    return tenantRange;
-    }
-
-	public void setTenantRange(String tenantRange) {
-	    this.tenantRange = tenantRange;
-    }
-	
-	public IaasContext addIaasContext(String iaasType){
-		IaasContext ctxt = new IaasContext(iaasType);
-		iaasCtxts.put(iaasType, ctxt);
-		return ctxt;
-	}
-	
-	public IaasContext getIaasContext(String type){
-		return iaasCtxts.get(type);
-	}
-	
-	public void setIaasContextMap(Map<String, IaasContext> map){
-		iaasCtxts = map;
-	}
-	
-//	public byte[] getPayload() {
-//    	return payload;
-//    }
-//
-//	public void setPayload(byte[] payload) {
-//    	this.payload = payload;
-//    }
-
-
-	public String getPayloadFile() {
-	    return payloadFilePath;
-    }
-
-	public void setPayloadFile(String payloadFile) {
-	    this.payloadFilePath = payloadFile;
-    }
-
-	public String getHostName() {
-		if(cartridge != null && (hostName == null || hostName.isEmpty())){
-			return cartridge.getHostName();
-		}
-	    return hostName;
-    }
-
-	public void setHostName(String hostName) {
-	    this.hostName = hostName;
-    }
-
-	public String getCartridgeType() {
-	    return cartridgeType;
-    }
-
-	public void setCartridgeType(String cartridgeType) {
-	    this.cartridgeType = cartridgeType;
-    }
-
-	public byte[] getPayload() {
-	    return payload;
-    }
-
-	public void setPayload(byte[] payload) {
-	    this.payload = payload;
-    }
-	
-	public String toXml() {
-		String str =
-				payloadFilePath == null ? "<service domain=\"" + domainName +
-				                        "\" subDomain=\"" + subDomainName +
-				                        "\" tenantRange=\"" + tenantRange + "\">\n" +
-				                        "\t<cartridge type=\"" + cartridgeType +
-				                        "\"/>\n" + "\t<host>" + hostName +
-				                        "</host>\n" + "</service>"
-				                        
-		                                    : "<service domain=\"" + domainName +
-		                                    "\" subDomain=\"" + subDomainName +
-		                                    "\" tenantRange=\"" + tenantRange + "\">\n" +
-		                                    "\t<cartridge type=\"" + cartridgeType +
-		                                    "\"/>\n"  + "\t<host>" + hostName +
-		                                    "</host>\n" + "\t<payload>" + payloadFilePath +
-		                                    "</payload>\n" +
-		                                    propertiesToXml() +
-		                                    "</service>";
-		return str;
-	}
-	
-	public Node toNode() {
-		Node node = new Node();
-		node.setName(cartridgeType);
-		String sbrace = Constants.NGINX_NODE_START_BRACE;
-		String ebrace = Constants.NGINX_NODE_END_BRACE;
-		String delimiter = Constants.NGINX_LINE_DELIMITER;
-		String newLine = "\n";
-		String nginx = 
-				Constants.DOMAIN_ELEMENT+sbrace+newLine+
-				domainName+sbrace+newLine+
-				Constants.HOSTS_ELEMENT+" "+hostName+delimiter+newLine+
-				Constants.SUB_DOMAIN_ELEMENT+" "+subDomainName+delimiter+newLine+
-				Constants.TENANT_RANGE_ELEMENT+" "+tenantRange+delimiter+newLine+
-				propertiesToNginx()+
-				ebrace+newLine+
-				ebrace+newLine;
-		
-		return NodeBuilder.buildNode(node, nginx);
-		
-	}
-	
-	/**
-	 * Had to made this public in order to access from a test case.
-	 * @return
-	 */
-	public String propertiesToNginx() {
-		StringBuilder builder = new StringBuilder("");
-		for (Iterator<Entry<String, String>> iterator = getProperties().entrySet().iterator(); iterator.hasNext();) {
-			Map.Entry<String, String> prop = (Map.Entry<String, String>) iterator.next();
-
-			String key = prop.getKey();
-			String value = prop.getValue();
-			if (key != null) {
-				builder.append(key + " " + (value == null ? "" : value) +
-				               Constants.NGINX_LINE_DELIMITER + "\n");
-			}
-
-		}
-
-		return builder.toString();
-	}
-	
-	public String propertiesToXml() {
-		StringBuilder builder = new StringBuilder("");
-		for (Iterator<Entry<String, String>> iterator = getProperties().entrySet().iterator(); iterator.hasNext();) {
-			Map.Entry<String, String> prop = (Map.Entry<String, String>) iterator.next();
-
-			String key = prop.getKey();
-			String value = prop.getValue();
-			if (key != null) {
-				builder.append("\t<property name=\""+key +"\" value=\"" + (value == null ? "" : value) +"\"/>\n");
-			}
-
-		}
-
-		return builder.toString();
-	}
-	
-	public File getFile() {
-		return file;
-	}
-	
-	public void setFile(File file) {
-		this.file = file;
-	}
-	
-	public boolean equals(Object obj) {
-		if (obj instanceof ServiceContext) {
-			return this.domainName.equals(((ServiceContext) obj).getDomainName()) &&
-			       this.subDomainName.equals(((ServiceContext) obj).getSubDomainName());
-		}
-		return false;
-	}
-    
-    public int hashCode() {
-        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
-            append(domainName).
-            append(subDomainName).
-            toHashCode();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
deleted file mode 100644
index e3e9861..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<!--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. 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.
- -->
-<component xmlns="http://products.wso2.org/carbon">
-    <deployers>
-    	<deployer>
-            <directory>../../conf</directory>
-            <extension>xml</extension>
-            <class>org.wso2.carbon.stratos.cloud.controller.deployers.CloudControllerDeployer</class>
-        </deployer>
-        <deployer>
-            <directory>cartridges</directory>
-            <extension>xml</extension>
-            <class>org.wso2.carbon.stratos.cloud.controller.deployers.CartridgeDeployer</class>
-        </deployer>
-        <deployer>
-            <directory>services</directory>
-            <extension>xml</extension>
-            <class>org.wso2.carbon.stratos.cloud.controller.deployers.ServiceDeployer</class>
-        </deployer>
-    </deployers>
-</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 7d71f78..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<serviceGroup>
-    <service name="CloudControllerService" scope="application">
-        <parameter name="ServiceClass">org.wso2.carbon.stratos.cloud.controller.impl.CloudControllerServiceImpl</parameter>
-        <messageReceivers>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
-    </messageReceivers>
-    </service>
-</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
deleted file mode 100644
index 6887211..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
+++ /dev/null
@@ -1,133 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-  <xs:element name="cartridge">
-    <xs:annotation>
-      <xs:documentation>You can have 1..n cartridge elements.</xs:documentation>
-    </xs:annotation>
-    <xs:complexType>
-    	<xs:choice maxOccurs="unbounded">
-    		<xs:element name="property" maxOccurs="unbounded"
-    			minOccurs="0">
-    			<xs:annotation>
-    				<xs:documentation>
-    					cartridge element can have 0..n properties, and
-    					they'll be overwritten by the properties
-    					specified under iaasProvider child elements of
-    					cartridge element.
-    				</xs:documentation>
-    			</xs:annotation>
-    			<xs:complexType>
-    				<xs:simpleContent>
-    					<xs:extension base="xs:string">
-    						<xs:attribute type="xs:string" name="name" />
-    						<xs:attribute type="xs:string" name="value" />
-    					</xs:extension>
-    				</xs:simpleContent>
-    			</xs:complexType>
-    		</xs:element>
-    		<xs:element name="displayName" maxOccurs="1" minOccurs="0" />
-    		<xs:element name="description" maxOccurs="1" minOccurs="0" />
-    		<xs:element name="iaasProvider" maxOccurs="unbounded"
-    			minOccurs="1">
-    			<xs:annotation>
-    				<xs:documentation>
-    					A cartridge element should add a reference to an
-    					existing IaaS provider (specified in the above
-    					&amp;lt;iaasProviders&amp;gt; section) or it can
-    					create a completely new IaaS Provider (which
-    					should have a unique "type" attribute.
-    				</xs:documentation>
-    			</xs:annotation>
-    			<xs:complexType>
-    				<xs:choice maxOccurs="unbounded">
-                        <xs:element type="xs:string" name="scaleUpOrder"
-    						minOccurs="0" maxOccurs="1" />
-                        <xs:element type="xs:string" name="scaleDownOrder"
-    						minOccurs="0" maxOccurs="1" />
-                        <xs:element type="xs:string" name="maxInstanceLimit"
-    						minOccurs="0" maxOccurs="1" />
-    					<xs:element type="xs:string" name="imageId"
-    						minOccurs="0" maxOccurs="1" />
-    					<xs:element name="property"
-    						maxOccurs="unbounded" minOccurs="0">
-    						<xs:complexType>
-    							<xs:simpleContent>
-    								<xs:extension base="xs:string">
-    									<xs:attribute type="xs:string"
-    										name="name" />
-    									<xs:attribute type="xs:string"
-    										name="value" />
-    								</xs:extension>
-    							</xs:simpleContent>
-    						</xs:complexType>
-    					</xs:element>
-    				</xs:choice>
-    				<xs:attribute type="xs:string" name="type" />
-    			</xs:complexType>
-    		</xs:element>
-    		<xs:element name="deployment" maxOccurs="1" minOccurs="1">
-    			<xs:complexType>
-    				<xs:choice maxOccurs="unbounded">
-    					<xs:element name="dir" maxOccurs="unbounded"
-    						minOccurs="0" type="xs:string">
-    					</xs:element>
-    				</xs:choice>
-    				<xs:attribute name="baseDir" type="xs:string">
-    				</xs:attribute>
-    			</xs:complexType>
-    		</xs:element>
-    		<xs:element name="portMapping" maxOccurs="1"
-    			minOccurs="1">
-    			<xs:complexType>
-    				<xs:choice maxOccurs="unbounded">
-    					<xs:element name="http" maxOccurs="1"
-    						minOccurs="1">
-    						<xs:complexType>
-    							<xs:attribute name="port"
-    								type="xs:string" />
-    							<xs:attribute name="proxyPort"
-    								type="xs:string" />
-    						</xs:complexType>
-    					</xs:element>
-    					<xs:element name="https" maxOccurs="1"
-    						minOccurs="0">
-    						<xs:complexType>
-    							<xs:attribute name="port"
-    								type="xs:string" />
-    							<xs:attribute name="proxyPort"
-    								type="xs:string" />
-    						</xs:complexType>
-    					</xs:element>
-    				</xs:choice>
-    			</xs:complexType>
-    		</xs:element>
-    		<xs:element name="appTypes" maxOccurs="1"
-    			minOccurs="1">
-    			<xs:complexType>
-    				<xs:choice maxOccurs="unbounded">
-    					<xs:element name="appType" maxOccurs="unbounded"
-    						minOccurs="1">
-    						<xs:complexType>
-                                    <xs:attribute name="name" type="xs:string" use="required" />
-                                    <xs:attribute name="appSpecificMapping"
-    								type="xs:string" />
-    						</xs:complexType>
-    					</xs:element>
-    				</xs:choice>
-    			</xs:complexType>
-    		</xs:element>
-    	</xs:choice>
-    	<xs:attribute type="xs:string" name="type" />
-    	<xs:attribute type="xs:string" name="host" />
-    	<xs:attribute type="xs:string" name="provider" />
-    	<xs:attribute type="xs:string" name="version" />
-    	<xs:attribute type="xs:boolean" name="multiTenant" />
-    </xs:complexType>
-  </xs:element>
-
-  <!-- <xs:complexType name="deploymentType">
-  	<xs:sequence>
-  		<xs:element name="dir" type="xs:string" maxOccurs="1" minOccurs="1"></xs:element>
-  	</xs:sequence>
-  </xs:complexType> -->
-</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
deleted file mode 100644
index 3b187a7..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
+++ /dev/null
@@ -1,144 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-  <xs:element name="cartridges" >
-    <xs:annotation>
-      <xs:documentation>Use below section to specify properties that are needed in order to start Cartridges.</xs:documentation>
-    </xs:annotation>
-    <xs:complexType>
-    <xs:sequence>
-      <xs:choice maxOccurs="unbounded">
-        <xs:element name="cartridge" maxOccurs="unbounded" minOccurs="1">
-          <xs:annotation>
-            <xs:documentation>You can have 1..n cartridge elements.</xs:documentation>
-          </xs:annotation>
-          <xs:complexType>
-            <xs:choice maxOccurs="unbounded">
-            	<xs:element name="property" maxOccurs="unbounded"
-            		minOccurs="0">
-            		<xs:annotation>
-            			<xs:documentation>
-            				cartridge element can have 0..n properties,
-            				and they'll be overwritten by the properties
-            				specified under iaasProvider child elements
-            				of cartridge element.
-            			</xs:documentation>
-            		</xs:annotation>
-            		<xs:complexType>
-            			<xs:simpleContent>
-            				<xs:extension base="xs:string">
-            					<xs:attribute type="xs:string"
-            						name="name" />
-            					<xs:attribute type="xs:string"
-            						name="value" />
-            				</xs:extension>
-            			</xs:simpleContent>
-            		</xs:complexType>
-            	</xs:element>
-            	<xs:element name="displayName" maxOccurs="1"
-            		minOccurs="0" />
-            	<xs:element name="description" maxOccurs="1"
-            		minOccurs="0" />
-            	<xs:element name="iaasProvider" maxOccurs="unbounded"
-            		minOccurs="1">
-            		<xs:annotation>
-            			<xs:documentation>
-            				A cartridge element should add a reference
-            				to an existing IaaS provider (specified in
-            				the above &amp;lt;iaasProviders&amp;gt;
-            				section) or it can create a completely new
-            				IaaS Provider (which should have a unique
-            				"type" attribute.
-            			</xs:documentation>
-            		</xs:annotation>
-            		<xs:complexType>
-            			<xs:choice maxOccurs="unbounded">
-                            <xs:element type="xs:string" name="scaleUpOrder"
-    						    minOccurs="0" maxOccurs="1" />
-                            <xs:element type="xs:string" name="scaleDownOrder"
-    						    minOccurs="0" maxOccurs="1" />
-                            <xs:element type="xs:string" name="maxInstanceLimit"
-    						    minOccurs="0" maxOccurs="1" />
-            				<xs:element type="xs:string" name="imageId"
-            					minOccurs="0" maxOccurs="1" />
-            				<xs:element name="property"
-            					maxOccurs="unbounded" minOccurs="0">
-            					<xs:complexType>
-            						<xs:simpleContent>
-            							<xs:extension
-            								base="xs:string">
-            								<xs:attribute
-            									type="xs:string" name="name" />
-            								<xs:attribute
-            									type="xs:string" name="value" />
-            							</xs:extension>
-            						</xs:simpleContent>
-            					</xs:complexType>
-            				</xs:element>
-            			</xs:choice>
-            			<xs:attribute type="xs:string" name="type" />
-            		</xs:complexType>
-            	</xs:element>
-            	<xs:element name="deployment" maxOccurs="1">
-            		<xs:complexType>
-            			<xs:choice maxOccurs="unbounded">
-            				<xs:element name="dir" maxOccurs="unbounded"
-            					minOccurs="0" type="xs:string">
-            				</xs:element>
-            			</xs:choice>
-            			<xs:attribute name="baseDir" type="xs:string">
-            			</xs:attribute>
-            		</xs:complexType>
-            	</xs:element>
-            	<xs:element name="portMapping" maxOccurs="1"
-            		minOccurs="1">
-            		<xs:complexType>
-            			<xs:choice maxOccurs="unbounded">
-            				<xs:element name="http" maxOccurs="1"
-            					minOccurs="1">
-            					<xs:complexType>
-            						<xs:attribute name="port"
-            							type="xs:string" />
-            						<xs:attribute name="proxyPort"
-            							type="xs:string" />
-            					</xs:complexType>
-            				</xs:element>
-            				<xs:element name="https" maxOccurs="1"
-            					minOccurs="0">
-            					<xs:complexType>
-            						<xs:attribute name="port"
-            							type="xs:string" />
-            						<xs:attribute name="proxyPort"
-            							type="xs:string" />
-            					</xs:complexType>
-            				</xs:element>
-            			</xs:choice>
-            		</xs:complexType>
-            	</xs:element>
-            	<xs:element name="appTypes" maxOccurs="1"
-    			minOccurs="1">
-    			<xs:complexType>
-    				<xs:choice maxOccurs="unbounded">
-    					<xs:element name="appType" maxOccurs="unbounded"
-    						minOccurs="1">
-    						<xs:complexType>
-                                    <xs:attribute name="name" type="xs:string" use="required" />
-                                    <xs:attribute name="appSpecificMapping"
-    								type="xs:string" />
-    						</xs:complexType>
-    					</xs:element>
-    				</xs:choice>
-    			</xs:complexType>
-    		</xs:element>
-            </xs:choice>
-            <xs:attribute type="xs:string" name="type"/>
-            <xs:attribute type="xs:string" name="host" />
-            <xs:attribute type="xs:string" name="provider" />
-            <xs:attribute type="xs:string" name="version" />
-            <xs:attribute type="xs:boolean" name="multiTenant" />
-          </xs:complexType>
-        </xs:element>
-      </xs:choice>
-      </xs:sequence>
-    </xs:complexType>
-  </xs:element>
-</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
deleted file mode 100644
index 48a8532..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
+++ /dev/null
@@ -1,46 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-        <xs:element name="service">
-          <xs:annotation>
-            <xs:documentation>you can have 0..n service elements</xs:documentation>
-          </xs:annotation>
-          <xs:complexType>
-          	<xs:choice maxOccurs="unbounded">
-          		<xs:element name="cartridge">
-          			<xs:annotation>
-          				<xs:documentation>
-          					this element's value should be a reference
-          					to an existing cartridge
-          				</xs:documentation>
-          			</xs:annotation>
-          			<xs:complexType>
-          				<xs:simpleContent>
-          					<xs:extension base="xs:string">
-          						<xs:attribute type="xs:string"
-          							name="type" />
-          					</xs:extension>
-          				</xs:simpleContent>
-          			</xs:complexType>
-          		</xs:element>
-          		<xs:element name="payload" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
-          		<xs:element name="host" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
-          		<xs:element name="property"
-    						maxOccurs="unbounded" minOccurs="0">
-    						<xs:complexType>
-    							<xs:simpleContent>
-    								<xs:extension base="xs:string">
-    									<xs:attribute type="xs:string"
-    										name="name" />
-    									<xs:attribute type="xs:string"
-    										name="value" />
-    								</xs:extension>
-    							</xs:simpleContent>
-    						</xs:complexType>
-    					</xs:element>
-          	</xs:choice>
-          	<xs:attribute type="xs:string" name="domain" />
-          	<xs:attribute type="xs:string" name="tenantRange" />
-          	<xs:attribute type="xs:string" name="subDomain" />
-          </xs:complexType>
-        </xs:element>
-</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
deleted file mode 100644
index 5fc9fb7..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-  <xs:element name="services">
-    <xs:annotation>
-      <xs:documentation>Here you specify the service domains related details.</xs:documentation>
-    </xs:annotation>
-    <xs:complexType>
-      <xs:choice maxOccurs="unbounded">
-        <xs:element name="service" maxOccurs="unbounded" minOccurs="1">
-          <xs:annotation>
-            <xs:documentation>you can have 0..n service elements</xs:documentation>
-          </xs:annotation>
-          <xs:complexType>
-            <xs:choice maxOccurs="unbounded">
-              <xs:element name="cartridge">
-                <xs:annotation>
-                  <xs:documentation>this element's value should be a reference to an existing cartridge</xs:documentation>
-                </xs:annotation>
-                <xs:complexType>
-                  <xs:simpleContent>
-                    <xs:extension base="xs:string">
-                      <xs:attribute type="xs:string" name="type"/>
-                    </xs:extension>
-                  </xs:simpleContent>
-                </xs:complexType>
-              </xs:element>
-              <xs:element name="payload" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
-              <xs:element name="host" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
-              <xs:element name="property"
-    						maxOccurs="unbounded" minOccurs="0">
-    						<xs:complexType>
-    							<xs:simpleContent>
-    								<xs:extension base="xs:string">
-    									<xs:attribute type="xs:string"
-    										name="name" />
-    									<xs:attribute type="xs:string"
-    										name="value" />
-    								</xs:extension>
-    							</xs:simpleContent>
-    						</xs:complexType>
-    					</xs:element>
-            </xs:choice>
-            <xs:attribute type="xs:string" name="domain"/>
-            <xs:attribute type="xs:string" name="subDomain"/>
-            <xs:attribute type="xs:string" name="tenantRange" />
-          </xs:complexType>
-        </xs:element>
-      </xs:choice>
-    </xs:complexType>
-  </xs:element>
-</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
deleted file mode 100644
index c277203..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.cartridge.autoscaler.service.axiom;
-
-import java.io.File;
-
-import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
-import org.xml.sax.SAXParseException;
-
-import junit.framework.TestCase;
-
-public class AxiomValidationTest extends TestCase {
-    
-    AxiomXpathParser util1, util2, util3, util4, util5, util6, util7, util8, util9;
-    File xmlSchemaCartridges = new File("src/main/resources/cartridges.xsd");
-    File xmlSchemaCartridge = new File("src/main/resources/cartridge.xsd");
-    String dir = "src/test/resources/";
-
-    public AxiomValidationTest(String name) {
-        super(name);
-    }
-    
-    protected void setUp() throws Exception {
-        super.setUp();
-        util1 = new AxiomXpathParser(new File(dir+"cartridges-1.xml"));
-        util2 = new AxiomXpathParser(new File(dir+"cartridges-2.xml"));
-        util3 = new AxiomXpathParser(new File(dir+"cartridges-3.xml"));
-        util4 = new AxiomXpathParser(new File(dir+"cartridges-4.xml"));
-        util5 = new AxiomXpathParser(new File(dir+"cartridges-5.xml"));
-        util6 = new AxiomXpathParser(new File(dir+"cartridges-6.xml"));
-        util7 = new AxiomXpathParser(new File(dir+"cartridges-7.xml"));
-        util8 = new AxiomXpathParser(new File(dir+"cartridges-8.xml"));
-        util9 = new AxiomXpathParser(new File(dir+"cartridges-9.xml"));
-        util1.parse();
-        util2.parse();
-        util3.parse();
-        util4.parse();
-        util5.parse();
-        util6.parse();
-        util7.parse();
-        util8.parse();
-        util9.parse();
-    }
-
-    public final void testCartridgeValidation() throws Exception {
-        
-        // schema 1 - cartridges 
-        assertEquals(true, util1.validate(xmlSchemaCartridges));
-        
-        assertEquals(true, util5.validate(xmlSchemaCartridges));
-        
-        assertEquals(true, util6.validate(xmlSchemaCartridges));
-        
-        assertEquals(true, util7.validate(xmlSchemaCartridges));
-        
-        assertEquals(true, util9.validate(xmlSchemaCartridges));
-        
-        // schema 2 - cartridge
-        assertEquals(true, util2.validate(xmlSchemaCartridge));
-        
-        assertEquals(true, util8.validate(xmlSchemaCartridge));
-    }
-    
-    public final void testCartridgeInvalidation() {
-        
-     // schema 1 - cartridges 
-        try {
-            util2.validate(xmlSchemaCartridges);
-        } catch (Exception e) {
-            assertEquals(SAXParseException.class, e.getClass());
-        }
-        
-        try {
-            util3.validate(xmlSchemaCartridges);
-        } catch (Exception e) {
-
-            assertEquals(SAXParseException.class, e.getClass());
-        }
-        
-        try {
-            util4.validate(xmlSchemaCartridges);
-        } catch (Exception e) {
-
-            assertEquals(SAXParseException.class, e.getClass());
-        }
-        
-        // schema 2 - cartridge
-        
-        try {
-            util1.validate(xmlSchemaCartridge);
-        } catch (Exception e) {
-
-            assertEquals(SAXParseException.class, e.getClass());
-        }
-        
-        try {
-            util3.validate(xmlSchemaCartridge);
-        } catch (Exception e) {
-
-            assertEquals(SAXParseException.class, e.getClass());
-        }
-        
-        try {
-            util4.validate(xmlSchemaCartridge);
-        } catch (Exception e) {
-
-            assertEquals(SAXParseException.class, e.getClass());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
deleted file mode 100644
index d886db1..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.cartridge.autoscaler.service.axiom;
-
-import java.io.File;
-import java.util.List;
-
-import org.apache.axiom.om.OMNode;
-import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-
-import junit.framework.TestCase;
-
-public class AxiomXpathParserTest extends TestCase {
-    AxiomXpathParser parser;
-    File xmlFile = new File("src/test/resources/cloud-controller.xml");
-
-    public AxiomXpathParserTest(String name) {
-        super(name);
-    }
-
-    protected void setUp() throws Exception {
-        super.setUp();
-        parser = new AxiomXpathParser(xmlFile);
-        parser.parse();
-    }
-    
-    public void testGetMatchingNodes(){
-        List<OMNode> list = parser.getMatchingNodes("/cloudController/iaasProviders/iaasProvider/provider");
-        assertEquals(1, list.size());
-        parser.setIaasProvidersList();
-        assertEquals(1, FasterLookUpDataHolder.getInstance().getIaasProviders().size());
-        assertEquals(5, FasterLookUpDataHolder.getInstance().getIaasProviders().get(0).getMaxInstanceLimit());
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java
deleted file mode 100644
index 2cfcfa2..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.cartridge.autoscaler.service.util;
-
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-import junit.framework.TestCase;
-
-public class ServiceContextTest extends TestCase {
-    
-    ServiceContext ctxt = new ServiceContext();
-
-    public ServiceContextTest(String name) {
-        super(name);
-    }
-    
-    protected void setUp() throws Exception {
-        super.setUp();
-        ctxt.setProperty("min_app_instances", "2");
-        ctxt.setProperty("max_app_instances", "5");
-        ctxt.setProperty("public_ip", null);
-    }
-
-    public final void testPropertiesToNginx() throws Exception {
-    	assertEquals(true, ctxt.propertiesToNginx().contains("min_app_instances 2;\n"));
-    	assertEquals(true, ctxt.propertiesToNginx().contains("max_app_instances 5;\n"));
-    	assertEquals(true, ctxt.propertiesToNginx().contains("public_ip ;\n"));
-    }
-    
-    public final void testPropertiesToXml() throws Exception {
-    	System.out.println(ctxt.propertiesToXml());
-    	assertEquals(true, ctxt.propertiesToXml().contains("name=\"min_app_instances\" value=\"2\""));
-    }
-   
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
deleted file mode 100644
index 2eccd3d..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php" host="abc.com" provider="carbon">
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			<property name="ss" value="slsls"/>
-			<description>This is a php cartridge.</description>
-			<deployment baseDir="xyz">
-				<dir>abc</dir>
-			</deployment>
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
deleted file mode 100644
index b0fe963..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-	<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php">
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-			<deployment>
-				<dir>abc/def</dir>
-			</deployment>
-			
-			<appTypes>
-				<appType name="axis2services" appSpecificMapping="true"/>
-				<appType name="webapps" appSpecificMapping="false"/>
-			</appTypes>
-		</cartridge>
-	
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
deleted file mode 100644
index eb6d565..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php">
-		
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			
-			<deployment>
-				<dir>abc</dir>
-			</deployment>
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
deleted file mode 100644
index 2f82ce8..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge>
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-
-			<deployment>
-				<dir>abc</dir>
-				<dir>def</dir>
-			</deployment>
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
deleted file mode 100644
index 705d020..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php">
-			
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-			<deployment>
-				<dir>abc</dir>
-			</deployment>
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
deleted file mode 100644
index 28ac6fb..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php">
-			
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-			</iaasProvider>
-		
-			<deployment>
-				<dir>abc</dir>
-			</deployment>
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
deleted file mode 100644
index 0baa407..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php" version="5.1">
-			<!-- Display name of this cartridge -->
-			<displayName>PHP</displayName>
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-			</iaasProvider>
-		
-			<deployment>
-				<dir>abc</dir>
-			</deployment>
-		</cartridge>
-	
-	</cartridges>
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php" version="5.1">
-			<!-- Display name of this cartridge -->
-			<displayName>PHP</displayName>
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-			</iaasProvider>
-		
-			<deployment>
-				<dir>abc</dir>
-			</deployment>
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
deleted file mode 100644
index 8d43239..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
+++ /dev/null
@@ -1,72 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-	<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php" version="5">
-			<!-- Display name of this cartridge -->
-			<displayName>PHP</displayName>
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-			<deployment>
-				<dir>abc/def</dir>
-			</deployment>
-			
-			<appTypes>
-				<appType name="axis2services" appSpecificMapping="true"/>
-				<appType name="webapps" appSpecificMapping="false"/>
-			</appTypes>
-		</cartridge>
-	
-<?xml version="1.0" encoding="ISO-8859-1"?>
-	<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="php" version="5">
-			<!-- Display name of this cartridge -->
-			<displayName>PHP</displayName>
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-			<deployment>
-				<dir>abc/def</dir>
-			</deployment>
-			
-			<appTypes>
-				<appType name="axis2services" appSpecificMapping="true"/>
-				<appType name="webapps" appSpecificMapping="false"/>
-			</appTypes>
-		</cartridge>
-	
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
deleted file mode 100644
index 969091a..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
+++ /dev/null
@@ -1,66 +0,0 @@
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="as" host="abc.com" provider="carbon" version="5.1.0" multiTenant="true">
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			<property name="ss" value="slsls"/>
-			<description>This is a WSO2 AS cartridge.</description>
-			<deployment baseDir="xyz">
-				<dir>abc</dir>
-			</deployment>
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-		</cartridge>
-	
-	</cartridges>
-<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
-	<cartridges>
-	
-		<!-- You can have 1..n cartridge elements. -->
-		<cartridge type="as" host="abc.com" provider="carbon" version="5.1.0" multiTenant="true">
-			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
-				 specified under iaasProvider child elements of cartridge element. -->
-			<property name="ss" value="slsls"/>
-			<property name="ss" value="slsls"/>
-			<description>This is a WSO2 AS cartridge.</description>
-			<deployment baseDir="xyz">
-				<dir>abc</dir>
-			</deployment>
-			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
-				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
-				 Provider (which should have a unique "type" attribute. -->
-			<iaasProvider type="openstack" >
-				<imageId>nova/xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="instanceType" value="1"/>
-				<property name="payload" value="resources/as.txt"/>
-			</iaasProvider>
-			<iaasProvider type="ec2" >
-				<imageId>xxxxxxxxxx</imageId>
-				<property name="keyPair" value="aa"/>
-				<property name="securityGroups" value="manager,cep,mb,default"/>
-				<property name="instanceType" value="m1.large"/>
-				<property name="payload" value="resources/as-ec2.txt"/>
-			</iaasProvider>
-			
-		</cartridge>
-	
-	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
deleted file mode 100644
index 1b5b160..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<!--
-  ~ Copyright 2005-2011 WSO2, Inc. (http://wso2.com)
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-  
-<cloudController xmlns:svns="http://org.wso2.securevault/configuration">
-
-	<svns:secureVault
-		provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler" />
-	
-	<dataPublisher enable="false">
-		<!-- BAM Server Info - default values are 'admin' and 'admin' 
-			 Optional element. -->
-		<bamServer>
-			<adminUserName>admin</adminUserName>
-			<adminPassword svns:secretAlias="cloud.controller.bam.server.admin.password">admin</adminPassword>
-		</bamServer>
-		<!-- Default cron expression is '1 * * * * ? *' meaning 'first second of every minute'.
-			 Optional element. -->
-		<cron>1 * * * * ? *</cron>
-		<!-- Cassandra cluster related info -->
-		<cassandraInfo>
-			<connectionUrl>localhost:9160</connectionUrl>
-			<userName>admin</userName>
-			<password svns:secretAlias="cloud.controller.cassandra.server.password">admin</password>
-		</cassandraInfo>
-	</dataPublisher>
-	
-	<topologySync enable="true">
-		<!-- MB server info -->
-		<mbServerUrl>localhost:5672</mbServerUrl>
-		<cron>1 * * * * ? *</cron>
-	</topologySync>
-	
-	<!-- Specify the properties that are common to an IaaS here. This element 
-		is not necessary [0..1]. But you can use this section to avoid specifying 
-		same property over and over again. -->
-	<iaasProviders>
-		<!--<iaasProvider type="ec2" name="EC2 specific details"> <provider>aws-ec2</provider> 
-			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity> 
-			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential> 
-			<scaleUpOrder>2</scaleUpOrder> <scaleDownOrder>1</scaleDownOrder> <property 
-			name="A.x" value="a"/> <property name="B" value="b"/> <imageId>tempEC2</imageId> 
-			</iaasProvider> -->
-		<iaasProvider type="openstack" name="openstack specific details">
-			<className>org.wso2.carbon.stratos.cloud.controller.iaases.OpenstackNovaIaas</className>
-			<provider>openstack-nova</provider>
-			<identity svns:secretAlias="cloud.controller.openstack.identity">demo:demo</identity>
-			<credential svns:secretAlias="cloud.controller.openstack.credential">openstack</credential>
-			<property name="jclouds.endpoint" value="http://172.17.0.1:5000/" />
-			<property name="jclouds.api-version" value="2.0/" />
-			<scaleUpOrder>1</scaleUpOrder>
-			<scaleDownOrder>2</scaleDownOrder>
-			<maxInstanceLimit>5</maxInstanceLimit>
-			<property name="region" value="x" />
-			<property name="Y" value="y" />
-			<imageId>tempLXC</imageId>
-		</iaasProvider>
-	</iaasProviders>
-</cloudController>
\ No newline at end of file


[10/10] git commit: Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
Apache Stratos Cloud Controller Component refactoring

Signed-off-by: Isuru <is...@wso2.com>


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

Branch: refs/heads/master
Commit: 35006acc920acacd124408dddf47685edc3c8d5d
Parents: 64777ba
Author: udara <udara@udara-ThinkPad-T530.(none)>
Authored: Thu Jul 4 17:16:42 2013 +0530
Committer: Isuru <is...@wso2.com>
Committed: Thu Jul 4 17:50:54 2013 +0530

----------------------------------------------------------------------
 .../2.1.3/pom.xml                               |  338 +++++
 .../controller/axiom/AxiomXpathParser.java      | 1263 ++++++++++++++++++
 .../controller/concurrent/ThreadExecutor.java   |   53 +
 .../controller/consumers/TopologyBuilder.java   |  188 +++
 .../controller/deployers/CartridgeDeployer.java |  194 +++
 .../deployers/CloudControllerDeployer.java      |  110 ++
 .../controller/deployers/ServiceDeployer.java   |  152 +++
 .../exception/CloudControllerException.java     |   32 +
 .../exception/DeserializationException.java     |   32 +
 .../InvalidCartridgeDefinitionException.java    |   32 +
 .../exception/InvalidXMLException.java          |   36 +
 .../MalformedConfigurationFileException.java    |   32 +
 .../exception/NoInstanceFoundException.java     |   38 +
 .../exception/SerializationException.java       |   32 +
 .../UnregisteredCartridgeException.java         |   32 +
 .../exception/UnregisteredServiceException.java |   32 +
 .../hector/CassandraDataRetriever.java          |  181 +++
 .../controller/hive/HiveQueryExecutor.java      |  167 +++
 .../cloud/controller/iaases/AWSEC2Iaas.java     |  275 ++++
 .../controller/iaases/OpenstackNovaIaas.java    |  269 ++++
 .../cloud/controller/iaases/VCloudIaas.java     |  164 +++
 .../impl/CloudControllerServiceImpl.java        | 1123 ++++++++++++++++
 .../interfaces/CloudControllerService.java      |  194 +++
 .../cloud/controller/interfaces/Iaas.java       |   73 +
 .../internal/CloudControllerDSComponent.java    |   85 ++
 .../jcloud/ComputeServiceBuilderUtil.java       |  182 +++
 .../cloud/controller/persist/Deserializer.java  |   91 ++
 .../cloud/controller/persist/Serializer.java    |   85 ++
 .../CartridgeInstanceDataPublisherTask.java     |  476 +++++++
 .../controller/registry/RegistryManager.java    |  101 ++
 .../registry/RegistryManager.java.back          |   96 ++
 .../runtime/FasterLookUpDataHolder.java         |  425 ++++++
 .../topic/ConfigurationPublisher.java           |   65 +
 .../topic/TopologySynchronizerTask.java         |   79 ++
 .../stratos/cloud/controller/util/AppType.java  |   44 +
 .../cloud/controller/util/Cartridge.java        |  254 ++++
 .../cloud/controller/util/CartridgeInfo.java    |  162 +++
 .../controller/util/CartridgeInstanceData.java  |  129 ++
 .../util/CloudControllerConstants.java          |  216 +++
 .../controller/util/CloudControllerUtil.java    |  102 ++
 .../util/DeclarativeServiceReferenceHolder.java |   69 +
 .../cloud/controller/util/IaasContext.java      |  149 +++
 .../cloud/controller/util/IaasProvider.java     |  263 ++++
 .../cloud/controller/util/PortMapping.java      |   46 +
 .../cloud/controller/util/Properties.java       |   36 +
 .../stratos/cloud/controller/util/Property.java |   35 +
 .../cloud/controller/util/ServiceContext.java   |  283 ++++
 .../src/main/resources/META-INF/component.xml   |   36 +
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../2.1.3/src/main/resources/cartridge.xsd      |  133 ++
 .../2.1.3/src/main/resources/cartridges.xsd     |  144 ++
 .../2.1.3/src/main/resources/service.xsd        |   46 +
 .../2.1.3/src/main/resources/services.xsd       |   51 +
 .../service/axiom/AxiomValidationTest.java      |  125 ++
 .../service/axiom/AxiomXpathParserTest.java     |   51 +
 .../service/util/ServiceContextTest.java        |   49 +
 .../2.1.3/src/test/resources/cartridges-1.xml   |   33 +
 .../2.1.3/src/test/resources/cartridges-2.xml   |   34 +
 .../2.1.3/src/test/resources/cartridges-3.xml   |   16 +
 .../2.1.3/src/test/resources/cartridges-4.xml   |   32 +
 .../2.1.3/src/test/resources/cartridges-5.xml   |   29 +
 .../2.1.3/src/test/resources/cartridges-6.xml   |   19 +
 .../2.1.3/src/test/resources/cartridges-7.xml   |   40 +
 .../2.1.3/src/test/resources/cartridges-8.xml   |   72 +
 .../2.1.3/src/test/resources/cartridges-9.xml   |   66 +
 .../src/test/resources/cloud-controller.xml     |   73 +
 components/pom.xml                              |    3 +-
 .../2.1.3/pom.xml                               |  324 -----
 .../controller/axiom/AxiomXpathParser.java      | 1263 ------------------
 .../controller/concurrent/ThreadExecutor.java   |   53 -
 .../controller/consumers/TopologyBuilder.java   |  189 ---
 .../controller/deployers/CartridgeDeployer.java |  194 ---
 .../deployers/CloudControllerDeployer.java      |  110 --
 .../controller/deployers/ServiceDeployer.java   |  153 ---
 .../exception/CloudControllerException.java     |   32 -
 .../exception/DeserializationException.java     |   32 -
 .../InvalidCartridgeDefinitionException.java    |   32 -
 .../exception/InvalidXMLException.java          |   36 -
 .../MalformedConfigurationFileException.java    |   32 -
 .../exception/NoInstanceFoundException.java     |   38 -
 .../exception/SerializationException.java       |   32 -
 .../UnregisteredCartridgeException.java         |   32 -
 .../exception/UnregisteredServiceException.java |   32 -
 .../hector/CassandraDataRetriever.java          |  181 ---
 .../controller/hive/HiveQueryExecutor.java      |  167 ---
 .../cloud/controller/iaases/AWSEC2Iaas.java     |  275 ----
 .../controller/iaases/OpenstackNovaIaas.java    |  269 ----
 .../cloud/controller/iaases/VCloudIaas.java     |  164 ---
 .../impl/CloudControllerServiceImpl.java        | 1123 ----------------
 .../interfaces/CloudControllerService.java      |  195 ---
 .../cloud/controller/interfaces/Iaas.java       |   73 -
 .../internal/CloudControllerDSComponent.java    |   85 --
 .../jcloud/ComputeServiceBuilderUtil.java       |  182 ---
 .../cloud/controller/persist/Deserializer.java  |   91 --
 .../cloud/controller/persist/Serializer.java    |   85 --
 .../CartridgeInstanceDataPublisherTask.java     |  476 -------
 .../controller/registry/RegistryManager.java    |  101 --
 .../registry/RegistryManager.java.back          |   96 --
 .../runtime/FasterLookUpDataHolder.java         |  425 ------
 .../topic/ConfigurationPublisher.java           |   65 -
 .../topic/TopologySynchronizerTask.java         |   78 --
 .../stratos/cloud/controller/util/AppType.java  |   44 -
 .../cloud/controller/util/Cartridge.java        |  254 ----
 .../cloud/controller/util/CartridgeInfo.java    |  162 ---
 .../controller/util/CartridgeInstanceData.java  |  129 --
 .../util/CloudControllerConstants.java          |  216 ---
 .../controller/util/CloudControllerUtil.java    |  102 --
 .../util/DeclarativeServiceReferenceHolder.java |   69 -
 .../cloud/controller/util/IaasContext.java      |  149 ---
 .../cloud/controller/util/IaasProvider.java     |  263 ----
 .../cloud/controller/util/PortMapping.java      |   46 -
 .../cloud/controller/util/Properties.java       |   36 -
 .../stratos/cloud/controller/util/Property.java |   35 -
 .../cloud/controller/util/ServiceContext.java   |  283 ----
 .../src/main/resources/META-INF/component.xml   |   36 -
 .../src/main/resources/META-INF/services.xml    |    9 -
 .../2.1.3/src/main/resources/cartridge.xsd      |  133 --
 .../2.1.3/src/main/resources/cartridges.xsd     |  144 --
 .../2.1.3/src/main/resources/service.xsd        |   46 -
 .../2.1.3/src/main/resources/services.xsd       |   51 -
 .../service/axiom/AxiomValidationTest.java      |  125 --
 .../service/axiom/AxiomXpathParserTest.java     |   51 -
 .../service/util/ServiceContextTest.java        |   49 -
 .../2.1.3/src/test/resources/cartridges-1.xml   |   33 -
 .../2.1.3/src/test/resources/cartridges-2.xml   |   34 -
 .../2.1.3/src/test/resources/cartridges-3.xml   |   16 -
 .../2.1.3/src/test/resources/cartridges-4.xml   |   32 -
 .../2.1.3/src/test/resources/cartridges-5.xml   |   29 -
 .../2.1.3/src/test/resources/cartridges-6.xml   |   19 -
 .../2.1.3/src/test/resources/cartridges-7.xml   |   40 -
 .../2.1.3/src/test/resources/cartridges-8.xml   |   72 -
 .../2.1.3/src/test/resources/cartridges-9.xml   |   66 -
 .../src/test/resources/cloud-controller.xml     |   73 -
 133 files changed, 9575 insertions(+), 9562 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/pom.xml b/components/org.apache.stratos.cloud.controller/2.1.3/pom.xml
new file mode 100644
index 0000000..0626149
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/pom.xml
@@ -0,0 +1,338 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<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.wso2.carbon</groupId>
+       <artifactId>stratos-components</artifactId>
+       <version>2.1.0</version>
+       <relativePath>../../pom.xml</relativePath>
+    </parent>
+-->
+    <parent>
+       <groupId>org.apache.stratos</groupId>
+       <artifactId>stratos-components-parent</artifactId>
+       <version>2.0.0</version>
+       <relativePath>../../pom.xml</relativePath>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.cloud.controller</artifactId>
+    <packaging>bundle</packaging>
+    <version>2.1.3</version>
+    <name>Apache - Stratos Cloud Controller</name>
+    <url>http://apache.org</url>
+
+    <build>
+        <plugins>
+            <!--plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <version>1.7.1</version>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <artifactSet>
+                                <includes>
+                                    <include>org.jclouds:*</include>
+                                    <include>org.jclouds.*:*</include>
+                                </includes>
+                            </artifactSet>
+                            <filtering>true</filtering>
+                            <filters>
+                                <filter>
+                                    <artifact>org.jclouds*:*</artifact>
+                                    <includes>
+                                        <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
+                                        <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
+                                    </includes>
+                                </filter>
+                            </filters>
+                            <transformers>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
+                                </transformer>
+                            </transformers>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin-->
+            <!--plugin>
+                <groupId>org.apache.axis2</groupId>
+                <artifactId>axis2-aar-maven-plugin</artifactId>
+                <version>1.4</version>
+                <extensions>true</extensions>
+            </plugin-->
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            og.apache.stratos.cloud.controller.interfaces.*,
+                            og.apache.stratos.cloud.controller.publisher.*,
+                            og.apache.stratos.cloud.controller.topic.*,
+                            og.apache.stratos.cloud.controller.iaases.*,
+                            og.apache.stratos.cloud.controller.util.*,
+				org.apache.stratos.cloud.controller.deployers.*,
+				org.apache.stratos.cloud.controller.exception.*,
+				org.apache.stratos.cloud.controller.*
+                        </Export-Package>
+                        <Private-Package>
+                            og.apache.stratos.cloud.controller.*,
+                            !og.apache.stratos.cloud.controller.interfaces,
+                            !og.apache.stratos.cloud.controller.publisher,
+                            !og.apache.stratos.cloud.controller.topic,
+                            !og.apache.stratos.cloud.controller.iaases 
+                        </Private-Package>
+                        <Import-Package>
+                        	  !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            <!--org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
+                            org.jclouds*;version="${jclouds.version}",-->
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                        
+                        <Axis2Deployer>CloudControllerDeployer</Axis2Deployer>
+                        
+                        <Axis2Deployer>CartridgeDeployer</Axis2Deployer>
+                        
+                        <Axis2Deployer>ServiceDeployer</Axis2Deployer>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+	    <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+	    <version>4.1.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>4.1.3</version>
+        </dependency>
+
+
+<dependency>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.securevault</artifactId>
+    <version>${wso2carbon.version}</version>
+</dependency>
+<dependency>
+    <groupId>org.hectorclient.wso2</groupId>
+    <artifactId>hector-core</artifactId>
+    <version>1.1.0.wso2v1</version>
+    <exclusions>
+        <exclusion>
+            <groupId>com.google.guava.wso2</groupId>
+            <artifactId>guava</artifactId>
+        </exclusion>
+    </exclusions>
+
+</dependency>
+<dependency>
+    <groupId>com.google.guava.wso2</groupId>
+    <artifactId>guava</artifactId>
+    <version>${google.guava.wso2.version}</version>
+</dependency>
+<dependency>
+        <groupId>org.wso2.andes.wso2</groupId>
+        <artifactId>andes-client</artifactId>
+        <version>0.13.wso2v3</version>
+    </dependency>
+<dependency>
+        <groupId>org.apache.geronimo.specs.wso2</groupId>
+        <artifactId>geronimo-jms_1.1_spec</artifactId>
+        <version>${orbit.version.geronimo-jms_1.1_spec}</version>
+    </dependency>
+
+<dependency>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.analytics.hive.stub</artifactId>
+       <version>4.1.0</version>
+</dependency>
+
+<!--  Jclouds dependencies -->
+       <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-core</artifactId>
+           <version>${jclouds.version}</version>
+          </dependency>
+        <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-compute</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+<!--
+	 <dependency>
+            <groupId>org.jclouds.api</groupId>
+            <artifactId>vcloud</artifactId>
+            <version>1.6.0-wso2v1</version>
+        </dependency>
+-->
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-bouncycastle</artifactId>
+           <version>${jclouds.version}</version>
+           <exclusions>
+              <exclusion>
+                 <groupId>org.bouncycastle</groupId>
+                 <artifactId>bcprov-jdk16</artifactId>
+              </exclusion>
+           </exclusions>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-sshj</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-log4j</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-enterprise</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.provider</groupId>
+           <artifactId>aws-ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>openstack-nova</artifactId>
+           <version>${jclouds.wso2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>openstack-keystone</artifactId>
+           <version>${jclouds.wso2.version}</version>
+         </dependency>
+         <dependency>
+          <groupId>org.jclouds</groupId>
+            <artifactId>jclouds-scriptbuilder</artifactId>
+              <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+          <groupId>org.jclouds.common</groupId>
+            <artifactId>aws-common</artifactId>
+              <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+             <groupId>com.jamesmurty.utils.wso2</groupId>
+             <artifactId>java-xmlbuilder</artifactId>
+             <version>0.4.wso2v1</version>
+         </dependency>
+        <dependency>
+            <groupId>org.jclouds.api</groupId>
+            <artifactId>vcloud</artifactId>
+            <version>1.6.0-wso2v1</version>
+        </dependency>
+         <dependency>
+           <groupId>com.google.code.gson</groupId>
+           <artifactId>gson</artifactId>
+           <version>${gson2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.google.guice.wso2</groupId>
+           <artifactId>guice</artifactId>
+           <version>${google.guice.wso2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.google.guice.assistedinject.wso2</groupId>
+           <artifactId>guice-assistedinject</artifactId>
+           <version>${com.google.guice.assistedinject.wso2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.sun.jersey</groupId>
+           <artifactId>jersey-core</artifactId>
+           <version>${sun.jersey.version}</version>
+         </dependency>
+         <dependency>
+          <groupId>net.oauth.core</groupId>
+          <artifactId>oauth</artifactId>
+          <version>20100527</version>
+         </dependency>
+         <dependency>
+           <groupId>commons-io.wso2</groupId>
+           <artifactId>commons-io</artifactId>
+           <version>2.0.0.wso2v1</version>
+         </dependency>
+         <dependency>
+           <groupId>rhino.wso2</groupId>
+           <artifactId>js</artifactId>
+           <version>1.7.0.R1-wso2v3</version>
+         </dependency>
+         <dependency>
+           <groupId>org.wso2.carbon</groupId>
+           <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
+           <version>2.1.1</version>
+         </dependency>
+         <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.databridge.agent.thrift</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ntask.core</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+    </dependencies>
+    <properties>
+        <gson2.version>2.2</gson2.version>
+        <jclouds.version>1.5.0-beta.5</jclouds.version>
+        <jclouds.wso2.version>1.5.0-beta.5.wso2v1</jclouds.wso2.version>
+        <com.google.guice.assistedinject.wso2.version>3.0.wso2v1</com.google.guice.assistedinject.wso2.version>
+        <sun.jersey.version>1.12</sun.jersey.version>
+    </properties>
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
new file mode 100644
index 0000000..92ca7d0
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
@@ -0,0 +1,1263 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.axiom;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNode;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
+import org.apache.axiom.om.impl.dom.ElementImpl;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.AppType;
+import org.apache.stratos.cloud.controller.util.Cartridge;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.PortMapping;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jaxen.JaxenException;
+import org.w3c.dom.Element;
+import org.apache.stratos.cloud.controller.exception.MalformedConfigurationFileException;
+import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * This class is parsing configuration files using Axiom Xpath.
+ */
+public class AxiomXpathParser {
+
+	private static final Log log = LogFactory.getLog(AxiomXpathParser.class);
+	private OMElement documentElement;
+	private final File xmlSource;
+
+	public AxiomXpathParser(final File xmlFile) {
+		xmlSource = xmlFile;
+	}
+
+	/**
+     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param aCartridge {@link org.apache.stratos.cloud.controller.util.Cartridge} instance.
+     * @param appTypesNodes nodes of App types.
+     */
+    private void getAppTypes(String cartridgeElementString, Cartridge aCartridge,
+                             List<?> appTypesNodes) {
+	    Object nodeObj;
+	    if (!appTypesNodes.isEmpty()) {
+	    	if ((nodeObj = appTypesNodes.get(0)) instanceof OMNode) {
+	    		OMNode appTypeNode = (OMNode) nodeObj;
+
+	    		if (appTypeNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    			OMElement appTypesElt = (OMElement) appTypeNode;
+
+	    			for (Iterator<?> iterator =
+	    			                            appTypesElt.getChildrenWithName(new QName(
+	    			                                                                      CloudControllerConstants.APP_TYPE_ELEMENT)); iterator.hasNext();) {
+	    				OMElement appElt = (OMElement) iterator.next();
+
+	    				String name =
+	    				              appElt.getAttributeValue(new QName(
+	    				                                                 CloudControllerConstants.NAME_ATTR));
+	    				String appSpecificMapping =
+	    				                            appElt.getAttributeValue(new QName(
+	    				                                                               CloudControllerConstants.APP_SPECIFIC_MAPPING_ATTR));
+
+	    				AppType appType;
+
+	    				if (appSpecificMapping == null) {
+	    					appType = new AppType(name);
+	    				} else {
+	    					appType =
+	    					          new AppType(name,
+	    					                      Boolean.valueOf(appSpecificMapping));
+	    				}
+
+	    				aCartridge.addAppType(appType);
+	    			}
+
+	    		} else {
+	    			String msg =
+	    			             "Essential '" + CloudControllerConstants.APP_TYPE_ELEMENT +
+	    			                     "' element cannot" + " be found in " +
+	    			                     cartridgeElementString + " of " +
+	    			                     xmlSource;
+	    			handleException(msg);
+	    		}
+
+	    	}
+	    }
+    }
+
+	/**
+	 * @return a List of {@link Cartridge}s.
+	 */
+	public List<Cartridge> getCartridgesList() {
+
+		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+
+		List<IaasProvider> iaasProviders = dataHolder.getIaasProviders();
+
+		if (iaasProviders == null) {
+			dataHolder.setIaasProviders((iaasProviders = new ArrayList<IaasProvider>()));
+		}
+
+		List<Cartridge> cartridges = new ArrayList<Cartridge>();
+
+		String xpath = CloudControllerConstants.CARTRIDGES_ELEMENT_XPATH;
+		
+		// cartridges can be found from this XPATH
+		List<?> cartridgeNodes = getMatchingNodes(xpath, documentElement);
+
+		if (cartridgeNodes == null || cartridgeNodes.isEmpty()) {
+			// or from this XPATH
+			xpath = CloudControllerConstants.CARTRIDGE_ELEMENT_XPATH;
+			cartridgeNodes = getMatchingNodes(xpath, documentElement);
+		}
+
+		if (cartridgeNodes == null || cartridgeNodes.isEmpty()) {
+			log.warn("No cartridge found in this configuration file : " + xmlSource.getPath());
+			return cartridges;
+		}
+
+		for (Object obj : cartridgeNodes) {
+
+			if (obj instanceof OMNode) {
+				OMNode cartridgeNode = (OMNode) obj;
+
+				if (cartridgeNode.getType() == OMNode.ELEMENT_NODE) {
+
+					OMElement cartridgeElement = (OMElement) cartridgeNode;
+
+					// retrieve Attributes of a Cartridge definition
+					String type = cartridgeElement.getAttributeValue(new QName(
+					                                                           CloudControllerConstants.TYPE_ATTR));
+					String host = cartridgeElement.getAttributeValue(new QName(
+					                                                           CloudControllerConstants.HOST_ATTR));
+					String provider = cartridgeElement.getAttributeValue(new QName(
+					                                                               CloudControllerConstants.PROVIDER_ATTR));
+					
+					String version =
+			                  cartridgeElement.getAttributeValue(new QName(
+			                                                               CloudControllerConstants.VERSION_ATTR));
+
+					boolean multiTenant = Boolean.valueOf(cartridgeElement.getAttributeValue(new QName(
+							CloudControllerConstants.MULTI_TENANT_ATTR)));
+
+					Cartridge aCartridge;
+
+					if ((aCartridge = dataHolder.getCartridge(type)) == null) {
+
+						aCartridge = new Cartridge(type, host, provider, version, multiTenant);
+					}
+					
+					// read displayName
+					Iterator<?> itName =
+					                 cartridgeElement.getChildrenWithName(new QName(
+					                                                                CloudControllerConstants.DISPLAY_NAME_ELEMENT));
+
+					if (itName.hasNext()) {
+						OMElement name = (OMElement) itName.next();
+
+						aCartridge.setDisplayName(name.getText());
+					}
+					
+					// read description
+					Iterator<?> it =
+					                 cartridgeElement.getChildrenWithName(new QName(
+					                                                                CloudControllerConstants.DESCRIPTION_ELEMENT));
+
+					if (it.hasNext()) {
+						OMElement desc = (OMElement) it.next();
+
+						aCartridge.setDescription(desc.getText());
+					}
+
+					// load properties of this cartridge
+					loadProperties(cartridgeElement, aCartridge.getProperties());
+
+					// retrieve the list of IaaS providers
+					List<?> iaasProviderNodes = getMatchingNodes(xpath + CloudControllerConstants.IAAS_PROVIDER_ELEMENT_XPATH,
+					                                             cartridgeElement);
+
+					getIaasProviders(iaasProviders, cartridgeElement.toString(), aCartridge, iaasProviderNodes);
+
+					// load dirs
+					List<?> deploymentNodes = getMatchingNodes(xpath + CloudControllerConstants.DEPLOYMENT_ELEMENT_XPATH,
+					                                           cartridgeElement);
+                    setDeploymentDirs(cartridgeElement.toString(), aCartridge, deploymentNodes);
+
+					// load port mappings
+					List<?> portMappingNodes =
+					                           getMatchingNodes(xpath +
+					                                                    CloudControllerConstants.PORT_MAPPING_ELEMENT_XPATH,
+					                                            cartridgeElement);
+					getPortMappings(cartridgeElement.toString(), aCartridge, portMappingNodes);
+
+					// load appTypes
+					List<?> appTypesNodes =
+					                        getMatchingNodes(xpath +
+					                                                 CloudControllerConstants.APP_TYPES_ELEMENT_XPATH,
+					                                         cartridgeElement);
+					getAppTypes(cartridgeElement.toString(), aCartridge, appTypesNodes);
+
+					cartridges.add(aCartridge);
+
+					if (dataHolder.getCartridge(type) == null) {
+						dataHolder.addCartridge(aCartridge);
+					}
+				}
+			}
+		}
+
+		return cartridges;
+
+	}
+
+	/**
+     * @param iaasProviders
+     * @param cartridgeElementString
+     * @param aCartridge
+     * @param iaasProviderNodes
+     */
+    private void getIaasProviders(List<IaasProvider> iaasProviders,
+                                  String cartridgeElementString, Cartridge aCartridge,
+                                  List<?> iaasProviderNodes) {
+	    for (Object nodeObj : iaasProviderNodes) {
+	    	if (nodeObj instanceof OMNode) {
+	    		OMNode iaasProviderNode = (OMNode) nodeObj;
+
+	    		if (iaasProviderNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    			OMElement iaasElt = (OMElement) iaasProviderNode;
+
+	    			// add the IaasProvider to this cartridge
+	    			aCartridge.addIaasProvider(getIaasProvider(iaasElt, iaasProviders));
+
+	    		} else {
+	    			String msg =
+	    			             "Essential '" +
+	    			                     CloudControllerConstants.IAAS_PROVIDER_ELEMENT +
+	    			                     "' element cannot" + " be found in " +
+	    			                     cartridgeElementString + " of " +
+	    			                     xmlSource;
+	    			handleException(msg);
+	    		}
+
+	    	}
+	    }
+    }
+
+	private Element getDOMElement(final OMElement omElement) {
+
+		// Get the StAX reader from the created element
+		XMLStreamReader llomReader = omElement.getXMLStreamReader();
+
+		// Create the DOOM OMFactory
+		OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
+
+		// Create the new builder
+		StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
+
+		// Get the document element
+		OMElement newElem = doomBuilder.getDocumentElement();
+
+		return newElem instanceof Element ? (Element) newElem : null;
+	}
+
+	private OMElement getElement(final Object obj) {
+		OMNode node;
+		if ((obj instanceof OMNode) && (node = (OMNode) obj).getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement element = (OMElement) node;
+
+			return element;
+
+		}
+
+		return null;
+	}
+
+	private OMElement getElement(final OMElement rootElt, final String eltStr, final String xpath) {
+		List<?> nodes = getMatchingNodes(xpath, rootElt);
+		neglectingWarn(eltStr, nodes.size());
+		OMElement element = getElement(nodes.get(0));
+		return element;
+	}
+
+	private OMElement getFirstChildElement(final OMElement root, final String childName) {
+		Iterator<?> it = root.getChildrenWithName(new QName(childName));
+		if (it.hasNext()) {
+			return (OMElement) it.next();
+		}
+
+		return null;
+	}
+
+	/**
+	 * 
+	 * @param xpath
+	 *            XPATH expression to be read.
+	 * @param elt
+	 *            OMElement to be used for the search.
+	 * @return List matching OMNode list
+	 */
+	@SuppressWarnings("unchecked")
+	public OMNode getFirstMatchingNode(final String xpath, final OMElement elt) {
+
+		AXIOMXPath axiomXpath;
+		List<OMNode> nodeList = null;
+		try {
+			axiomXpath = new AXIOMXPath(xpath);
+			nodeList = axiomXpath.selectNodes(elt);
+		} catch (JaxenException e) {
+			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		return nodeList != null ? nodeList.get(0) : null;
+	}
+
+	private IaasProvider getIaasProvider(final OMNode item, List<IaasProvider> iaases) {
+
+		IaasProvider iaas = null;
+
+		if (item.getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement iaasElt = (OMElement) item;
+
+			if (iaases != null) {
+				// check whether this is a reference to a predefined IaaS.
+				for (IaasProvider iaasProvider : iaases) {
+					if (iaasProvider.getType()
+					                .equals(iaasElt.getAttribute(new QName(
+					                                                       CloudControllerConstants.TYPE_ATTR))
+					                               .getAttributeValue())) {
+						iaas = new IaasProvider(iaasProvider);
+						break;
+					}
+				}
+			}
+
+			if (iaas == null) {
+				iaas = new IaasProvider();
+			}
+
+			if (iaas.getType() == null) {
+				iaas.setType(iaasElt.getAttribute(new QName(CloudControllerConstants.TYPE_ATTR))
+				                    .getAttributeValue());
+			}
+
+			if ("".equals(iaas.getType())) {
+				String msg =
+				             "'" + CloudControllerConstants.IAAS_PROVIDER_ELEMENT + "' element's '" +
+				                     CloudControllerConstants.TYPE_ATTR +
+				                     "' attribute should be specified!";
+
+				handleException(msg);
+
+			}
+
+			// this is not mandatory
+			String name =
+			              (iaasElt.getAttribute(new QName(CloudControllerConstants.NAME_ATTR)) == null)
+			                                                                                     ? iaas.getName()
+			                                                                                     : iaasElt.getAttributeValue(new QName(
+			                                                                                                                           CloudControllerConstants.NAME_ATTR));
+
+			iaas.setName(name);
+
+			String xpath = CloudControllerConstants.IAAS_PROVIDER_ELEMENT_XPATH;
+
+			// load other elements
+			loadClassName(iaas, iaasElt);
+			loadMaxInstanceLimit(iaas, iaasElt);
+			loadProperties(iaasElt, iaas.getProperties());
+			loadTemplate(iaas, iaasElt);
+			loadScalingOrders(iaas, iaasElt);
+			loadProvider(iaas, iaasElt);
+			loadIdentity(iaas, iaasElt);
+			loadCredentials(iaas, iaasElt, xpath);
+		}
+
+		return iaas;
+	}
+
+	/**
+	 * 
+	 * @param xpath
+	 *            XPATH expression to be read.
+	 * @return List matching OMNode list
+	 */
+	@SuppressWarnings("unchecked")
+	public List<OMNode> getMatchingNodes(final String xpath) {
+
+		AXIOMXPath axiomXpath;
+		List<OMNode> nodeList = null;
+		try {
+			axiomXpath = new AXIOMXPath(xpath);
+			nodeList = axiomXpath.selectNodes(documentElement);
+		} catch (JaxenException e) {
+			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		return nodeList;
+	}
+
+	/**
+	 * 
+	 * @param xpath
+	 *            XPATH expression to be read.
+	 * @param elt
+	 *            OMElement to be used for the search.
+	 * @return List matching OMNode list
+	 */
+	@SuppressWarnings("unchecked")
+	public List<OMNode> getMatchingNodes(final String xpath, final OMElement elt) {
+
+		AXIOMXPath axiomXpath;
+		List<OMNode> nodeList = null;
+		try {
+			axiomXpath = new AXIOMXPath(xpath);
+			nodeList = axiomXpath.selectNodes(elt);
+		} catch (JaxenException e) {
+			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		return nodeList;
+	}
+
+	/**
+     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param aCartridge {@link Cartridge} instance.
+     * @param portMappingNodes nodes of port mapping elements
+     */
+    private void getPortMappings(String cartridgeElementString, Cartridge aCartridge,
+                                 List<?> portMappingNodes) {
+	    Object nodeObj;
+	    if (!portMappingNodes.isEmpty()) {
+	    	if ((nodeObj = portMappingNodes.get(0)) instanceof OMNode) {
+	    		OMNode portMappingNode = (OMNode) nodeObj;
+
+	    		if (portMappingNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    			OMElement portMappingElt = (OMElement) portMappingNode;
+
+	    			for (Iterator<?> iterator =
+	    			                            portMappingElt.getChildrenWithName(new QName(
+	    			                                                                         CloudControllerConstants.HTTP_ELEMENT)); iterator.hasNext();) {
+	    				OMElement httpElt = (OMElement) iterator.next();
+
+	    				String port =
+	    				              httpElt.getAttributeValue(new QName(
+	    				                                                  CloudControllerConstants.PORT_ATTR));
+	    				String proxyPort =
+	    				                   httpElt.getAttributeValue(new QName(
+	    				                                                       CloudControllerConstants.PROXY_PORT_ATTR));
+
+	    				PortMapping mapping =
+	    				                      new PortMapping(
+	    				                                      CloudControllerConstants.HTTP_ELEMENT,
+	    				                                      port, proxyPort);
+
+	    				aCartridge.addPortMapping(mapping);
+	    			}
+
+	    			for (Iterator<?> iterator =
+	    			                            portMappingElt.getChildrenWithName(new QName(
+	    			                                                                         CloudControllerConstants.HTTPS_ELEMENT)); iterator.hasNext();) {
+	    				OMElement httpsElt = (OMElement) iterator.next();
+
+	    				String port =
+	    				              httpsElt.getAttributeValue(new QName(
+	    				                                                   CloudControllerConstants.PORT_ATTR));
+	    				String proxyPort =
+	    				                   httpsElt.getAttributeValue(new QName(
+	    				                                                        CloudControllerConstants.PROXY_PORT_ATTR));
+
+	    				PortMapping mapping =
+	    				                      new PortMapping(
+	    				                                      CloudControllerConstants.HTTPS_ELEMENT,
+	    				                                      port, proxyPort);
+
+	    				aCartridge.addPortMapping(mapping);
+	    			}
+
+	    		} else {
+	    			String msg =
+	    			             "Essential '" +
+	    			                     CloudControllerConstants.PORT_MAPPING_ELEMENT +
+	    			                     "' element cannot" + " be found in " +
+	    			                     cartridgeElementString + " of " +
+	    			                     xmlSource;
+	    			handleException(msg);
+	    		}
+
+	    	}
+	    }
+    }
+
+	public List<ServiceContext> getServiceContexts() {
+
+		List<ServiceContext> serviceContextList = new ArrayList<ServiceContext>();
+
+		// services can be found from this XPATH
+		String xpath = CloudControllerConstants.SERVICES_ELEMENT_XPATH;
+		List<?> serviceNodes = getMatchingNodes(xpath, documentElement);
+
+		if (serviceNodes == null || serviceNodes.isEmpty()) {
+			// or from this XPATH
+			xpath = CloudControllerConstants.SERVICE_ELEMENT_XPATH;
+			serviceNodes = getMatchingNodes(xpath, documentElement);
+		}
+
+		if (serviceNodes == null || serviceNodes.isEmpty()) {
+			log.warn("No service found in this configuration file : " + xmlSource.getPath());
+			return serviceContextList;
+		}
+
+		for (Object obj : serviceNodes) {
+			ServiceContext serviceCtxt = new ServiceContext();
+
+			// set the definition file
+			serviceCtxt.setFile(xmlSource);
+			
+			if (obj instanceof OMNode) {
+				OMNode serviceNode = (OMNode) obj;
+
+				if (serviceNode.getType() == OMNode.ELEMENT_NODE) {
+
+					OMElement node = (OMElement) serviceNode;
+
+					if (node.getAttribute(new QName(CloudControllerConstants.SERVICE_DOMAIN_ATTR)) == null) {
+						String msg =
+						             "Essential '" + CloudControllerConstants.SERVICE_DOMAIN_ATTR + "' " +
+						                     "attribute of '" + CloudControllerConstants.SERVICE_ELEMENT +
+						                     "' element cannot be found in " + xmlSource;
+
+						handleException(msg);
+					}
+
+					// set domain name
+					serviceCtxt.setDomainName(node.getAttribute(new QName(
+					                                                      CloudControllerConstants.SERVICE_DOMAIN_ATTR))
+					                              .getAttributeValue());
+
+					// set sub domain
+					serviceCtxt.setSubDomainName(node.getAttribute(new QName(
+					                                                         CloudControllerConstants.SERVICE_SUB_DOMAIN_ATTR))
+					                                 .getAttributeValue());
+
+					// set tenant range
+					serviceCtxt.setTenantRange(node.getAttribute(new QName(
+					                                                       CloudControllerConstants.SERVICE_TENANT_RANGE_ATTR))
+					                               .getAttributeValue());
+
+					OMNode cartridgeNode =
+					                       getFirstMatchingNode(xpath +
+					                                                    CloudControllerConstants.CARTRIDGE_ELEMENT_XPATH,
+					                                            node);
+
+					if (cartridgeNode != null && cartridgeNode.getType() == OMNode.ELEMENT_NODE) {
+
+						OMElement cartridgeElt = (OMElement) cartridgeNode;
+
+						String type =
+								cartridgeElt.getAttribute(new QName(CloudControllerConstants.TYPE_ATTR))
+						                  .getAttributeValue();
+
+						if ("".equals(type)) {
+							String msg =
+							             "Essential '" + CloudControllerConstants.TYPE_ATTR + "' " +
+							                     " attribute of '" +
+							                     CloudControllerConstants.CARTRIDGE_ELEMENT + "' of '" +
+							                     CloudControllerConstants.SERVICE_ELEMENT +
+							                     "' element cannot be found in " + xmlSource;
+
+							handleException(msg);
+						}
+						
+						// set Cartridge type
+						serviceCtxt.setCartridgeType(type);
+
+					}
+					if (serviceCtxt.getCartridgeType() == null) {
+						String msg =
+						             "Essential '" + CloudControllerConstants.CARTRIDGE_ELEMENT +
+						                     "' element" + " has not specified in " + xmlSource;
+						handleException(msg);
+					}
+
+					// load payload
+					loadPayload(getMatchingNodes(xpath + CloudControllerConstants.PAYLOAD_ELEMENT_XPATH,
+					                             node), serviceCtxt);
+
+					// load host name
+					loadHostName(getMatchingNodes(xpath + CloudControllerConstants.HOST_ELEMENT_XPATH,
+					                              node), serviceCtxt);
+
+					// load properties
+					loadProperties(node, serviceCtxt.getProperties());
+
+				}
+			}
+
+			FasterLookUpDataHolder.getInstance().addServiceContext(serviceCtxt);
+			// add each domain specific template to list
+			serviceContextList.add(serviceCtxt);
+		}
+
+		return serviceContextList;
+
+	}
+
+	public File getXmlSource() {
+		return xmlSource;
+	}
+
+	private void handleException(final String msg) {
+		log.error(msg);
+		throw new MalformedConfigurationFileException(msg);
+	}
+
+	private void handleException(final String msg, final Exception e) {
+		log.error(msg, e);
+		throw new MalformedConfigurationFileException(msg, e);
+	}
+
+	private void loadClassName(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.CLASS_NAME_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement classNameElt = (OMElement) it.next();
+			iaas.setClassName(classNameElt.getText());
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.CLASS_NAME_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getClassName() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.CLASS_NAME_ELEMENT + "' element " +
+			                     "has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadCredentials(final IaasProvider iaas, final OMElement iaasElt,
+	                             final String xpath) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.CREDENTIAL_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement credentialElt = (OMElement) it.next();
+
+			// retrieve the value using secure vault
+			SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+			String alias =
+			               credentialElt.getAttributeValue(new QName(
+			                                                         CloudControllerConstants.ALIAS_ATTRIBUTE));
+
+			// retrieve the secured password
+			if (secretResolver != null && secretResolver.isInitialized() &&
+			    secretResolver.isTokenProtected(alias)) {
+
+				iaas.setCredential(secretResolver.resolve(alias));
+
+			}
+
+			// if we still cannot find a value, we try to assign the value which
+			// is specified
+			// in the element, if any
+			if (iaas.getCredential() == null) {
+				log.warn("Unable to find a value for " + CloudControllerConstants.CREDENTIAL_ELEMENT +
+				         " element from Secure Vault." +
+				         "Hence we will try to assign the plain text value (if specified).");
+				iaas.setCredential(credentialElt.getText());
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.CREDENTIAL_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getCredential() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.CREDENTIAL_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+	
+	private void loadHostName(final List<OMNode> nodes, final ServiceContext serviceCtxt) {
+
+		if (nodes == null || nodes.isEmpty()) {
+			return;
+		}
+
+		// read host element
+		if (nodes.get(0).getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement node = (OMElement) nodes.get(0);
+
+			if (node.getText() != null) {
+				serviceCtxt.setHostName(node.getText());
+			}
+
+		}
+	}
+
+	private void loadIdentity(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.IDENTITY_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement identityElt = (OMElement) it.next();
+
+			// retrieve the value using secure vault
+			SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+			String alias =
+			               identityElt.getAttributeValue(new QName(
+			                                                       CloudControllerConstants.ALIAS_ATTRIBUTE));
+
+			// retrieve the secured password
+			if (secretResolver != null && secretResolver.isInitialized() &&
+			    secretResolver.isTokenProtected(alias)) {
+
+				iaas.setIdentity(secretResolver.resolve(alias));
+
+			}
+
+			// if we still cannot find a value, we try to assign the value which
+			// is specified
+			// in the element, if any
+			if (iaas.getIdentity() == null) {
+				log.warn("Unable to find a value for " + CloudControllerConstants.IDENTITY_ELEMENT +
+				         " element from Secure Vault." +
+				         "Hence we will try to assign the plain text value (if specified).");
+				iaas.setIdentity(identityElt.getText());
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.IDENTITY_ELEMENT +
+			         " elements!" + " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getIdentity() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.IDENTITY_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadMaxInstanceLimit(IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement maxInstanceLimitElt = (OMElement) it.next();
+
+			try {
+				iaas.setMaxInstanceLimit(Integer.parseInt(maxInstanceLimitElt.getText()));
+			} catch (NumberFormatException e) {
+				String msg =
+				             CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT +
+				                     " element contained" + " in " + xmlSource + "" +
+				                     " has a value which is not an Integer value.";
+				handleException(msg, e);
+			}
+
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+	}
+
+	private void loadPayload(final List<OMNode> nodes, final ServiceContext serviceCtxt) {
+
+		if (nodes == null || nodes.isEmpty()) {
+			return;
+		}
+
+		// read payload element
+		if (nodes.get(0).getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement node = (OMElement) nodes.get(0);
+
+			if (node.getText() != null) {
+				byte[] payload = CloudControllerUtil.getBytesFromFile(node.getText());
+				serviceCtxt.setPayload(payload);
+
+			}
+
+		}
+
+	}
+
+	private void loadProperties(final OMElement iaasElt, final Map<String, String> propertyMap) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROPERTY_ELEMENT));
+
+		while (it.hasNext()) {
+			OMElement prop = (OMElement) it.next();
+
+			if (prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_NAME_ATTR)) == null ||
+			    prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_VALUE_ATTR)) == null) {
+
+				String msg =
+				             "Property element's, name and value attributes should be specified " +
+				                     "in " + xmlSource;
+
+				handleException(msg);
+			}
+
+			propertyMap.put(prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_NAME_ATTR))
+			                    .getAttributeValue(),
+			                prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_VALUE_ATTR))
+			                    .getAttributeValue());
+		}
+
+	}
+
+	private void loadProvider(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROVIDER_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement providerElt = (OMElement) it.next();
+			iaas.setProvider(providerElt.getText());
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.PROVIDER_ELEMENT +
+			         " elements!" + " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getProvider() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.PROVIDER_ELEMENT + "' element " +
+			                     "has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadScalingOrders(final IaasProvider iaas, final OMElement iaasElt) {
+		// set scale up order
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.SCALE_UP_ORDER_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement scaleUpOrderElt = (OMElement) it.next();
+
+			try {
+				iaas.setScaleUpOrder(Integer.parseInt(scaleUpOrderElt.getText()));
+			} catch (NumberFormatException e) {
+				String msg =
+				             CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + " element contained" +
+				                     " in " + xmlSource + "" +
+				                     " has a value which is not an Integer value.";
+				handleException(msg, e);
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getScaleUpOrder() == -1) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+		// set scale down order
+		it = iaasElt.getChildrenWithName(new QName(CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement scaleDownElt = (OMElement) it.next();
+
+			try {
+				iaas.setScaleDownOrder(Integer.parseInt(scaleDownElt.getText()));
+			} catch (NumberFormatException e) {
+				String msg =
+				             CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + " element contained" +
+				                     " in " + xmlSource + "" +
+				                     " has a value which is not an Integer value.";
+				handleException(msg, e);
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getScaleDownOrder() == -1) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadTemplate(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.IMAGE_ID_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement imageElt = (OMElement) it.next();
+			iaas.setImage(imageElt.getText());
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.IMAGE_ID_ELEMENT +
+			         " elements!" + " Elements other than the first will be neglected.");
+		}
+
+	}
+
+	private void neglectingWarn(final String elt, final int size) {
+		if (size > 1) {
+			log.warn(xmlSource + " contains more than one " + elt + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+	}
+
+	public void parse() {
+
+		if (xmlSource.exists()) {
+			try {
+				documentElement = new StAXOMBuilder(xmlSource.getPath()).getDocumentElement();
+
+			} catch (Exception ex) {
+				String msg = "Error occurred when parsing the " + xmlSource.getPath() + ".";
+				handleException(msg, ex);
+			}
+		} else {
+			String msg = "Configuration file cannot be found : " + xmlSource.getPath();
+			handleException(msg);
+		}
+	}
+
+	private void plainTextWarn(final String elt) {
+		log.warn("Unable to find a value for " + elt + " element from Secure Vault." +
+		         "Hence we will try to assign the plain text value (if specified).");
+	}
+
+	private String resolveSecret(final OMElement elt) {
+		// retrieve the value using secure vault
+		SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+
+		String alias = elt.getAttributeValue(new QName(CloudControllerConstants.ALIAS_ATTRIBUTE));
+
+		// retrieve the secured password
+		if (secretResolver != null && secretResolver.isInitialized() &&
+		    secretResolver.isTokenProtected(alias)) {
+
+			return secretResolver.resolve(alias);
+
+		}
+
+		return null;
+	}
+
+	public void setDataPublisherRelatedData() {
+
+		String eltStr = CloudControllerConstants.DATA_PUBLISHER_ELEMENT;
+		// get dataPublisher element
+		OMElement element =
+		                    getElement(documentElement, eltStr,
+		                               CloudControllerConstants.DATA_PUBLISHER_XPATH);
+
+		if (element == null) {
+			return;
+		}
+
+		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+		// get enable attribute
+		boolean isEnable =
+		                   Boolean.parseBoolean(element.getAttributeValue(new QName(
+		                                                                            CloudControllerConstants.ENABLE_ATTR)));
+		dataHolder.setEnableBAMDataPublisher(isEnable);
+
+		if (isEnable) {
+			// get bam server info
+			OMElement childElement =
+			                         getFirstChildElement(element,
+			                                              CloudControllerConstants.BAM_SERVER_ELEMENT);
+			OMElement elt;
+
+			if (childElement != null) {
+				// set bam user name
+				elt =
+				      getFirstChildElement(childElement,
+				                           CloudControllerConstants.BAM_SERVER_ADMIN_USERNAME_ELEMENT);
+				if (elt != null) {
+					dataHolder.setBamUsername(elt.getText());
+				}
+				// set bam password
+				elt =
+				      getFirstChildElement(childElement,
+				                           CloudControllerConstants.BAM_SERVER_ADMIN_PASSWORD_ELEMENT);
+				if (elt != null) {
+					String password = resolveSecret(elt);
+					if (password == null) {
+						plainTextWarn(CloudControllerConstants.BAM_SERVER_ADMIN_PASSWORD_ELEMENT);
+						password = elt.getText();
+					}
+
+					if (password != null) {
+						dataHolder.setBamPassword(password);
+					}
+				}
+			}
+
+			// set cron
+			childElement = getFirstChildElement(element, CloudControllerConstants.CRON_ELEMENT);
+			if (childElement != null) {
+				dataHolder.setDataPublisherCron(childElement.getText());
+			}
+
+			// set cassandra info
+			childElement = getFirstChildElement(element, CloudControllerConstants.CASSANDRA_INFO_ELEMENT);
+
+			if (childElement != null) {
+				// set connection url
+				elt = getFirstChildElement(childElement, CloudControllerConstants.CONNECTION_URL_ELEMENT);
+				if (elt != null) {
+					dataHolder.setCassandraConnUrl(elt.getText());
+				}
+
+				// set user name
+				elt = getFirstChildElement(childElement, CloudControllerConstants.USER_NAME_ELEMENT);
+				if (elt != null) {
+					dataHolder.setCassandraUser(elt.getText());
+				}
+				// set password
+				elt = getFirstChildElement(childElement, CloudControllerConstants.PASSWORD_ELEMENT);
+				if (elt != null) {
+					String password = resolveSecret(elt);
+					if (password == null) {
+						plainTextWarn(CloudControllerConstants.PASSWORD_ELEMENT);
+						password = elt.getText();
+					}
+
+					if (password != null) {
+						dataHolder.setCassandraPassword(password);
+					}
+				}
+			}
+
+		}
+
+	}
+
+	/**
+     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param aCartridge {@link Cartridge} instance.
+     * @param deploymentNodes list of deployment directory nodes
+     */
+    private void setDeploymentDirs(String cartridgeElementString, Cartridge aCartridge,
+                                   List<?> deploymentNodes) {
+	    Object nodeObj;
+	    if ((nodeObj = deploymentNodes.get(0)) instanceof OMNode) {
+	    	OMNode deploymentNode = (OMNode) nodeObj;
+
+	    	if (deploymentNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    		OMElement deployElt = (OMElement) deploymentNode;
+
+	    		if (deployElt.getAttributeValue(new QName(
+	    		                                          CloudControllerConstants.BASE_DIR_ATTR)) != null) {
+
+	    			aCartridge.setBaseDir(deployElt.getAttributeValue(new QName(
+	    			                                                            CloudControllerConstants.BASE_DIR_ATTR)));
+	    		}
+
+	    		for (Iterator<?> iterator =
+	    		                            deployElt.getChildrenWithName(new QName(
+	    		                                                                    CloudControllerConstants.DIRECTORY_ELEMENT)); iterator.hasNext();) {
+	    			OMElement dir = (OMElement) iterator.next();
+	    			aCartridge.addDeploymentDir(dir.getText());
+	    		}
+
+	    	} else {
+	    		String msg =
+	    		             "Essential '" + CloudControllerConstants.DEPLOYMENT_ELEMENT +
+	    		                     "' element cannot" + " be found in " +
+	    		                     cartridgeElementString + " of " + xmlSource;
+	    		handleException(msg);
+	    	}
+
+	    }
+    }
+
+	public void setIaasProvidersList() {
+
+		List<IaasProvider> iaasProviders = FasterLookUpDataHolder.getInstance().getIaasProviders();
+
+		if (iaasProviders == null) {
+			FasterLookUpDataHolder.getInstance()
+			                      .setIaasProviders((iaasProviders = new ArrayList<IaasProvider>()));
+		}
+
+		List<OMNode> nodeList = getMatchingNodes(CloudControllerConstants.IAAS_PROVIDER_XPATH);
+
+		// this is a valid scenario. User can have 0..1 iaas provider elements
+		// in cloud-controller xml.
+		if (nodeList == null || nodeList.isEmpty()) {
+			return;
+		}
+
+		for (OMNode node : nodeList) {
+			iaasProviders.add(getIaasProvider(node, iaasProviders));
+		}
+
+	}
+
+
+	public void setTopologySyncRelatedData() {
+
+		String eltStr = CloudControllerConstants.TOPOLOGY_SYNC_ELEMENT;
+		// get topologySync element
+		OMElement element =
+		                    getElement(documentElement, eltStr,
+		                               CloudControllerConstants.TOPOLOGY_SYNC_XPATH);
+
+		if (element == null) {
+			return;
+		}
+
+		// get enable attribute
+		boolean isEnable =
+		                   Boolean.parseBoolean(element.getAttributeValue(new QName(
+		                                                                            CloudControllerConstants.ENABLE_ATTR)));
+
+		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+		dataHolder.setEnableTopologySync(isEnable);
+
+		if (isEnable) {
+			// get MB server info
+			OMElement childElement =
+			                         getFirstChildElement(element,
+			                                              CloudControllerConstants.MB_SERVER_ELEMENT);
+
+			if (childElement != null) {
+				// set MB server IP
+				dataHolder.setMBServerUrl(childElement.getText());
+			}
+
+			// set cron
+			childElement = getFirstChildElement(element, CloudControllerConstants.CRON_ELEMENT);
+			if (childElement != null) {
+				dataHolder.setTopologySynchronizerCron(childElement.getText());
+			}
+
+		}
+
+	}
+
+	public boolean validate(final File schemaFile) throws Exception {
+		validate(documentElement, schemaFile);
+		return true;
+	}
+
+	public void validate(final OMElement omElement, final File schemaFile) throws Exception {
+
+		Element sourceElement;
+
+		// if the OMElement is created using DOM implementation use it
+		if (omElement instanceof ElementImpl) {
+			sourceElement = (Element) omElement;
+		} else { // else convert from llom to dom
+			sourceElement = getDOMElement(omElement);
+		}
+
+		// Create a SchemaFactory capable of understanding WXS schemas.
+
+		// Load a WXS schema, represented by a Schema instance.
+		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+		Source source = new StreamSource(schemaFile);
+
+		// Create a Validator object, which can be used to validate
+		// an instance document.
+		Schema schema = factory.newSchema(source);
+		Validator validator = schema.newValidator();
+
+		// Validate the DOM tree.
+		validator.validate(new DOMSource(sourceElement));
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/concurrent/ThreadExecutor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/concurrent/ThreadExecutor.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/concurrent/ThreadExecutor.java
new file mode 100644
index 0000000..ac4eeae
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/concurrent/ThreadExecutor.java
@@ -0,0 +1,53 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.concurrent;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * This class can be used to create a thread pool, and hand over new jobs to the pool.
+ */
+public class ThreadExecutor {
+    private ExecutorService executor;
+
+    public ThreadExecutor(int poolSize) {
+        executor = Executors.newFixedThreadPool(poolSize);
+    }
+    
+    public void execute(Runnable job){
+        executor.execute(job);
+    }
+    
+    public void executeAll(Runnable[] jobs){
+        for (Runnable job : jobs) {
+            
+            executor.execute(job);
+        }
+    }
+    
+    public void shutdown() {
+        // This will make the executor accept no new threads
+        // and finish all existing threads in the queue
+        executor.shutdown();
+        // Wait until all threads are finished
+        while (!executor.isTerminated()) {}
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java
new file mode 100644
index 0000000..c6d191d
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java
@@ -0,0 +1,188 @@
+package org.apache.stratos.cloud.controller.consumers;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+
+/**
+ * This class is responsible for generating the service topology and
+ * publishing it to a topic.
+ */
+public class TopologyBuilder implements Runnable {
+
+    private BlockingQueue<List<ServiceContext>> sharedQueue;
+	private static File topologyFile, backup;
+	private static final Log log = LogFactory.getLog(TopologyBuilder.class);
+	private static DeclarativeServiceReferenceHolder data = DeclarativeServiceReferenceHolder.getInstance();
+	
+	public TopologyBuilder(BlockingQueue<List<ServiceContext>> queue){
+		
+		sharedQueue = queue;
+		topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
+		backup = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH+".back");
+		
+	}
+	
+	@Override
+	public void run() {
+
+		while(true){
+            try {
+            	Object obj = sharedQueue.take();
+            	boolean isAdded = false;
+            	
+            	if(obj instanceof List<?>){
+            		@SuppressWarnings("unchecked")
+                    List<ServiceContext> ctxts = (List<ServiceContext>) obj;
+            		
+            		for (ServiceContext serviceContext : ctxts) {
+
+            			Node newNode = serviceContext.toNode();
+            			
+            			if(!topologyFile.exists()){
+            				FileUtils.writeStringToFile(topologyFile, "services {\n}");
+            			}
+            			
+            			String currentContent = FileUtils.readFileToString(topologyFile);
+            			Node currentNode = NodeBuilder.buildNode(currentContent);
+                   			
+            			for (Node aNode : currentNode.getChildNodes()) {
+            				// similar service element is present
+	                        if(aNode.getName().equals(newNode.getName())){
+	                        	// hence, we should not override, but append
+	                        	Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
+	                        	
+	                        	if(domainsNode == null){
+	                        		// existing node is useless
+	                        		currentNode.removeChildNode(aNode.getName());
+	                        		currentNode.appendChild(newNode);
+	                        		break;
+	                        	}
+	                        	
+	                        	// append the new node/s
+	                        	for (Node serNode : newNode.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
+	                                
+	                        		for (Node currentSerNode : domainsNode.getChildNodes()) {
+	                                    String prop = Constants.SUB_DOMAIN_ELEMENT;
+	                        			if(serNode.getName().equals(currentSerNode.getName()) &&
+	                        					serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
+	                        				// if domain and sub domain, are not unique, we shouldn't append, but override
+	                        				domainsNode.removeChildNode(currentSerNode.getName());
+	                        				break;
+	                        			}
+                                    }
+	                        		
+	                        		domainsNode.appendChild(serNode);
+                                }
+	                        	isAdded = true;
+	                        	break;
+	                        }
+                        }
+            			
+						if (!isAdded) {
+							currentNode.appendChild(newNode);
+						}
+						
+            			if (topologyFile.exists()) {
+            				backup.delete();
+            				topologyFile.renameTo(backup);
+            			}
+            			
+            			// overwrite the topology file
+            			FileUtils.writeStringToFile(topologyFile, currentNode.toString());
+            			
+            			// publish to the topic - to sync immediately
+            	        data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME, currentNode.toString());
+
+                    }
+            	}
+                
+            } catch (InterruptedException ignore) {
+            } catch (IOException e) {
+            	log.error(e.getMessage(), e);
+            	throw new CloudControllerException(e.getMessage(), e);
+            }
+        }
+
+	}
+	
+	public static void removeTopologyAndPublish(ServiceContext serviceContext){
+	    
+	    Node currentNodeToBeRemoved = null;
+	    Node nodeToBeRemoved = serviceContext.toNode();
+        
+        if(!topologyFile.exists()){
+            return;
+        }
+        try{
+        String currentContent = FileUtils.readFileToString(topologyFile);
+        Node currentNode = NodeBuilder.buildNode(currentContent);
+            
+        for (Node aNode : currentNode.getChildNodes()) {
+            // similar service element is present
+            if(aNode.getName().equals(nodeToBeRemoved.getName())){
+                // let's check whether the domain node exists
+                
+                Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
+                
+                if(domainsNode == null){
+                    continue;
+                }
+                
+                for (Node serNode : nodeToBeRemoved.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
+                    
+                    for (Node currentSerNode : domainsNode.getChildNodes()) {
+                        String prop = Constants.SUB_DOMAIN_ELEMENT;
+                        if(serNode.getName().equals(currentSerNode.getName()) &&
+                                serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
+                            // if domain and sub domain, are matching, we should remove the node.
+                            domainsNode.removeChildNode(currentSerNode.getName());
+                            if(domainsNode.getChildNodes().size() == 0){
+                                // if no cluster definitions remain, we shouldn't keep the node
+                                currentNodeToBeRemoved = aNode;
+                            }
+                            break;
+                        }
+                    }
+                    
+                }
+                
+            }
+        }
+        
+        if(currentNodeToBeRemoved != null){
+            // remove the node with empty clusters
+            currentNode.removeChildNode(currentNodeToBeRemoved);
+        }
+        
+        if (topologyFile.exists()) {
+            backup.delete();
+            topologyFile.renameTo(backup);
+        }
+        
+        // overwrite the topology file
+        FileUtils.writeStringToFile(topologyFile, currentNode.toString());
+        
+        // publish to the topic - to sync immediately
+        data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME, currentNode.toString());
+        
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+            throw new CloudControllerException(e.getMessage(), e);
+        }
+
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
new file mode 100644
index 0000000..a130f4e
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
@@ -0,0 +1,194 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.deployers;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.AbstractDeployer;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.apache.stratos.cloud.controller.concurrent.ThreadExecutor;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.interfaces.Iaas;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.Cartridge;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * All the {@link org.apache.stratos.cloud.controller.util.Cartridge}s will get deployed / undeployed / updated via this class.
+ */
+public class CartridgeDeployer extends AbstractDeployer{
+    
+    private static final Log log = LogFactory.getLog(CartridgeDeployer.class);
+    
+    private FasterLookUpDataHolder serviceContextLookUpStructure;
+    private Map<String, List<Cartridge>> fileToCartridgeListMap;
+    private File cartridgesSchema, cartridgeSchema;
+
+    public void init(ConfigurationContext arg0) {
+        fileToCartridgeListMap = new ConcurrentHashMap<String, List<Cartridge>>();
+        String etcDir = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator;
+        cartridgesSchema = new File(etcDir+"cartridges.xsd");
+        cartridgeSchema = new File(etcDir+"cartridge.xsd");
+    }
+
+    public void setDirectory(String arg0) {
+        // component xml handles this
+    }
+
+    public void setExtension(String arg0) {
+        // component xml handles this
+    }
+    
+    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
+        
+        log.debug("Started to deploy the deployment artifact: "+deploymentFileData.getFile());
+        
+        AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
+        parser.parse();
+
+        try {
+        	// validate
+            validateCartridge(parser);
+            
+			// deploy - grab cartridges
+			List<Cartridge> cartridges = parser.getCartridgesList();
+
+			ThreadExecutor exec = new ThreadExecutor(3);
+			// create Jclouds objects, for each IaaS
+			for (Cartridge cartridge : cartridges) {
+				// jclouds object building is time consuming, hence I use Java executor framework
+				exec.execute(new JcloudsObjectBuilder(cartridge, deploymentFileData));
+			}
+			exec.shutdown();
+			// update map
+			fileToCartridgeListMap.put(deploymentFileData.getAbsolutePath(),
+			                           new ArrayList<Cartridge>(cartridges));
+
+			log.info("Successfully deployed the Cartridge definition specified at "+deploymentFileData.getAbsolutePath());
+			
+		} catch (Exception e) {
+			String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
+            // back up the file
+            File f = deploymentFileData.getFile();
+            f.renameTo(new File(deploymentFileData.getAbsolutePath()+".back"));
+            log.error(msg, e);
+            throw new DeploymentException(msg, e);
+		} 
+        
+        
+    }
+    
+    private void validateCartridge(AxiomXpathParser parser) throws Exception {
+        boolean validated = false;
+        Exception firstException = null;
+
+        try{
+            // first try to validate using cartridges schema
+            parser.validate(cartridgesSchema);
+            validated = true;
+            
+        }catch (Exception e) {
+            firstException = e;
+        }
+        
+        if(!validated){
+            try{
+                // Now try to validate using cartridge schema
+                parser.validate(cartridgeSchema);
+                validated = true;
+                log.debug("Cartridge validation was successful.");
+                
+            }catch (Exception e) {
+                String msg = "Cartridge XML validation failed. Invalid Cartridge XML: "+parser.getXmlSource().getAbsolutePath();
+                log.error(msg, firstException);
+                throw firstException;
+            }
+        }
+        
+        
+    }
+
+    public void undeploy(String file) throws DeploymentException {
+        
+    	serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
+    	
+        // grab the entry from Map
+        if(fileToCartridgeListMap.containsKey(file)){
+            // remove 'em
+            serviceContextLookUpStructure.removeCartridges(fileToCartridgeListMap.get(file));
+            
+            log.info("Successfully undeployed the Cartridge definition specified at "+file);
+        }
+        
+    }
+    
+    private void handleException(String msg, Exception e) {
+        log.fatal(msg, e);
+        throw new CloudControllerException(msg, e);
+    }
+    
+    /**
+     * JcloudsObjectBuilder job
+     *
+     */
+    class JcloudsObjectBuilder implements Runnable{
+    	
+    	private Cartridge cartridge;
+    	private DeploymentFileData file;
+
+    	public JcloudsObjectBuilder (Cartridge cartridge, DeploymentFileData file){
+    		this.cartridge = cartridge;
+    		this.file = file;
+    	}
+    	
+		@Override
+        public void run() {
+
+			for (IaasProvider iaasProvider : cartridge.getIaases()) {
+				try {
+					Iaas iaas = (Iaas) Class.forName(iaasProvider.getClassName()).newInstance();
+					iaas.buildComputeServiceAndTemplate(iaasProvider);
+					iaasProvider.setIaas(iaas);
+					
+				} catch (Exception e) {
+					rename();
+					handleException(e.getMessage(), e);
+				}
+			}
+			
+        }
+		
+		private void rename(){
+			// back up the file
+            File f = file.getFile();
+            f.renameTo(new File(file.getAbsolutePath()+".back"));
+		}
+    	
+    }
+
+}


[09/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CloudControllerDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CloudControllerDeployer.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CloudControllerDeployer.java
new file mode 100644
index 0000000..79987b0
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/CloudControllerDeployer.java
@@ -0,0 +1,110 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.deployers;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.AbstractDeployer;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+
+/**
+ * All the {@link IaasProvider}s will get deployed / undeployed / updated via this class. 
+ */
+public class CloudControllerDeployer extends AbstractDeployer{
+    
+    private static final Log log = LogFactory.getLog(CloudControllerDeployer.class);
+    private static final String FILE_NAME = "cloud-controller";
+    private Map<String, List<IaasProvider>> fileToIaasProviderListMap;
+
+    @Override
+    public void init(ConfigurationContext arg0) {
+    	fileToIaasProviderListMap = new ConcurrentHashMap<String, List<IaasProvider>>();
+    }
+
+    @Override
+    public void setDirectory(String arg0) {
+        // component xml handles this
+        
+    }
+
+    @Override
+    public void setExtension(String arg0) {
+        // component xml handles this
+    }
+    
+    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
+        
+        log.debug("Started to deploy the deployment artifact: "+deploymentFileData.getFile());
+        
+        // since cloud-controller.xml resides in repository/conf
+		if (deploymentFileData.getName().contains(FILE_NAME)) {
+
+			AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
+
+			// parse the file
+			parser.parse();
+
+			// deploy iaases
+			parser.setIaasProvidersList();
+			parser.setDataPublisherRelatedData();
+			parser.setTopologySyncRelatedData();
+
+			// update map
+			fileToIaasProviderListMap.put(deploymentFileData.getAbsolutePath(),
+			                              new ArrayList<IaasProvider>(
+			                                                          FasterLookUpDataHolder.getInstance()
+			                                                                                .getIaasProviders()));
+
+			log.info("Successfully deployed the cloud-controller XML file specified at " +
+			         deploymentFileData.getAbsolutePath());
+		}
+        
+    }
+    
+
+    public void undeploy(String file) throws DeploymentException {
+        
+        if (file.contains(FILE_NAME)) {
+            // reset
+            FasterLookUpDataHolder.getInstance().setSerializationDir("");
+            
+            // grab the entry from Map
+            if(fileToIaasProviderListMap.containsKey(file)){
+                // remove 'em
+                FasterLookUpDataHolder.getInstance().getIaasProviders().removeAll(fileToIaasProviderListMap.get(file));
+                
+                log.info("Successfully undeployed the cloud-controller XML file specified at "+file);
+            }
+            // only one cloud-controller file, hence delete 'em all
+//            FasterLookUpDataHolder.getInstance().setIaasProviders(new ArrayList<IaasProvider>());
+            
+        }
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
new file mode 100644
index 0000000..2e37bef
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
@@ -0,0 +1,152 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.deployers;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.AbstractDeployer;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.apache.stratos.cloud.controller.consumers.TopologyBuilder;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * All the {@link org.apache.stratos.cloud.controller.util.Cartridge}s will get deployed / undeployed / updated via this class.
+ */
+public class ServiceDeployer extends AbstractDeployer{
+    
+    private static final Log log = LogFactory.getLog(ServiceDeployer.class);
+    
+    private FasterLookUpDataHolder serviceContextLookUpStructure;
+    private Map<String, List<ServiceContext>> fileToServiceContextListMap;
+    private File servicesSchema, serviceSchema;
+
+    @Override
+    public void init(ConfigurationContext arg0) {
+        fileToServiceContextListMap = new ConcurrentHashMap<String, List<ServiceContext>>();
+        String etcDir = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator;
+        servicesSchema = new File(etcDir+"services.xsd");
+        serviceSchema = new File(etcDir+"service.xsd");
+    }
+
+    @Override
+    public void setDirectory(String arg0) {
+        // component xml handles this
+    }
+
+    @Override
+    public void setExtension(String arg0) {
+        // component xml handles this
+    }
+    
+    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
+        
+        log.debug("Started to deploy the deployment artefact: "+deploymentFileData.getFile());
+        serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
+        
+        AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
+        parser.parse();
+        
+        // validate
+        try {
+            validateService(parser);
+            
+        } catch (Exception e) {
+            String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
+            // back up the file
+            File f = deploymentFileData.getFile();
+            f.renameTo(new File(deploymentFileData.getAbsolutePath()+".back"));
+            log.error(msg, e);
+            throw new DeploymentException(msg, e);
+        }
+        
+        // deploy
+        List<ServiceContext> services = parser.getServiceContexts();
+        
+        // notify consumer by adding the diff
+        try {
+	        serviceContextLookUpStructure.getSharedTopologyDiffQueue().put(services);
+        } catch (InterruptedException ignore) {
+        }
+        
+        // update map
+        fileToServiceContextListMap.put(deploymentFileData.getAbsolutePath(), new ArrayList<ServiceContext>(services));
+        
+        log.info("Successfully deployed the Service definition specified at "+deploymentFileData.getAbsolutePath());
+    }
+    
+    private void validateService(AxiomXpathParser parser) throws Exception {
+        boolean validated = false;
+        Exception firstException = null;
+
+        try{
+            // first try to validate using services schema
+            parser.validate(servicesSchema);
+            validated = true;
+            log.debug("Service validation was successful.");
+            
+        }catch (Exception e) {
+            firstException = e;
+        }
+        
+        if(!validated){
+            try{
+                // Now try to validate using service schema
+                parser.validate(serviceSchema);
+                validated = true;
+                log.debug("Service validation was successful.");
+                
+            }catch (Exception e) {
+                String msg = "Service XML validation failed. Invalid Service XML: "+parser.getXmlSource().getAbsolutePath();
+                log.error(msg, firstException);
+                throw firstException;
+            }
+        }
+        
+        
+    }
+
+    public void undeploy(String file) throws DeploymentException {
+
+        serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
+
+        // grab the entry from Map
+        if(fileToServiceContextListMap.containsKey(file)){
+            // remove 'em all
+            for (ServiceContext ctxt : fileToServiceContextListMap.get(file)) {
+                serviceContextLookUpStructure.removeServiceContext(ctxt);
+                // remove from the topology
+                TopologyBuilder.removeTopologyAndPublish(ctxt);
+            }
+            
+            log.info("Successfully undeployed the Service definition specified at "+file);
+        }
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/CloudControllerException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/CloudControllerException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/CloudControllerException.java
new file mode 100644
index 0000000..08e57f5
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/CloudControllerException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class CloudControllerException extends RuntimeException {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public CloudControllerException(String msg) {
+        super(msg);
+    }
+    
+    public CloudControllerException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/DeserializationException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/DeserializationException.java
new file mode 100644
index 0000000..33ec80b
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/DeserializationException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class DeserializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -2426068347954381831L;
+
+    public DeserializationException(String msg) {
+        super(msg);
+    }
+    
+    public DeserializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
new file mode 100644
index 0000000..363dc38
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class InvalidCartridgeDefinitionException extends Exception {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public InvalidCartridgeDefinitionException(String msg) {
+        super(msg);
+    }
+    
+    public InvalidCartridgeDefinitionException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidXMLException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidXMLException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidXMLException.java
new file mode 100644
index 0000000..d0bab7e
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/InvalidXMLException.java
@@ -0,0 +1,36 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class InvalidXMLException extends RuntimeException {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public InvalidXMLException(String msg) {
+        super(msg);
+    }
+    
+    public InvalidXMLException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+    
+    public InvalidXMLException(Exception ex) {
+        super(ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/MalformedConfigurationFileException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
new file mode 100644
index 0000000..db268f2
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class MalformedConfigurationFileException extends RuntimeException {
+
+    private static final long serialVersionUID = -1662095377704279326L;
+    
+    public MalformedConfigurationFileException(String msg) {
+        super(msg);
+    }
+    
+    public MalformedConfigurationFileException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/NoInstanceFoundException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/NoInstanceFoundException.java
new file mode 100644
index 0000000..c85d47a
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/NoInstanceFoundException.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.exception;
+
+/**
+ * This will throw when no instance is found
+ */
+public class NoInstanceFoundException extends Exception {
+
+    /**
+     * For serializing requirement
+     */
+    private static final long serialVersionUID = -435060299292679892L;
+
+
+    public NoInstanceFoundException(String msg) {
+        super(msg);
+    }
+    
+    public NoInstanceFoundException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/SerializationException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/SerializationException.java
new file mode 100644
index 0000000..b2e2302
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/SerializationException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class SerializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -3701458642228072331L;
+
+    public SerializationException(String msg) {
+        super(msg);
+    }
+    
+    public SerializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredCartridgeException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
new file mode 100644
index 0000000..96e2236
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class UnregisteredCartridgeException extends Exception {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public UnregisteredCartridgeException(String msg) {
+        super(msg);
+    }
+    
+    public UnregisteredCartridgeException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredServiceException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredServiceException.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredServiceException.java
new file mode 100644
index 0000000..166be6d
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/exception/UnregisteredServiceException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.exception;
+
+public class UnregisteredServiceException extends Exception {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public UnregisteredServiceException(String msg) {
+        super(msg);
+    }
+    
+    public UnregisteredServiceException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hector/CassandraDataRetriever.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hector/CassandraDataRetriever.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hector/CassandraDataRetriever.java
new file mode 100644
index 0000000..71aa720
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hector/CassandraDataRetriever.java
@@ -0,0 +1,181 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.hector;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+
+import me.prettyprint.cassandra.model.BasicColumnDefinition;
+import me.prettyprint.cassandra.model.BasicColumnFamilyDefinition;
+import me.prettyprint.cassandra.model.CqlQuery;
+import me.prettyprint.cassandra.model.CqlRows;
+import me.prettyprint.cassandra.serializers.StringSerializer;
+import me.prettyprint.cassandra.service.CassandraHostConfigurator;
+import me.prettyprint.cassandra.service.ThriftCfDef;
+import me.prettyprint.hector.api.Cluster;
+import me.prettyprint.hector.api.Keyspace;
+import me.prettyprint.hector.api.beans.HColumn;
+import me.prettyprint.hector.api.beans.Row;
+import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
+import me.prettyprint.hector.api.ddl.ColumnIndexType;
+import me.prettyprint.hector.api.ddl.ComparatorType;
+import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
+import me.prettyprint.hector.api.factory.HFactory;
+import me.prettyprint.hector.api.query.QueryResult;
+
+public class CassandraDataRetriever {
+
+    private static final Log log = LogFactory.getLog(CassandraDataRetriever.class);
+    private static FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+    private final static StringSerializer se = StringSerializer.get();
+    private static Cluster cluster;
+    private static Keyspace keyspace;
+    private static boolean isInit;
+    
+    public static void init() {
+
+        if(isInit){
+            return;
+        }
+        getCassandraKeyspace();
+        indexCounterColumn("payload_status");
+        isInit = true;
+    }
+    
+    public static void connect() {
+        
+        if(keyspace == null){
+            handleException("Cannot find the key space.");
+        }
+        
+        String colFamily = CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY;
+        
+        CqlQuery<String,String,String> cqlQuery = new CqlQuery<String,String,String>(keyspace, se, se, se);
+        cqlQuery.setQuery("select payload_nodeId from "+colFamily+" where payload_status='RUNNING'");
+//        cqlQuery.setQuery("select * from "+colFamily+" where payload_domain='nirmal'");
+        QueryResult<CqlRows<String,String,String>> result = cqlQuery.execute();
+        
+        if (result != null && result.get() != null) {
+            List<Row<String, String, String>> list = result.get().getList();
+            for (Row<?, ?, ?> row : list) {
+                System.out.println(".");
+                List<?> columns = row.getColumnSlice().getColumns();
+                for (Iterator<?> iterator = columns.iterator(); iterator.hasNext();) {
+                    HColumn<?, ?> column = (HColumn<?, ?>) iterator.next();
+                    System.out.print(column.getName() + ":" + column.getValue()
+                            + "\t");
+                }
+                System.out.println("");
+            }
+        }
+        
+//        ColumnQuery<String, String, String> columnQuery =
+//                HFactory.createStringColumnQuery(keyspace);
+//        KeyIterator<String> keyIterator = new KeyIterator<String>(keyspace, colFamily, StringSerializer.get());
+//        for ( String key : keyIterator ) {
+//            
+//            columnQuery.setColumnFamily(colFamily).setKey(key).setName("payload_nodeId");
+//            QueryResult<HColumn<String, String>> result = columnQuery.execute();
+//            HColumn<String, String> hColumn = result.get();
+//            System.out.println("Column: " + hColumn.getName() + " Value : " + hColumn.getValue() + "\n");
+//        }
+        
+//        //Read Data
+//        for (String key : keyList) {
+//            System.out.println("\nretrieving Key " + rowKey + "From Column Family " + columnFamily + "\n");
+//            for (String columnName : columnList.split(":")) {
+//                //sout data
+//            }
+//        }
+        
+        
+    }
+    
+    private static void indexCounterColumn(String idxColumnName) {
+
+        KeyspaceDefinition keyspaceDefinition = cluster.describeKeyspace(CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE);
+
+        List<ColumnFamilyDefinition> cdfs = keyspaceDefinition.getCfDefs();
+        ColumnFamilyDefinition cfd = null;
+        for (ColumnFamilyDefinition c : cdfs) {
+            if (c.getName().equals(CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY)) {
+                System.out.println(c.getName());
+                cfd = c;
+                break;
+            }
+        }
+
+        BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(cfd);
+
+        BasicColumnDefinition bcdf = new BasicColumnDefinition();
+        bcdf.setName(StringSerializer.get().toByteBuffer(idxColumnName));
+        bcdf.setIndexName(idxColumnName + "index");
+        bcdf.setIndexType(ColumnIndexType.KEYS);
+        bcdf.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
+
+        columnFamilyDefinition.addColumnDefinition(bcdf);
+        cluster.updateColumnFamily(new ThriftCfDef(columnFamilyDefinition));
+
+    } 
+    
+    private static void getCassandraKeyspace() {
+        if (cluster == null) {
+            Map<String, String> credentials = new HashMap<String, String>();
+            credentials.put("username", dataHolder.getCassandraUser());
+            credentials.put("password", dataHolder.getCassandraPassword());
+
+            cluster =
+                      retrieveCassandraCluster(CloudControllerConstants.DEFAULT_CASSANDRA_CLUSTER_NAME,
+                                               dataHolder.getCassandraConnUrl(), credentials);
+
+            keyspace =
+                       HFactory.createKeyspace(CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE,
+                                               cluster);
+        }
+        
+    }
+    
+    private static Cluster retrieveCassandraCluster(String clusterName, String connectionUrl,
+        Map<String, String> credentials) {
+
+        CassandraHostConfigurator hostConfigurator = new CassandraHostConfigurator(connectionUrl);
+        hostConfigurator.setRetryDownedHosts(false);
+        Cluster cluster = HFactory.createCluster(clusterName, hostConfigurator, credentials);
+        return cluster;
+    }
+
+    private static void handleException(String msg) {
+
+        log.error(msg);
+        throw new CloudControllerException(msg);
+    }
+    
+//    private void handleException(String msg, Exception e) {
+//
+//        log.error(msg, e);
+//        throw new AutoscalerServiceException(msg, e);
+//    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hive/HiveQueryExecutor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hive/HiveQueryExecutor.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hive/HiveQueryExecutor.java
new file mode 100644
index 0000000..fbbf940
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/hive/HiveQueryExecutor.java
@@ -0,0 +1,167 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.hive;
+
+import java.rmi.RemoteException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.transport.http.HttpTransportProperties;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceHiveExecutionException;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub.QueryResult;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub.QueryResultRow;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class HiveQueryExecutor {
+    private static final Log log = LogFactory.getLog(HiveQueryExecutor.class);
+    private HiveExecutionServiceStub hiveService;
+    private String payloadPrefix = CloudControllerConstants.PAYLOAD_PREFIX;
+    private String hiveTable = "cloudController";
+    private FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+    
+    public HiveQueryExecutor() {
+
+        ServerConfiguration serverConfig =  CarbonUtils.getServerConfiguration();
+        String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");
+        String serviceName = "HiveExecutionService";
+        HttpTransportProperties.Authenticator authenticator;
+        
+        try {
+            hiveService = new HiveExecutionServiceStub(bamServerUrl+"/services/"+serviceName);
+            
+            // admin service authentication
+            authenticator = new HttpTransportProperties.Authenticator();
+            authenticator.setUsername(dataHolder.getBamUsername());
+            authenticator.setPassword(dataHolder.getBamPassword());
+            authenticator.setPreemptiveAuthentication(true);
+            
+            ServiceClient client = hiveService._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
+            option.setTimeOutInMilliSeconds(120000);
+
+        } catch (AxisFault e) {
+            String msg = "Cannot get a connection to "+serviceName;
+            handleException(msg, e);
+        }
+    }
+    
+    public QueryResult[] execute(String query){
+        try {
+            return hiveService.executeHiveScript(query);
+        } catch (RemoteException e) {
+            handleException("Query : '"+query+"' - "+e.getMessage(), e);
+        } catch (HiveExecutionServiceHiveExecutionException e) {
+            handleException("Query : '"+query+"' - "+e.getMessage(), e);
+        }
+        
+        return new QueryResult[0];
+    }
+    
+    public void createHiveTable(){
+        String query = 
+                "CREATE EXTERNAL TABLE IF NOT EXISTS "+hiveTable+" (id STRING, " +
+                payloadPrefix+CloudControllerConstants.NODE_ID_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.CARTRIDGE_TYPE_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.DOMAIN_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.HOST_NAME_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.HYPERVISOR_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.IAAS_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.IMAGE_ID_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.LOGIN_PORT_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.PRIV_IP_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.PUB_IP_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.STATUS_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.SUB_DOMAIN_COL+" STRING" +
+                ") STORED BY 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' " +
+                "WITH SERDEPROPERTIES ( \"cassandra.host\" = \""+dataHolder.getCassandraConnUrl().split(":")[0]+"\"," +
+                "\"cassandra.port\" = \""+dataHolder.getCassandraConnUrl().split(":")[1]+
+                "\",\"cassandra.ks.name\" = \""+CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE+"\"," +
+                "\"cassandra.ks.username\" = \""+dataHolder.getCassandraUser()+
+                "\", \"cassandra.ks.password\" = \""+dataHolder.getCassandraPassword()+"\"," +
+                "\"cassandra.cf.name\" = \""+CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY+"\"," +
+                "\"cassandra.columns.mapping\" = \"" +
+                payloadPrefix+CloudControllerConstants.NODE_ID_COL+"," +
+                payloadPrefix+CloudControllerConstants.CARTRIDGE_TYPE_COL+"," +
+                payloadPrefix+CloudControllerConstants.DOMAIN_COL+"," +
+                payloadPrefix+CloudControllerConstants.HOST_NAME_COL+"," +
+                payloadPrefix+CloudControllerConstants.HYPERVISOR_COL+"," +
+                payloadPrefix+CloudControllerConstants.IAAS_COL+"," +
+                payloadPrefix+CloudControllerConstants.IMAGE_ID_COL+"," +
+                payloadPrefix+CloudControllerConstants.LOGIN_PORT_COL+"," +
+                payloadPrefix+CloudControllerConstants.PRIV_IP_COL+"," +
+                payloadPrefix+CloudControllerConstants.PUB_IP_COL+"," +
+                payloadPrefix+CloudControllerConstants.STATUS_COL+"," +
+                payloadPrefix+CloudControllerConstants.SUB_DOMAIN_COL +
+                "\");";
+        
+        execute(query);
+    }
+    
+    public List<String> getRunningNodeIds() {
+        List<String> nodeIds = new ArrayList<String>();
+        String query =
+//                       "select " + payloadPrefix + AutoscalerConstant.NODE_ID_COL + " from " +
+//                               hiveTable + " where payload_status='RUNNING' OR payload_status='PENDING' ;";
+
+//        "select id1 from (select distinct payload_nodeId from cloud1  where payload_status='RUNNING' OR payload_status='PENDING') table1
+//LEFT OUTER JOIN
+//(select distinct payload_nodeId as nodeId from cloud1  where payload_status='TERMINATED') table2
+//ON(table2.nodeId = table1.payload_nodeId)
+//where table2.nodeId is null;";
+                "select table1.id1 from (select distinct "+payloadPrefix+CloudControllerConstants.NODE_ID_COL+
+                " as id1 from "+ hiveTable +" where "+payloadPrefix+CloudControllerConstants.STATUS_COL+
+                "='RUNNING' OR "+payloadPrefix+CloudControllerConstants.STATUS_COL+"='PENDING') table1 " +
+                "LEFT OUTER JOIN " +"(select distinct "+payloadPrefix+CloudControllerConstants.NODE_ID_COL+
+                " as id2 from "+hiveTable+" where "+payloadPrefix+CloudControllerConstants.STATUS_COL+"='TERMINATED') table2 " +
+                "ON(table1.id1 = table2.id2) where table2.id2 is null;";
+        
+        QueryResult[] result = execute(query);
+
+        for (QueryResult queryResult : result) {
+            if(queryResult == null || queryResult.getResultRows() == null){
+                continue;
+            }
+            for (QueryResultRow row : queryResult.getResultRows()) {
+                if (row != null && row.getColumnValues() != null && row.getColumnValues().length != 0) {
+                    nodeIds.add(row.getColumnValues()[0]);
+                }
+            }
+        }
+        
+        return nodeIds;
+
+    }
+    
+    private void handleException(String msg, Exception e){
+        log.error(msg, e);
+        throw new CloudControllerException(msg, e);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/AWSEC2Iaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/AWSEC2Iaas.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/AWSEC2Iaas.java
new file mode 100644
index 0000000..3dee581
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/AWSEC2Iaas.java
@@ -0,0 +1,275 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.iaases;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.aws.ec2.AWSEC2AsyncClient;
+import org.jclouds.aws.ec2.AWSEC2Client;
+import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
+import org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;
+import org.jclouds.aws.ec2.functions.ImportOrReturnExistingKeypair;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.ec2.domain.KeyPair;
+import org.jclouds.ec2.domain.PublicIpInstanceIdPair;
+import org.jclouds.rest.RestContext;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.interfaces.Iaas;
+import org.apache.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class AWSEC2Iaas extends Iaas{
+    
+    private static final Log log = LogFactory.getLog(AWSEC2Iaas.class);
+    private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
+    private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
+
+    @Override
+    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
+
+        // builds and sets Compute Service
+        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
+        
+        // builds and sets Template
+        buildTemplate(iaasInfo);
+        
+    }
+    
+    private void buildTemplate(IaasProvider iaas) {
+        if (iaas.getComputeService() == null) {
+            String msg = "Compute service is null for IaaS provider: " + iaas.getName();
+            log.fatal(msg);
+            throw new CloudControllerException(msg);
+        }
+
+        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
+
+        // set image id specified
+        templateBuilder.imageId(iaas.getImage());
+
+        if (iaas.getProperty("instanceType") != null) {
+            // set instance type eg: m1.large
+            templateBuilder.hardwareId(iaas.getProperty("instanceType"));
+        }
+
+		// build the Template
+		Template template = templateBuilder.build();
+
+		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
+		// wish to assign IPs manually, it can be non-blocking.
+		// is auto-assign-ip mode or manual-assign-ip mode?
+		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
+		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+        
+        // this is required in order to avoid creation of additional security groups by jclouds.
+        template.getOptions().as(TemplateOptions.class).inboundPorts(new int[]{});
+
+        // set EC2 specific options
+		if (iaas.getProperty("subnetId") != null) {
+			template.getOptions().as(AWSEC2TemplateOptions.class).subnetId(iaas.getProperty("subnetId"));
+		}
+
+        if (iaas.getProperty("availabilityZone") != null) {
+            template.getOptions().as(AWSEC2TemplateOptions.class)
+                    .placementGroup(iaas.getProperty("availabilityZone"));
+        }
+
+        if (iaas.getProperty("securityGroups") != null) {
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .securityGroups(iaas.getProperty("securityGroups")
+                                        .split(CloudControllerConstants.ENTRY_SEPARATOR));
+
+        }
+
+        if (iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER) != null) {
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .userData(ComputeServiceBuilderUtil.getUserData(CarbonUtils.getCarbonHome() +
+                                                                File.separator +
+                                                                iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER)));
+        }
+
+        if (iaas.getProperty("keyPair") != null) {
+            template.getOptions().as(AWSEC2TemplateOptions.class)
+                    .keyPair(iaas.getProperty("keyPair"));
+        }
+
+        // set Template
+        iaas.setTemplate(template);
+    }
+
+    @Override
+    public void setDynamicPayload(IaasProvider iaasInfo) {
+
+        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
+
+            iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
+                    .userData(iaasInfo.getPayload());
+        }
+
+    }
+
+    @Override
+    public synchronized boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
+        String publicKey) {
+
+        String ec2Msg = " ec2. Region: "+region+" - Key Pair Name: ";
+        
+        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext = context.unwrap(RestContext.class);
+        AWSEC2Client ec2Client = restContext.getApi();
+        
+        ImportOrReturnExistingKeypair importer = new ImportOrReturnExistingKeypair(ec2Client);
+        
+        RegionNameAndPublicKeyMaterial regionNameAndKey = new RegionNameAndPublicKeyMaterial(region, keyPairName, publicKey);
+        KeyPair keyPair = importer.apply(regionNameAndKey);
+        
+        if (keyPair != null) {
+
+            iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
+                    .keyPair(keyPair.getKeyName());
+
+            log.info(SUCCESSFUL_LOG_LINE + ec2Msg + keyPair.getKeyName());
+            return true;
+        }
+        
+        log.error(FAILED_LOG_LINE+ec2Msg);
+        
+        return false;
+    }
+
+    @Override
+	public synchronized String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
+
+		ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+		@SuppressWarnings("unchecked")
+		RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext =
+		                                                           context.unwrap(RestContext.class);
+		AWSEC2Client ec2Client = restContext.getApi();
+		String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+
+		String ip = null;
+		
+		// first try to find an unassigned IP.
+		ArrayList<PublicIpInstanceIdPair> unassignedIps =
+		                                                  Lists.newArrayList(Iterables.filter(ec2Client.getElasticIPAddressServices()
+		                                                                                               .describeAddressesInRegion(region,
+		                                                                                                                          new String[0]),
+		                                                                                      new Predicate<PublicIpInstanceIdPair>() {
+
+			                                                                                      @Override
+			                                                                                      public boolean apply(PublicIpInstanceIdPair arg0) {
+				                                                                                      return arg0.getInstanceId() == null;
+			                                                                                      }
+
+		                                                                                      }));
+		
+		
+		if (!unassignedIps.isEmpty()) {
+			// try to prevent multiple parallel launches from choosing the same
+			// ip.
+			Collections.shuffle(unassignedIps);
+			ip = Iterables.getLast(unassignedIps).getPublicIp();
+		}
+		
+		// if no unassigned IP is available, we'll try to allocate an IP.
+		if (ip == null || ip.isEmpty()) {
+			try {
+				ip = ec2Client.getElasticIPAddressServices().allocateAddressInRegion(region);
+				log.info("Assigned ip [" + ip +"]");
+
+			} catch (Exception e) {
+				String msg = "Failed to allocate an IP address. All IP addresses are in use.";
+				log.error(msg, e);
+				throw new CloudControllerException(msg, e);
+			}
+		}
+
+		String id = node.getProviderId();
+
+		// wait till the fixed IP address gets assigned - this is needed before we associate a
+		// public IP
+
+		while (node.getPrivateAddresses() == null) {
+			CloudControllerUtil.sleep(1000);
+		}
+
+		int retries = 0;
+		while (retries < 12 && !associatePublicIp(ec2Client, region, ip, id)) {
+
+			// wait for 5s
+			CloudControllerUtil.sleep(5000);
+			retries++;
+		}
+
+		// FIXME make this debug
+		log.info("Successfully associated an IP address " + ip + " for node with id: " +
+		         node.getId());
+
+		return ip;
+
+	}
+
+	/**
+     * @param ec2Client
+     * @param region
+     * @param ip
+     * @param id
+     */
+	private boolean associatePublicIp(AWSEC2Client ec2Client, String region, String ip, String id) {
+		try {
+			ec2Client.getElasticIPAddressServices().associateAddressInRegion(region, ip, id);
+			log.info("Successfully associated public IP ");
+			return true;
+		} catch (Exception e) {
+			log.error("Exception in associating public IP " + e.getMessage());
+			return false;
+		}
+	}
+
+	@Override
+    public synchronized void releaseAddress(IaasProvider iaasInfo, String ip) {
+	    
+		ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+		@SuppressWarnings("unchecked")
+		RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext =
+		                                                           context.unwrap(RestContext.class);
+		AWSEC2Client ec2Client = restContext.getApi();
+		String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+
+		ec2Client.getElasticIPAddressServices().disassociateAddressInRegion(region, ip);
+		ec2Client.getElasticIPAddressServices().releaseAddressInRegion(region, ip);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/OpenstackNovaIaas.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
new file mode 100644
index 0000000..1db370a
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
@@ -0,0 +1,269 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.iaases;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.interfaces.Iaas;
+import org.apache.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.openstack.nova.v2_0.NovaAsyncClient;
+import org.jclouds.openstack.nova.v2_0.NovaClient;
+import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
+import org.jclouds.openstack.nova.v2_0.domain.FloatingIP;
+import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
+import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPClient;
+import org.jclouds.openstack.nova.v2_0.extensions.KeyPairClient;
+import org.jclouds.rest.InsufficientResourcesException;
+import org.jclouds.rest.RestContext;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class OpenstackNovaIaas extends Iaas {
+    
+    private static final Log log = LogFactory.getLog(OpenstackNovaIaas.class);
+    private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
+    private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
+
+    @Override
+    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
+
+        // builds and sets Compute Service
+        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
+        
+        // builds and sets Template
+        buildTemplate(iaasInfo);
+        
+    }
+    
+    private void buildTemplate(IaasProvider iaas) {
+        if (iaas.getComputeService() == null) {
+            throw new CloudControllerException("Compute service is null for IaaS provider: " +
+                                                 iaas.getName());
+        }
+
+        // // if domain to template map is null
+        // if (entity.getDomainToTemplateMap() == null) {
+        // // we initialize it
+        // entity.setDomainToTemplateMap(new HashMap<String, Template>());
+        // }
+
+        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
+        templateBuilder.imageId(iaas.getImage());
+
+        // to avoid creation of template objects in each and every time, we create all
+        // at once!
+        // for (org.apache.cartridge.autoscaler.service.util.ServiceContext temp :
+        // serviceContexts) {
+
+        String instanceType;
+
+        // set instance type
+        if (((instanceType = iaas.getProperty("instanceType")) != null)) {
+
+            templateBuilder.hardwareId(instanceType);
+        }
+
+        Template template = templateBuilder.build();
+        
+		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
+		// wish to assign IPs manually, it can be non-blocking.
+		// is auto-assign-ip mode or manual-assign-ip mode?
+		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
+		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+
+		// this is required in order to avoid creation of additional security groups by Jclouds.
+        template.getOptions().as(TemplateOptions.class).inboundPorts(new int[]{});
+
+        if (iaas.getProperty("securityGroups") != null) {
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .securityGroupNames(iaas.getProperty("securityGroups")
+                                            .split(CloudControllerConstants.ENTRY_SEPARATOR));
+        }
+
+        if (iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER) != null) {
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .userData(ComputeServiceBuilderUtil.getUserData(CarbonUtils.getCarbonHome() +
+                                                                File.separator +
+                                                                iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER)));
+        }
+
+        if (iaas.getProperty("keyPair") != null) {
+            template.getOptions().as(NovaTemplateOptions.class)
+                    .keyPairName(iaas.getProperty("keyPair"));
+        }
+
+        // set Template
+        iaas.setTemplate(template);
+    }
+
+    @Override
+    public void setDynamicPayload(IaasProvider iaasInfo) {
+        
+        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
+
+            iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class).userData(iaasInfo.getPayload());
+        }
+
+    }
+
+    @Override
+    public synchronized boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
+        String publicKey) {
+
+        String openstackNovaMsg = " Openstack-nova. Region: " + region + " - Name: ";
+
+        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
+        
+        KeyPairClient api = restContext.getApi().getKeyPairExtensionForZone(region).get();
+        
+        KeyPair keyPair = api.createKeyPairWithPublicKey(keyPairName, publicKey);
+
+        if (keyPair != null) {
+            
+            iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class)
+            .keyPairName(keyPair.getName());
+            
+            log.info(SUCCESSFUL_LOG_LINE + openstackNovaMsg + keyPair.getName());
+            return true;
+        }
+
+        log.error(FAILED_LOG_LINE + openstackNovaMsg);
+        return false;
+
+    }
+
+    @Override
+    public synchronized String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
+
+        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
+        
+        NovaClient novaClient = restContext.getApi();
+        String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+        
+        FloatingIPClient floatingIp = novaClient.getFloatingIPExtensionForZone(region).get();
+        
+        String ip=null;
+        // first try to find an unassigned IP.
+        ArrayList<FloatingIP> unassignedIps =
+        		Lists.newArrayList(Iterables.filter(floatingIp.listFloatingIPs(),
+        		                                    new Predicate<FloatingIP>() {
+        			
+        			@Override
+        			public boolean apply(FloatingIP arg0) {
+        				//FIXME is this the correct filter?
+        				return arg0.getFixedIp() == null;
+        			}
+        			
+        		}));
+        
+		if (!unassignedIps.isEmpty()) {
+			// try to prevent multiple parallel launches from choosing the same
+			// ip.
+			Collections.shuffle(unassignedIps);
+			ip = Iterables.getLast(unassignedIps).getIp();
+		}
+        
+        // if no unassigned IP is available, we'll try to allocate an IP.
+		if (ip == null || ip.isEmpty()) {
+
+			try {
+				ip = floatingIp.allocate().getIp();
+
+			} catch (InsufficientResourcesException e) {
+				String msg = "Failed to allocate an IP address. All IP addresses are in use.";
+				log.error(msg, e);
+				throw new CloudControllerException(msg, e);
+			}
+		}
+
+        // wait till the fixed IP address gets assigned - this is needed before we associate a public IP
+        
+        while(node.getPrivateAddresses() == null){
+        	CloudControllerUtil.sleep(1000);
+        }
+
+        int retries =0;
+        while(retries < 5 && !associateIp(floatingIp, ip, node.getProviderId()) ){
+        	
+        	// wait for 5s
+        	CloudControllerUtil.sleep(5000);
+        	retries++;
+        }
+        
+        NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip)).build();
+      
+        log.info("Successfully associated an IP address "+ip+" for node with id: "+node.getId());
+        
+        return ip;
+    }
+    
+    @Override
+    public synchronized void releaseAddress(IaasProvider iaasInfo, String ip){
+    	
+    	ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
+        
+        NovaClient novaClient = restContext.getApi();
+        String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+        
+        FloatingIPClient floatingIpClient = novaClient.getFloatingIPExtensionForZone(region).get();
+        
+        for (FloatingIP floatingIP: floatingIpClient.listFloatingIPs()) {
+	        if(floatingIP.getIp().equals(ip)){
+	        	floatingIpClient.deallocate(floatingIP.getId());
+	        	break;
+	        }
+        }
+        
+    }
+    
+    private boolean associateIp(FloatingIPClient client, String ip, String id){
+    	try{
+    		client.addFloatingIPToServer(ip, id);
+    		return true;
+    	}catch(RuntimeException ex){
+    		return false;
+    	}
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/VCloudIaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/VCloudIaas.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/VCloudIaas.java
new file mode 100644
index 0000000..9c320a2
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/iaases/VCloudIaas.java
@@ -0,0 +1,164 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.iaases;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.vcloud.compute.options.VCloudTemplateOptions;
+import org.jclouds.vcloud.domain.network.IpAddressAllocationMode;
+import org.apache.stratos.cloud.controller.interfaces.Iaas;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+
+public class VCloudIaas extends Iaas{
+    
+    private static final Log log = LogFactory.getLog(VCloudIaas.class);
+
+    @Override
+    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
+
+        // builds and sets Compute Service
+        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
+        
+        // builds and sets Template
+        buildTemplate(iaasInfo);
+        
+    }
+    
+    private void buildTemplate(IaasProvider iaas) {
+        if (iaas.getComputeService() == null) {
+            String msg = "Compute service is null for IaaS provider: " + iaas.getName();
+            log.fatal(msg);
+            throw new CloudControllerException(msg);
+        }
+
+        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
+
+        // set image id specified
+        templateBuilder.imageId(iaas.getImage());
+
+        // build the Template
+        Template template = templateBuilder.build();
+
+		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
+		// wish to assign IPs manually, it can be non-blocking.
+		// is auto-assign-ip mode or manual-assign-ip mode? - default mode is non-blocking 
+		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
+		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+		
+        // this is required in order to avoid creation of additional security groups by Jclouds.
+        template.getOptions().as(TemplateOptions.class).inboundPorts(22, 80, 8080, 443, 8243);
+
+        template.getOptions().as(VCloudTemplateOptions.class).ipAddressAllocationMode(IpAddressAllocationMode.POOL);
+
+        // set Template
+        iaas.setTemplate(template);
+    }
+
+    @Override
+    public void setDynamicPayload(IaasProvider iaasInfo) {
+
+    	// in VCloud case we need to run a script
+        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
+
+        	Template template = iaasInfo.getTemplate();
+        	String script = "";
+        	String launchParams ="", key="";
+        	
+            // open the zip file stream
+            ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(iaasInfo.getPayload()));
+
+            try
+            {
+
+                // now iterate through each item in the stream. The get next
+                // entry call will return a ZipEntry for each file in the
+                // stream
+                ZipEntry entry;
+                while((entry = stream.getNextEntry())!=null)
+                {
+                	StringWriter writer = new StringWriter();
+                	IOUtils.copy(stream, writer);
+                	
+                	if(entry.getName().contains("launch-params")){
+                		launchParams = writer.toString();
+                	} else if(entry.getName().contains("id_rsa")){
+                		key = writer.toString();
+                	}
+                	
+                }
+            } catch (IOException e) {
+	            log.error(e.getMessage(), e);
+            }
+            finally
+            {
+                // we must always close the zip file.
+                try {
+	                stream.close();
+                } catch (IOException e) {
+
+                	log.error("failed to close the ZIP stream", e);
+                }
+            }
+            
+            script = "mkdir /var/lib/cloud && mkdir /var/lib/cloud/instance && mkdir /var/lib/cloud/instance/payload && " +
+            		 "echo \""+launchParams+"\" > /var/lib/cloud/instance/payload/launch-params && " +
+            		 "echo \""+key+"\" > /var/lib/cloud/instance/payload/id_rsa && " +
+            		 "cd /opt/ && " +
+            		 "chmod 755 wso2-openstack-init.sh && "+
+            		 "./wso2-openstack-init.sh";
+        	
+        	template.getOptions().overrideLoginUser(iaasInfo.getProperty("loginUser")).overrideLoginPassword(iaasInfo.getProperty("loginPassword")).runScript(script);
+        }
+
+    }
+
+    @Override
+    public boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
+        String publicKey) {
+        
+    	//TODO
+        return false;
+    }
+
+    @Override
+    public String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
+
+    	// TODO
+        return "";
+        
+    }
+
+	@Override
+    public void releaseAddress(IaasProvider iaasInfo, String ip) {
+		//TODO
+    }
+	
+}


[08/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
new file mode 100644
index 0000000..b33d7b6
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
@@ -0,0 +1,1123 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.stratos.cloud.controller.consumers.TopologyBuilder;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.exception.UnregisteredServiceException;
+import org.apache.stratos.cloud.controller.publisher.CartridgeInstanceDataPublisherTask;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.Cartridge;
+import org.apache.stratos.cloud.controller.util.CartridgeInfo;
+import org.apache.stratos.cloud.controller.util.Properties;
+import org.apache.stratos.cloud.controller.util.Property;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.ComputeMetadata;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadata.Status;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.internal.NodeMetadataImpl;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.wso2.carbon.ntask.common.TaskException;
+import org.wso2.carbon.ntask.core.TaskInfo;
+import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo;
+import org.wso2.carbon.ntask.core.TaskManager;
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.apache.stratos.cloud.controller.exception.UnregisteredCartridgeException;
+import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.apache.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.apache.stratos.cloud.controller.persist.Deserializer;
+import org.apache.stratos.cloud.controller.registry.RegistryManager;
+import org.apache.stratos.cloud.controller.topic.TopologySynchronizerTask;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
+import org.apache.stratos.cloud.controller.util.IaasContext;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Cloud Controller Service is responsible for starting up new server instances,
+ * terminating already started instances, providing pending instance count etc.
+ * 
+ */
+public class CloudControllerServiceImpl implements CloudControllerService {
+
+	private static final Log log = LogFactory.getLog(CloudControllerServiceImpl.class);
+	private FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+
+	public CloudControllerServiceImpl() {
+
+		// acquire serialized data from registry
+		acquireData();
+
+		// gets the task service
+		TaskService taskService =
+		                          DeclarativeServiceReferenceHolder.getInstance()
+		                                                               .getTaskService();
+
+		if (dataHolder.getEnableBAMDataPublisher()) {
+
+			// register and schedule, BAM data publisher task 
+			registerAndScheduleDataPublisherTask(taskService);
+		}
+
+		if (dataHolder.getEnableTopologySync()) {
+
+			// start the topology builder thread
+			startTopologyBuilder();
+
+			// register and schedule, topology synchronizer task
+			registerAndScheduleTopologySyncerTask(taskService);
+		}
+	}
+
+    private void registerAndScheduleTopologySyncerTask(TaskService taskService) {
+	    TaskInfo taskInfo;
+	    TaskManager tm = null;
+	    try {
+
+	    	if (!taskService.getRegisteredTaskTypes()
+	    	                .contains(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE)) {
+
+	    		// topology sync
+	    		taskService.registerTaskType(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE);
+
+	    		tm =
+	    		     taskService.getTaskManager(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE);
+
+	    		TriggerInfo triggerInfo =
+	    		                          new TriggerInfo(
+	    		                                          dataHolder.getTopologySynchronizerCron());
+	    		taskInfo =
+	    		           new TaskInfo(CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME,
+	    		                        TopologySynchronizerTask.class.getName(),
+	    		                        new HashMap<String, String>(), triggerInfo);
+	    		tm.registerTask(taskInfo);
+	    	}
+
+	    } catch (Exception e) {
+	    	String msg =
+	    	             "Error scheduling task: " +
+	    	                     CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME;
+	    	log.error(msg, e);
+	    	if (tm != null) {
+	    		try {
+	    			tm.deleteTask(CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME);
+	    		} catch (TaskException e1) {
+	    			log.error(e1);
+	    		}
+	    	}
+	    	throw new CloudControllerException(msg, e);
+	    }
+    }
+
+    private void startTopologyBuilder() {
+	    // initialize TopologyBuilder Consumer
+	    Thread topologyBuilder =
+	                              new Thread(
+	                                         new TopologyBuilder(
+	                                                             dataHolder.getSharedTopologyDiffQueue()));
+	    // start consumer
+	    topologyBuilder.start();
+    }
+
+    private TaskManager registerAndScheduleDataPublisherTask(TaskService taskService) {
+	    TaskInfo taskInfo;
+	    TaskManager tm = null;
+	    // initialize and schedule the data publisher task
+	    try {
+
+	    	if (!taskService.getRegisteredTaskTypes()
+	    	                .contains(CloudControllerConstants.DATA_PUB_TASK_TYPE)) {
+
+	    		taskService.registerTaskType(CloudControllerConstants.DATA_PUB_TASK_TYPE);
+
+	    		tm = taskService.getTaskManager(CloudControllerConstants.DATA_PUB_TASK_TYPE);
+
+	    		if (!tm.isTaskScheduled(CloudControllerConstants.DATA_PUB_TASK_NAME)) {
+
+	    			TriggerInfo triggerInfo =
+	    			                          new TriggerInfo(
+	    			                                          FasterLookUpDataHolder.getInstance()
+	    			                                                                .getDataPublisherCron());
+	    			taskInfo =
+	    			           new TaskInfo(CloudControllerConstants.DATA_PUB_TASK_NAME,
+	    			                        CartridgeInstanceDataPublisherTask.class.getName(),
+	    			                        new HashMap<String, String>(), triggerInfo);
+	    			tm.registerTask(taskInfo);
+
+	    			// Following code is currently not required, due to an issue in TS API.
+	    			// tm.scheduleTask(taskInfo.getName());
+	    		}
+	    	}
+
+	    } catch (Exception e) {
+	    	String msg =
+	    	             "Error scheduling task: " +
+	    	                     CloudControllerConstants.DATA_PUB_TASK_NAME;
+	    	log.error(msg, e);
+	    	if (tm != null) {
+	    		try {
+	    			tm.deleteTask(CloudControllerConstants.DATA_PUB_TASK_NAME);
+	    		} catch (TaskException e1) {
+	    			log.error(e1);
+	    		}
+	    	}
+	    	throw new CloudControllerException(msg, e);
+	    }
+	    return tm;
+    }
+
+	private void acquireData() {
+
+		Object obj = RegistryManager.getInstance().retrieve();
+		if (obj != null) {
+			try {
+				Object dataObj = Deserializer.deserializeFromByteArray((byte[]) obj);
+				if (dataObj instanceof FasterLookUpDataHolder) {
+					FasterLookUpDataHolder serializedObj = (FasterLookUpDataHolder) dataObj;
+					FasterLookUpDataHolder currentData = FasterLookUpDataHolder.getInstance();
+					
+					// assign necessary data
+					currentData.setNodeIdToServiceContextMap(serializedObj.getNodeIdToServiceContextMap());
+					
+					// traverse through current Service Contexts
+					for (ServiceContext ctxt : currentData.getServiceCtxtList()) {
+						// traverse through serialized Service Contexts
+	                    for (ServiceContext serializedCtxt : serializedObj.getServiceCtxtList()) {
+	                    	// if a matching Service Context found
+	                        if(ctxt.equals(serializedCtxt)){
+	                        	// persisted node ids of this Service Context
+	                        	List<Object> nodeIds = serializedObj.getNodeIdsOfServiceCtxt(serializedCtxt);
+	                        	for (Object nodeIdObj : nodeIds) {
+	                                String nodeId = (String) nodeIdObj;
+	                                
+	                                // assign persisted data
+	                                currentData.addNodeId(nodeId, ctxt);
+	                                
+                                }
+	                        	
+	                        	ctxt.setIaasContextMap(serializedCtxt.getIaasCtxts());
+	                        	appendToPublicIpProperty(serializedCtxt.getProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY), ctxt);
+	                        	
+	                        	// assign lastly used IaaS
+	                        	if(serializedCtxt.getCartridge() != null && serializedCtxt.getCartridge().getLastlyUsedIaas() != null){
+	                        		
+	                        		if(ctxt.getCartridge() == null){
+	                        			// load Cartridge
+	                        			ctxt.setCartridge(loadCartridge(ctxt.getCartridgeType(), ctxt.getPayload(), serializedObj.getCartridges()));
+	                        		}
+	                        		
+	                        		IaasProvider serializedIaas = serializedCtxt.getCartridge().getLastlyUsedIaas();
+	                        		ctxt.getCartridge().setLastlyUsedIaas(serializedIaas);
+	                        		
+	                        	}
+	                        }
+                        }
+                    }
+					
+					log.debug("Data is retrieved from registry.");
+				} else {
+					log.debug("No data is persisted in registry.");
+				}
+			} catch (Exception e) {
+
+				String msg =
+				             "Unable to acquire data from Registry. Hence, any historical data will not get reflected.";
+				log.warn(msg, e);
+			}
+
+		}
+	}
+
+	@Override
+	public String startInstance(String domainName, String subDomainName) {
+
+		ComputeService computeService;
+		Template template;
+		String ip = "";
+		final Lock lock = new ReentrantLock();
+
+		// check for sub domain
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting new instance of domain : " + domainName + " and sub domain : " +
+		         subDomainName);
+
+		// get the subjected ServiceContext
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge
+		serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+		                                       serviceCtxt.getPayload(),
+		                                       FasterLookUpDataHolder.getInstance().getCartridges()));
+
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		if (serviceCtxt.getCartridge().getIaases().isEmpty()) {
+			String msg =
+			             "There's no registered IaaSes found for Cartridge type: " +
+			                     serviceCtxt.getCartridge().getType();
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// sort the IaasProviders according to scale up order
+		Collections.sort(serviceCtxt.getCartridge().getIaases(),
+		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_UP_SORT)));
+
+		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+			IaasContext ctxt = null;
+			if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
+				ctxt = serviceCtxt.addIaasContext(iaas.getType());
+			}
+
+			if (iaas.getMaxInstanceLimit() > ctxt.getCurrentInstanceCount()) {
+				try {
+
+					iaas.getIaas().setDynamicPayload(iaas);
+
+					// get the ComputeService
+					computeService = iaas.getComputeService();
+
+					// corresponding Template
+					template = iaas.getTemplate();
+
+					if (template == null) {
+						String msg =
+						             "Failed to start an instance in " +
+						                     iaas.getType() +
+						                     ". Reason : Template is null. You have not specify a matching service " +
+						                     "element in the configuration file of Autoscaler.\n Hence, will try to " +
+						                     "start in another IaaS if available.";
+						log.error(msg);
+						continue;
+					}
+
+					// set instance name as the host name
+					// template.getOptions().userMetadata("Name",
+					// serviceCtxt.getHostName());
+					// template.getOptions().as(TemplateOptions.class).userMetadata("Name",
+					// serviceCtxt.getHostName());
+
+					// generate the group id from domain name and sub domain name.
+					// Should have lower-case ASCII letters, numbers, or dashes.
+					// Should have a length between 3-15
+					String str = domainName.concat("-" + subDomainName).substring(0, 10);
+					String group = str.replaceAll("[^a-z0-9-]", "");
+
+					NodeMetadata node;
+
+					// create and start a node
+					Set<? extends NodeMetadata> nodes =
+					                                    computeService.createNodesInGroup(group, 1,
+					                                                                      template);
+
+					node = nodes.iterator().next();
+
+					String autoAssignIpProp =
+					                          iaas.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
+
+					// acquire the lock
+					lock.tryLock();
+
+					try {
+						// reset ip
+						ip = "";
+						// default behavior is autoIpAssign=false
+						if (autoAssignIpProp == null ||
+						    (autoAssignIpProp != null && autoAssignIpProp.equals("false"))) {
+							// allocate an IP address - manual IP assigning mode
+							ip = iaas.getIaas().associateAddress(iaas, node);
+						}
+
+						if (ip.isEmpty() && node.getPublicAddresses() != null &&
+						    node.getPublicAddresses().iterator().hasNext()) {
+							ip = node.getPublicAddresses().iterator().next();
+						}
+
+						// if not public IP is assigned, we're using private IP
+						if (ip.isEmpty() && node.getPrivateAddresses() != null &&
+						    node.getPrivateAddresses().iterator().hasNext()) {
+							ip = node.getPrivateAddresses().iterator().next();
+						}
+
+						if (node.getId() == null) {
+							String msg =
+							             "Node id of the starting instance is null.\n" +
+							                     node.toString();
+							log.fatal(msg);
+							throw new CloudControllerException(msg);
+						}
+
+						// add node ID
+						ctxt.addNodeId(node.getId());
+						ctxt.addNodeToPublicIp(node.getId(), ip);
+
+						// to faster look up
+						FasterLookUpDataHolder.getInstance().addNodeId(node.getId(), serviceCtxt);
+
+						serviceCtxt.getCartridge().setLastlyUsedIaas(iaas);
+
+						// add this ip to the topology
+						appendToPublicIpProperty(ip, serviceCtxt);
+
+						ctxt.incrementCurrentInstanceCountByOne();
+						
+						// persist in registry
+						persist();
+
+						// trigger topology consumers
+						List<ServiceContext> list = new ArrayList<ServiceContext>();
+						list.add(serviceCtxt);
+						try {
+							dataHolder.getSharedTopologyDiffQueue().put(list);
+							
+							// publish data
+							CartridgeInstanceDataPublisherTask.publish();
+						} catch (InterruptedException ignore) {
+						}
+
+						if (log.isDebugEnabled()) {
+							log.debug("Node details: \n" + node.toString() + "\n***************\n");
+						}
+
+						log.info("Instance is successfully starting up in IaaS " + iaas.getType() +
+						         ".\tIP Address(public/private): " + ip + "\tNode Id: " +
+						         node.getId());
+
+						return ip;
+
+					} finally {
+						// release the lock
+						lock.unlock();
+					}
+
+				} catch (Exception e) {
+					log.warn("Failed to start an instance in " + iaas.getType() +
+					         ". Hence, will try to start in another IaaS if available.", e);
+					continue;
+				}
+			} else {
+				log.warn("Max instance limit is reached in the IaaS " + iaas.getType() +
+				          " : Max instance limit: " + iaas.getMaxInstanceLimit());
+			}
+
+		}
+
+		log.error("Failed to start an instance, in any available IaaS: " + domainName +
+		          " and sub domain : " + subDomainName);
+
+		return null;
+
+	}
+
+	/**
+	 * Appends this ip to the Service Context's {@link CloudControllerConstants#PUBLIC_IP_PROPERTY}
+     * @param ip
+     * @param serviceCtxt
+     */
+	private void appendToPublicIpProperty(String ip, ServiceContext serviceCtxt) {
+		String ipStr = serviceCtxt.getProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY);
+		if (ip != null && !"".equals(ip)) {
+			serviceCtxt.setProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY,
+			                        ("".equals(ipStr) ? ""
+			                                         : ipStr +
+			                                           CloudControllerConstants.ENTRY_SEPARATOR) +
+			                                ip);
+		}
+	}
+
+	/**
+     * Persist data in registry.
+     */
+    private void persist() {
+	    try {
+	        RegistryManager.getInstance().persist(FasterLookUpDataHolder.getInstance());
+	    } catch (RegistryException e) {
+
+	    	String msg = "Failed to persist the Cloud Controller data in registry. Further, transaction roll back also failed.";
+	    	log.fatal(msg);
+	    	throw new CloudControllerException(msg, e);
+	    }
+    }
+
+	private Cartridge loadCartridge(String cartridgeType, byte[] payload, List<Cartridge> cartridges) {
+
+		for (Cartridge cartridge : cartridges) {
+			if (cartridge.getType().equals(cartridgeType)) {
+				for (IaasProvider iaas : cartridge.getIaases()) {
+					iaas.setPayload(payload);
+				}
+				return cartridge;
+			}
+		}
+
+		return null;
+	}
+
+	@Override
+	public boolean terminateInstance(String domainName, String subDomainName) {
+
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting to terminate an instance of domain : " + domainName +
+		         " and sub domain : " + subDomainName);
+
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge, if null
+		if (serviceCtxt.getCartridge() == null) {
+			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+			                                       serviceCtxt.getPayload(),
+			                                       FasterLookUpDataHolder.getInstance()
+			                                                             .getCartridges()));
+		}
+		
+		// if still, Cartridge is null
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// sort the IaasProviders according to scale down order
+		Collections.sort(serviceCtxt.getCartridge().getIaases(),
+		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
+
+		// traverse in scale down order
+		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+			String msg =
+			             "Failed to terminate an instance in " + iaas.getType() +
+			                     ". Hence, will try to terminate an instance in another IaaS if possible.";
+
+			String nodeId = null;
+
+			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+
+			// terminate the last instance first
+			for (String id : Lists.reverse(ctxt.getNodeIds())) {
+				if (id != null) {
+					nodeId = id;
+					break;
+				}
+			}
+
+			// if no matching node id can be found.
+			if (nodeId == null) {
+
+				log.warn(msg + " : Reason- No matching instance found for domain: " + domainName +
+				         " and sub domain: " + subDomainName + ".");
+				continue;
+			}
+
+			// terminate it!
+			terminate(iaas, ctxt, nodeId);
+			
+			// log information
+			logTermination(nodeId, ctxt, serviceCtxt);
+
+			return true;
+
+		}
+
+		log.info("Termination of an instance which is belong to domain '" + domainName +
+		         "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
+		         "running instance found in any available IaaS.");
+
+		return false;
+
+	}
+
+	@Override
+	public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
+
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting to terminate the last instance spawned, of domain : " + domainName +
+		         " and sub domain : " + subDomainName);
+
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge, if null
+		if (serviceCtxt.getCartridge() == null) {
+			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+			                                       serviceCtxt.getPayload(),
+			                                       FasterLookUpDataHolder.getInstance()
+			                                                             .getCartridges()));
+		}
+		
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		IaasProvider iaas = serviceCtxt.getCartridge().getLastlyUsedIaas();
+		// this is required since, we need to find the correct reference.
+		// caz if the lastly used iaas retrieved from registry, it is not a reference.
+		iaas = serviceCtxt.getCartridge().getIaasProvider(iaas.getType());
+
+		if (iaas != null) {
+
+			String nodeId = null;
+			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+
+			int i=0;
+			for (i = ctxt.getNodeIds().size()-1; i >= 0 ; i--) {
+	            String id = ctxt.getNodeIds().get(i);
+				if (id != null) {
+					nodeId = id;
+					break;
+				}
+            }
+
+			if (nodeId != null) {
+
+				// terminate it!
+				iaas = terminate(iaas, ctxt, nodeId);
+				
+				// log information
+				logTermination(nodeId, ctxt, serviceCtxt);
+
+				return true;
+			}
+
+		}
+
+		log.info("Termination of an instance which is belong to domain '" + domainName +
+		          "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
+		          "running instance found in lastly used IaaS.");
+
+		return false;
+
+	}
+
+	@Override
+	public boolean terminateAllInstances(String domainName, String subDomainName) {
+
+		boolean isAtLeastOneTerminated = false;
+		
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting to terminate all instances of domain : " + domainName +
+		         " and sub domain : " + subDomainName);
+
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge, if null
+		if (serviceCtxt.getCartridge() == null) {
+			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+			                                       serviceCtxt.getPayload(),
+			                                       FasterLookUpDataHolder.getInstance()
+			                                                             .getCartridges()));
+		}
+		
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// sort the IaasProviders according to scale down order
+		Collections.sort(serviceCtxt.getCartridge().getIaases(),
+		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
+
+		// traverse in scale down order
+		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+			
+			if (ctxt == null) {
+				log.error("Iaas Context for " + iaas.getType() + " not found. Cannot terminate instances");
+				continue;
+			}
+
+			ArrayList<String> temp = new ArrayList<String>(ctxt.getNodeIds());
+			for (String id : temp) {
+				if (id != null) {
+					// terminate it!
+					terminate(iaas, ctxt, id);
+					
+					// log information
+					logTermination(id, ctxt, serviceCtxt);
+					
+					isAtLeastOneTerminated = true;
+				}
+			}
+		}
+		
+		if(isAtLeastOneTerminated){
+			return true;
+		}
+		
+		log.info("Termination of an instance which is belong to domain '" + domainName +
+		          "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
+		          "running instance found in lastly used IaaS.");
+
+		return false;
+
+	}
+	
+	public int getPendingInstanceCount(String domainName, String subDomainName) {
+
+		subDomainName = checkSubDomain(subDomainName);
+
+		int pendingInstanceCount = 0;
+
+		ServiceContext subjectedSerCtxt =
+		                                  FasterLookUpDataHolder.getInstance()
+		                                                        .getServiceContext(domainName,
+		                                                                           subDomainName);
+
+		if (subjectedSerCtxt != null && subjectedSerCtxt.getCartridgeType() != null) {
+			
+			// load cartridge
+			subjectedSerCtxt.setCartridge(loadCartridge(subjectedSerCtxt.getCartridgeType(),
+			                                            subjectedSerCtxt.getPayload(),
+			                                            FasterLookUpDataHolder.getInstance()
+			                                                                  .getCartridges()));
+			
+			if(subjectedSerCtxt.getCartridge() == null){
+				return pendingInstanceCount;
+			}
+			
+			List<IaasProvider> iaases = subjectedSerCtxt.getCartridge().getIaases();
+			
+			for (IaasProvider iaas : iaases) {
+
+				ComputeService computeService = iaas.getComputeService();
+
+				IaasContext ctxt = null;
+				if ((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null) {
+					ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
+				}
+
+				// get list of node Ids which are belong to this domain- sub
+				// domain
+				List<String> nodeIds = ctxt.getNodeIds();
+
+				if (nodeIds.isEmpty()) {
+					log.debug("Zero nodes spawned in the IaaS " + iaas.getType() + " of domain: " +
+					          domainName + " and sub domain: " + subDomainName);
+					continue;
+				}
+
+				// get all the nodes spawned by this IaasContext
+				Set<? extends ComputeMetadata> set = computeService.listNodes();
+
+				Iterator<? extends ComputeMetadata> iterator = set.iterator();
+
+				// traverse through all nodes of this ComputeService object
+				while (iterator.hasNext()) {
+					NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
+
+					// if this node belongs to the requested domain
+					if (nodeIds.contains(nodeMetadata.getId())) {
+
+						// get the status of the node
+						Status nodeStatus = nodeMetadata.getStatus();
+
+						// count nodes that are in pending state
+						if (nodeStatus.equals(Status.PENDING)) {
+							pendingInstanceCount++;
+						}
+					}
+
+				}
+			}
+		}
+
+		log.debug("Pending instance count of domain '" + domainName + "' and sub domain '" +
+		          subDomainName + "' is " + pendingInstanceCount);
+
+		return pendingInstanceCount;
+
+	}
+
+	
+	/**
+	 * A helper method to terminate an instance.
+	 */
+	private IaasProvider terminate(IaasProvider iaasTemp, IaasContext ctxt, String nodeId) {
+
+		// this is just to be safe
+		if (iaasTemp.getComputeService() == null) {
+			String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
+			log.error(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// destroy the node
+		iaasTemp.getComputeService().destroyNode(nodeId);
+		
+		
+		String autoAssignIpProp =
+			iaasTemp.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
+		
+		// release allocated IP address
+		if (autoAssignIpProp == null ||
+			    (autoAssignIpProp != null && autoAssignIpProp.equals("false"))) {
+				// allocate an IP address - manual IP assigning mode
+			iaasTemp.getIaas().releaseAddress(iaasTemp, ctxt.getPublicIp(nodeId));
+		}		
+
+		// remove the node id
+		ctxt.removeNodeId(nodeId);
+		
+		ctxt.decrementCurrentInstanceCountByOne();
+		
+		// publish data to BAM
+		CartridgeInstanceDataPublisherTask.publish();
+
+		log.info("Node with Id: '" + nodeId + "' is terminated!");
+		return iaasTemp;
+	}
+	
+	private void logTermination(String nodeId, IaasContext ctxt, ServiceContext serviceCtxt) {
+
+		// get the ip of the terminated node
+		String ip = ctxt.getPublicIp(nodeId);
+		String ipProp = CloudControllerConstants.PUBLIC_IP_PROPERTY;
+		String ipStr = serviceCtxt.getProperty(ipProp);
+		StringBuilder newIpStr = new StringBuilder("");
+
+		for (String str : ipStr.split(CloudControllerConstants.ENTRY_SEPARATOR)) {
+			if (!str.equals(ip)) {
+				newIpStr.append(str + CloudControllerConstants.ENTRY_SEPARATOR);
+			}
+		}
+
+		// add this ip to the topology
+		serviceCtxt.setProperty(ipProp,
+		                        newIpStr.length() == 0
+		                                              ? ""
+		                                              : newIpStr.substring(0, newIpStr.length() - 1)
+		                                                        .toString());
+
+		// remove the reference
+		ctxt.removeNodeIdToPublicIp(nodeId);
+
+		// persist
+		persist();
+		
+		// trigger topology consumers
+		List<ServiceContext> list = new ArrayList<ServiceContext>();
+		list.add(serviceCtxt);
+		try {
+			dataHolder.getSharedTopologyDiffQueue().put(list);
+		} catch (InterruptedException ignore) {
+		}
+
+	}
+
+	/**
+	 * Comparator to compare {@link IaasProvider} on different attributes.
+	 */
+	public enum IaasProviderComparator implements Comparator<IaasProvider> {
+		SCALE_UP_SORT {
+			public int compare(IaasProvider o1, IaasProvider o2) {
+				return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
+			}
+		},
+		SCALE_DOWN_SORT {
+			public int compare(IaasProvider o1, IaasProvider o2) {
+				return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
+			}
+		};
+
+		public static Comparator<IaasProvider> ascending(final Comparator<IaasProvider> other) {
+			return new Comparator<IaasProvider>() {
+				public int compare(IaasProvider o1, IaasProvider o2) {
+					return other.compare(o1, o2);
+				}
+			};
+		}
+
+		public static Comparator<IaasProvider> getComparator(final IaasProviderComparator... multipleOptions) {
+			return new Comparator<IaasProvider>() {
+				public int compare(IaasProvider o1, IaasProvider o2) {
+					for (IaasProviderComparator option : multipleOptions) {
+						int result = option.compare(o1, o2);
+						if (result != 0) {
+							return result;
+						}
+					}
+					return 0;
+				}
+			};
+		}
+	}
+
+	@Override
+	public boolean registerService(String domain, String subDomain, String tenantRange,
+	                               String cartridgeType, String hostName, Properties properties, byte[] payload)
+	                                                                                     throws UnregisteredCartridgeException {
+
+		// create a ServiceContext dynamically
+		ServiceContext newServiceCtxt = new ServiceContext();
+		newServiceCtxt.setDomainName(domain);
+		newServiceCtxt.setSubDomainName(subDomain);
+		newServiceCtxt.setTenantRange(tenantRange);
+		newServiceCtxt.setHostName(hostName);
+		
+		if (properties != null && properties.getProperties() != null ) {
+			// add properties
+			for (Property property : properties.getProperties()) {
+				if (property != null && property.getName() != null) {
+					newServiceCtxt.setProperty(property.getName(), property.getValue());
+				}
+			}
+		}
+		
+		newServiceCtxt.setCartridgeType(cartridgeType);
+
+		for (Cartridge cartridge : FasterLookUpDataHolder.getInstance().getCartridges()) {
+			if (cartridge.getType().equals(cartridgeType)) {
+				newServiceCtxt.setCartridge(cartridge);
+				break;
+			}
+		}
+
+		if (newServiceCtxt.getCartridge() == null) {
+			String msg = "Registration failed - Unregistered Cartridge type: " + cartridgeType;
+			log.error(msg);
+			throw new UnregisteredCartridgeException(msg);
+		}
+
+		if (payload != null && payload.length != 0) {
+
+			// write payload file
+			try {
+				String uniqueName = domain + "-" + subDomain + ".txt";
+				FileUtils.forceMkdir(new File(CloudControllerConstants.PAYLOAD_DIR));
+				File payloadFile = new File(CloudControllerConstants.PAYLOAD_DIR + uniqueName);
+				FileUtils.writeByteArrayToFile(payloadFile, payload);
+				newServiceCtxt.setPayloadFile(payloadFile.getPath());
+
+			} catch (IOException e) {
+				String msg =
+				             "Failed while persisting the payload of domain : " + domain +
+				                     ", sub domain : " + subDomain;
+				log.error(msg, e);
+				throw new CloudControllerException(msg, e);
+			}
+
+		} else {
+			log.debug("Payload is null or empty for :\n "+newServiceCtxt.toNode().toString());
+		}
+
+		// persist
+		try {
+			String uniqueName = domain + "-" + subDomain + "-" + UUID.randomUUID() + ".xml";
+			FileUtils.writeStringToFile(new File(CloudControllerConstants.SERVICES_DIR + uniqueName),
+			                            newServiceCtxt.toXml());
+		} catch (IOException e) {
+			String msg =
+			             "Failed while persisting the service configuration - domain : " + domain +
+			                     ", sub domain : " + subDomain + ", tenant range: " + tenantRange +
+			                     ", cartridge type: " + cartridgeType;
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		log.info("Service successfully registered! Domain - " + domain + ", Sub domain - " +
+		         newServiceCtxt.getSubDomainName() + ", Cartridge type - " + cartridgeType);
+
+		return true;
+	}
+
+	@Override
+	public String[] getRegisteredCartridges() {
+		// get the list of cartridges registered
+		List<Cartridge> cartridges = FasterLookUpDataHolder.getInstance().getCartridges();
+
+		if (cartridges == null) {
+			return new String[0];
+		}
+
+		String[] cartridgeTypes = new String[cartridges.size()];
+		int i = 0;
+
+		for (Cartridge cartridge : cartridges) {
+			cartridgeTypes[i] = cartridge.getType();
+			i++;
+		}
+
+		return cartridgeTypes;
+	}
+
+	@Override
+	public boolean createKeyPairFromPublicKey(String cartridgeType, String keyPairName,
+	                                          String publicKey) {
+
+		Cartridge cartridge = FasterLookUpDataHolder.getInstance().getCartridge(cartridgeType);
+
+		if (cartridge == null) {
+			String msg = "Invalid Cartridge type specified : " + cartridgeType;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		for (IaasProvider iaas : cartridge.getIaases()) {
+			String region = ComputeServiceBuilderUtil.extractRegion(iaas);
+
+			if (region == null) {
+				String msg =
+				             "Cannot find a region to create the key pair. Please add a property called 'region' under IaaS '" +
+				                     iaas.getType() + "' of Cartridge - " + cartridgeType;
+				log.fatal(msg);
+				throw new CloudControllerException(msg);
+			}
+
+			return iaas.getIaas().createKeyPairFromPublicKey(iaas, region, keyPairName, publicKey);
+		}
+
+		return false;
+	}
+
+	private String checkSubDomain(String subDomainName) {
+		// if sub domain is null, we assume it as default one.
+		if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
+			subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+			log.debug("Sub domain is null, hence using the default value : " + subDomainName);
+		}
+
+		return subDomainName;
+	}
+
+	@Override
+	public CartridgeInfo getCartridgeInfo(String cartridgeType)
+	                                                           throws UnregisteredCartridgeException {
+		Cartridge cartridge = FasterLookUpDataHolder.getInstance().getCartridge(cartridgeType);
+
+		if (cartridge != null) {
+
+			return CloudControllerUtil.toCartridgeInfo(cartridge);
+
+		}
+
+		String msg =
+		             "Cannot find a Cartridge having a type of " + cartridgeType +
+		                     ". Hence unable to find information.";
+		log.error(msg);
+		throw new UnregisteredCartridgeException(msg);
+	}
+
+	@Override
+    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException {
+		
+		subDomain = checkSubDomain(subDomain);
+
+		// find the service context
+		ServiceContext subjectedSerCtxt =
+		                                  FasterLookUpDataHolder.getInstance()
+		                                                        .getServiceContext(domain,
+		                                                                           subDomain);
+		
+		if(subjectedSerCtxt == null){
+			throw new UnregisteredServiceException("No registered service found for domain: "+domain+" - sub domain: "+subDomain);
+		}
+		
+		// get the service definition file.
+		File serviceDefFile = subjectedSerCtxt.getFile();
+		
+		// delete that file, so that it gets automatically undeployed.
+	    return serviceDefFile.delete();
+    }
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
new file mode 100644
index 0000000..462afd9
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.interfaces;
+
+import org.apache.stratos.cloud.controller.exception.UnregisteredServiceException;
+import org.apache.stratos.cloud.controller.util.CartridgeInfo;
+import org.apache.stratos.cloud.controller.util.Properties;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.apache.stratos.cloud.controller.exception.UnregisteredCartridgeException;
+
+/**
+ * This Interface provides a way to communicate with underline
+ * Infrastructure which are supported by <i>JClouds</i>.
+ * 
+ */
+public interface CloudControllerService {
+
+    /**
+     * Creates a key pair in all IaaSes that are configured for the given cartridge,
+     * having the given name and public key.
+     * 
+     * <p/>
+     * <h4>Supported Formats</h4>
+     * <ul>
+     * <li>OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)</li>
+     * <li>Base64 encoded DER format</li>
+     * <li>SSH public key file format as specified in RFC4716</li>
+     * </ul>
+     * DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
+     * <p/>
+     * Supported lengths: 1024, 2048, and 4096.
+     * <p/>
+     * 
+     * @param cartridgeType
+     *            type of the cartridge. Note this cartridge type should be already
+     *            registered one.
+     * @param keyPairName
+     *            name of the key pair which is going to get created in IaaSes.
+     * @param publicKey
+     *            The public key.
+     * 
+     */
+	@Deprecated
+    public boolean createKeyPairFromPublicKey(String cartridgeType, String keyPairName,
+        String publicKey);
+
+    /**
+     * This method will return the information regarding the given cartridge, if present.
+     * Else this will return <code>null</code>.
+     * 
+     * @param cartridgeType
+     *            type of the cartridge.
+     * @return {@link org.apache.stratos.cloud.controller.util.CartridgeInfo} of the given cartridge type or <code>null</code>.
+     * @throws UnregisteredCartridgeException if there is no registered cartridge with this type.
+     */
+    public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException;
+
+    /**
+     * Calling this method will result in returning the pending instances
+     * count of a particular domain.
+     * 
+     * @param domainName
+     *            service cluster domain
+     * @param sudDomainName
+     *            service clustering sub domain of the instance to be started up.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return number of pending instances for this domain. If no instances of this
+     *         domain is present, this will return zero.
+     */
+    public int getPendingInstanceCount(String domainName, String subDomainName);
+
+    /**
+     * Calling this method will result in returning the types of {@link org.apache.stratos.cloud.controller.util.Cartridge}s
+     * registered in Cloud Controller.
+     * 
+     * @return String array containing types of registered {@link org.apache.stratos.cloud.controller.util.Cartridge}s.
+     */
+    public String[] getRegisteredCartridges();
+    
+    /**
+     * <p>
+     * Registers the details of a newly created service cluster. This will override an already
+     * present service cluster, if there is any. A service cluster is uniquely identified by its
+     * domain and sub domain combination.
+     * </p>
+     * @param domain
+     *            service cluster domain
+     * @param subDomain
+     *            service cluster sub domain
+     * @param tenantRange 
+     * 			  tenant range eg: '1-10' or '2'
+     * @param cartridgeType
+     *            cartridge type of the new service. This should be an already registered cartridge
+     *            type.
+     * @param hostName
+     * 			  host name of this service instance
+     * @param properties
+     * 			  Set of properties related to this service definition.
+     * @param payload
+     *            payload which will be passed to instance to be started. Payload shouldn't contain 
+     *            xml tags.
+     * @return whether the registration is successful or not.
+     * 
+     * @throws UnregisteredCartridgeException
+     *             when the cartridge type requested by this service is
+     *             not a registered one.
+     */
+    public boolean registerService(String domain, String subDomain, String tenantRange, String cartridgeType,
+        String hostName, Properties properties, byte[] payload) throws UnregisteredCartridgeException;
+
+    /**
+     * Calling this method will result in an instance startup, which is belong
+     * to the provided service domain. Also note that the instance that is starting up
+     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
+     * by a hyphen (<i>-</i>).
+     * 
+     * @param domainName
+     *            service clustering domain of the instance to be started up.
+     * @param subDomainName
+     *            service clustering sub domain of the instance to be started up.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return public IP which is associated with the newly started instance.
+     */
+    public String startInstance(String domainName, String subDomainName);
+
+    /**
+     * Calling this method will result in termination of all instances belong
+     * to the provided service domain and sub domain.
+     * 
+     * @param domainName
+     *            service domain of the instance to be terminated.
+     * @param sudDomainName
+     *            service clustering sub domain of the instances to be terminated.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether an instance terminated successfully or not.
+     */
+    public boolean terminateAllInstances(String domainName, String subDomainName);
+
+    /**
+     * Calling this method will result in termination of an instance which is belong
+     * to the provided service domain and sub domain.
+     * 
+     * @param domainName
+     *            service domain of the instance to be terminated.
+     * @param sudDomainName
+     *            service clustering sub domain of the instance to be terminated.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether an instance terminated successfully or not.
+     */
+    public boolean terminateInstance(String domainName, String subDomainName);
+    
+    /**
+     * Calling this method will result in termination of the lastly spawned instance which is
+     * belong to the provided service domain and sub domain.
+     * 
+     * @param domainName
+     *            service domain of the instance to be terminated.
+     * @param sudDomainName
+     *            service clustering sub domain of the instance to be terminated.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether the termination is successful or not.
+     */
+    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
+
+    /**
+     * Unregister the service cluster which represents by this domain and sub domain.
+     * @param domain service cluster domain
+     * @param subDomain service cluster sub domain
+     * @return whether the unregistration was successful or not.
+     * @throws org.apache.stratos.cloud.controller.exception.UnregisteredServiceException if the service cluster requested is not a registered one.
+     */
+    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/Iaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/Iaas.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/Iaas.java
new file mode 100644
index 0000000..ceb1bcb
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/interfaces/Iaas.java
@@ -0,0 +1,73 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.interfaces;
+
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.Template;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+
+/**
+ * All IaaSes that are going to support by Cloud Controller, should extend this abstract class.
+ */
+public abstract class Iaas {
+    
+    /**
+     * This should build the {@link ComputeService} object and the {@link Template} object,
+     * using the information from {@link IaasProvider} and should set the built 
+     * {@link ComputeService} object in the {@link IaasProvider#setComputeService(ComputeService)}
+     * and also should set the built {@link Template} object in the 
+     * {@link IaasProvider#setTemplate(Template)}.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     */
+    public abstract void buildComputeServiceAndTemplate(IaasProvider iaasInfo);
+    
+    /**
+     * This method provides a way to set payload that can be obtained from {@link IaasProvider#getPayload()}
+     * in the {@link Template} of this IaaS.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     */
+    public abstract void setDynamicPayload(IaasProvider iaasInfo);
+    
+    /**
+     * This will obtain an IP address from the allocated list and associate that IP with this node.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     * @param node Node to be associated with an IP.
+     * @return associated public IP.
+     */
+    public abstract String associateAddress(IaasProvider iaasInfo, NodeMetadata node);
+    
+    /**
+     * This will deallocate/release the given IP address back to pool.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     * @param ip public IP address to be released.
+     */
+    public abstract void releaseAddress(IaasProvider iaasInfo, String ip);
+    
+    /**
+     * This method should create a Key Pair corresponds to a given public key in the respective region having the name given.
+     * Also should override the value of the key pair in the {@link Template} of this IaaS.
+     * @param iaasInfo {@link IaasProvider} 
+     * @param region region that the key pair will get created.
+     * @param keyPairName name of the key pair. NOTE: Jclouds adds a prefix : <code>jclouds#</code>
+     * @param publicKey public key, from which the key pair will be created.
+     * @return whether the key pair creation is successful or not.
+     */
+    public abstract boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName, String publicKey);
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
new file mode 100644
index 0000000..0152a75
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
@@ -0,0 +1,85 @@
+package org.apache.stratos.cloud.controller.internal;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.impl.CloudControllerServiceImpl;
+import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.apache.stratos.cloud.controller.topic.ConfigurationPublisher;
+import org.apache.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+
+/**
+ * Registering Cloud Controller Service.
+ * 
+ * @scr.component name="org.wso2.carbon.stratos.cloud.controller" immediate="true"
+ * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
+ *                cardinality="1..1" policy="dynamic" bind="setTaskService"
+ *                unbind="unsetTaskService"
+ * @scr.reference name="registry.service"
+ *                interface=
+ *                "org.wso2.carbon.registry.core.service.RegistryService"
+ *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ *                unbind="unsetRegistryService"
+ */
+public class CloudControllerDSComponent {
+
+    private static final Log log = LogFactory.getLog(CloudControllerDSComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+        	if (DeclarativeServiceReferenceHolder.getInstance().getConfigPub() == null) {
+        		DeclarativeServiceReferenceHolder.getInstance()
+        		.setConfigPub(new ConfigurationPublisher());
+        	}
+            
+            BundleContext bundleContext = context.getBundleContext();
+            bundleContext.registerService(CloudControllerService.class.getName(),
+                                          new CloudControllerServiceImpl(), null);
+            
+
+            log.debug("******* Cloud Controller Service bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Cloud Controller Service bundle is failed to activate ****", e);
+        }
+    }
+    
+    protected void setTaskService(TaskService taskService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Setting the Task Service");
+        }
+        DeclarativeServiceReferenceHolder.getInstance().setTaskService(taskService);
+    }
+
+    protected void unsetTaskService(TaskService taskService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unsetting the Task Service");
+        }
+        DeclarativeServiceReferenceHolder.getInstance().setTaskService(null);
+    }
+    
+	protected void setRegistryService(RegistryService registryService) {
+		if (log.isDebugEnabled()) {
+			log.debug("Setting the Registry Service");
+		}
+		try {
+	        DeclarativeServiceReferenceHolder.getInstance()
+	                                             .setRegistry(registryService.getGovernanceSystemRegistry());
+        } catch (RegistryException e) {
+        	String msg = "Failed when retrieving Governance System Registry.";
+        	log.error(msg, e);
+        	throw new CloudControllerException(msg, e);
+        }
+	}
+
+	protected void unsetRegistryService(RegistryService registryService) {
+		if (log.isDebugEnabled()) {
+            log.debug("Unsetting the Registry Service");
+        }
+        DeclarativeServiceReferenceHolder.getInstance().setRegistry(null);
+	}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
new file mode 100644
index 0000000..e80f949
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
@@ -0,0 +1,182 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.jcloud;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.jclouds.ContextBuilder;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
+import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
+import org.jclouds.sshj.config.SshjSshClientModule;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.inject.Module;
+
+/**
+ * This class is responsible for creating a JClouds specific ComputeService object.
+ */
+public class ComputeServiceBuilderUtil {
+    
+    private static final Log log = LogFactory.getLog(ComputeServiceBuilderUtil.class);
+    
+    public static byte[] getUserData(String payloadFileName) {
+        // String userData = null;
+        byte[] bytes = null;
+        try {
+            File file = new File(payloadFileName);
+            if (!file.exists()) {
+                handleException("Payload file " + payloadFileName + " does not exist");
+            }
+            if (!file.canRead()) {
+                handleException("Payload file " + payloadFileName + " does cannot be read");
+            }
+            bytes = getBytesFromFile(file);
+
+        } catch (IOException e) {
+            handleException("Cannot read data from payload file " + payloadFileName, e);
+        }
+        return bytes;
+    }
+
+    
+    public static void buildDefaultComputeService(IaasProvider iaas) {
+
+        Properties properties = new Properties();
+
+        // load properties
+        for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
+            properties.put(entry.getKey(), entry.getValue());
+        }
+
+        // set modules
+        Iterable<Module> modules =
+            ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
+                                     new EnterpriseConfigurationModule());
+
+        // build context
+        ContextBuilder builder =
+            ContextBuilder.newBuilder(iaas.getProvider())
+                          .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
+                          .overrides(properties);
+
+        // set the compute service object
+        iaas.setComputeService(builder.buildView(ComputeServiceContext.class).getComputeService());
+    }
+    
+    public static String extractRegion(IaasProvider iaas) {
+        String region;
+        // try to find region
+        if ((region = iaas.getProperty(CloudControllerConstants.REGION_PROPERTY)) == null) {
+            // if the property, isn't specified, try to obtain from the image id
+            // image id can be in following format - {region}/{UUID}
+            region = iaas.getImage().contains("/") ? iaas.getImage().split("/")[0] : null;
+        }
+
+        return region;
+    }
+    
+    /** Returns the contents of the file in a byte array
+     *
+     * @param file
+     *            - Input File
+     * @return Bytes from the file
+     * @throws java.io.IOException
+     *             , if retrieving the file contents failed.
+     */
+    public static byte[] getBytesFromFile(File file) throws IOException {
+        if (!file.exists()) {
+            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
+            return null;
+        }
+        InputStream is = new FileInputStream(file);
+        byte[] bytes;
+
+        try {
+            // Get the size of the file
+            long length = file.length();
+            
+            // You cannot create an array using a long type.
+            // It needs to be an int type.
+            // Before converting to an int type, check
+            // to ensure that file is not larger than Integer.MAX_VALUE.
+            if (length > Integer.MAX_VALUE) {
+                if (log.isDebugEnabled()) {
+                    log.debug("File is too large");
+                }
+            }
+
+            // Create the byte array to hold the data
+            bytes = new byte[(int) length];
+
+            // Read in the bytes
+            int offset = 0;
+            int numRead;
+            while (offset < bytes.length &&
+                (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+                offset += numRead;
+            }
+
+            // Ensure all the bytes have been read in
+            if (offset < bytes.length) {
+                throw new IOException("Could not completely read file " + file.getName());
+            }
+        } finally {
+            // Close the input stream and return bytes
+            is.close();
+         }
+        
+        return bytes;
+    }
+    
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     */
+    private static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     * @param e
+     *            exception
+     */
+    private static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Deserializer.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Deserializer.java
new file mode 100644
index 0000000..bafddb7
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Deserializer.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.persist;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Deserializer {
+    
+    private static final Log log = LogFactory.getLog(Deserializer.class);
+
+    /**
+     * We deserialize only if the path to the serialized object file is exists.
+     * @param filePath path to the serialized object file
+     * @return the object obtained after deserialization or null if file isn't valid.
+     * @throws Exception
+     */
+    public static Object deserialize(String filePath) throws Exception {
+
+        ObjectInputStream objIn = null; 
+        Object obj = null;
+        
+        if(!new File(filePath).isFile()){
+            return obj;
+        }
+        
+        try {
+
+            objIn = new ObjectInputStream(new FileInputStream(filePath));
+            obj = objIn.readObject();
+
+        } catch (IOException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } catch (ClassNotFoundException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } finally{
+            objIn.close();
+        }
+        
+        return obj;
+
+    }
+    
+    /**
+     * Deserialize a byte array and retrieve the object.
+     * @param bytes bytes to be deserialized
+     * @return the deserialized {@link Object}
+     * @throws Exception if the deserialization is failed.
+     */
+    public static Object deserializeFromByteArray(byte[] bytes) throws Exception {
+
+    	ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
+    	ObjectInput in = null;
+    	try {
+    	  in = new ObjectInputStream(bis);
+    	  Object o = in.readObject(); 
+    	  
+    	  return o;
+    	  
+    	} finally {
+    	  bis.close();
+    	  in.close();
+    	}
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Serializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Serializer.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Serializer.java
new file mode 100644
index 0000000..9ce69cb
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/persist/Serializer.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.persist;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Serializer {
+    
+    private static final Log log = LogFactory.getLog(Serializer.class);
+
+    public static void serializeToFile(Object serializableObj, String filePath) throws IOException {
+
+        File outFile = new File(filePath);
+        ObjectOutput ObjOut = null;
+        
+        try {
+
+            if(outFile.createNewFile()){
+                log.debug("Serialization file is created at "+filePath);
+            } else{
+                log.debug("Serialization file is already existing at "+filePath);
+            }
+            
+            ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
+            ObjOut.writeObject(serializableObj);
+
+        } catch (IOException e) {
+            log.error("Failed to serialize the object "+serializableObj.toString()
+                      + " to file "+filePath , e);
+            throw e;
+            
+        } finally{
+            ObjOut.close();
+        }
+
+    }
+    
+    /**
+     * Serialize a {@link org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder} to a byte array.
+     * @param serializableObj
+     * @return byte[] 
+     * @throws IOException
+     */
+    public static byte[] serializeToByteArray(FasterLookUpDataHolder serializableObj) throws IOException {
+
+    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
+    	ObjectOutput out = null;
+    	try {
+    	  out = new ObjectOutputStream(bos);   
+    	  out.writeObject(serializableObj);
+    	  
+    	  return bos.toByteArray();
+    	  
+    	} finally {
+    	  out.close();
+    	  bos.close();
+    	}
+
+    }
+
+}


[05/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml
deleted file mode 100644
index db3e774..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml
+++ /dev/null
@@ -1,324 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ Licensed under the Apache License, Version 2.0 (the "License");
- ~ you may not use this file except in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~      http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
--->
-<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.wso2.carbon</groupId>
-       <artifactId>stratos-components</artifactId>
-       <version>2.1.0</version>
-       <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>org.wso2.carbon</groupId>
-    <artifactId>org.wso2.carbon.stratos.cloud.controller</artifactId>
-    <packaging>bundle</packaging>
-    <version>2.1.3</version>
-    <name>WSO2 Carbon - Stratos Cloud Controller</name>
-    <url>http://wso2.org</url>
-
-    <build>
-        <plugins>
-            <!--plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-shade-plugin</artifactId>
-                <version>1.7.1</version>
-                <executions>
-                    <execution>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>shade</goal>
-                        </goals>
-                        <configuration>
-                            <artifactSet>
-                                <includes>
-                                    <include>org.jclouds:*</include>
-                                    <include>org.jclouds.*:*</include>
-                                </includes>
-                            </artifactSet>
-                            <filtering>true</filtering>
-                            <filters>
-                                <filter>
-                                    <artifact>org.jclouds*:*</artifact>
-                                    <includes>
-                                        <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
-                                        <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
-                                    </includes>
-                                </filter>
-                            </filters>
-                            <transformers>
-                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
-                                </transformer>
-                            </transformers>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin-->
-            <!--plugin>
-                <groupId>org.apache.axis2</groupId>
-                <artifactId>axis2-aar-maven-plugin</artifactId>
-                <version>1.4</version>
-                <extensions>true</extensions>
-            </plugin-->
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.wso2.carbon.stratos.cloud.controller.interfaces.*,
-                            org.wso2.carbon.stratos.cloud.controller.publisher.*,
-                            org.wso2.carbon.stratos.cloud.controller.topic.*,
-                            org.wso2.carbon.stratos.cloud.controller.iaases.*,
-                            org.wso2.carbon.stratos.cloud.controller.util.*
-                        </Export-Package>
-                        <Private-Package>
-                            org.wso2.carbon.stratos.cloud.controller.*,
-                            !org.wso2.carbon.stratos.cloud.controller.interfaces,
-                            !org.wso2.carbon.stratos.cloud.controller.publisher,
-                            !org.wso2.carbon.stratos.cloud.controller.topic,
-                            !org.wso2.carbon.stratos.cloud.controller.iaases 
-                        </Private-Package>
-                        <Import-Package>
-                        	  !org.apache.commons.logging,
-                            org.apache.commons.logging; version=0.0.0,
-                            org.wso2.carbon.utils.*,
-                            <!--org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
-                            org.jclouds*;version="${jclouds.version}",-->
-                            *; resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                        
-                        <Axis2Deployer>CloudControllerDeployer</Axis2Deployer>
-                        
-                        <Axis2Deployer>CartridgeDeployer</Axis2Deployer>
-                        
-                        <Axis2Deployer>ServiceDeployer</Axis2Deployer>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-	    <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-	    <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.lb.common</artifactId>
-            <version>4.1.3</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.securevault</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-    		<groupId>org.hectorclient.wso2</groupId>
-	    	<artifactId>hector-core</artifactId>
-		    <version>1.1.0.wso2v1</version>
-	        <exclusions>
-	            <exclusion>
-	                <groupId>com.google.guava.wso2</groupId>
-	                <artifactId>guava</artifactId>
-	            </exclusion>
-	        </exclusions>
-
-		</dependency>
-        <dependency>
-            <groupId>com.google.guava.wso2</groupId>
-	        <artifactId>guava</artifactId>
-            <version>${google.guava.wso2.version}</version>
-        </dependency>
-        <dependency>
-                <groupId>org.wso2.andes.wso2</groupId>
-                <artifactId>andes-client</artifactId>
-                <version>0.13.wso2v3</version>
-            </dependency>
-        <dependency>
-                <groupId>org.apache.geronimo.specs.wso2</groupId>
-                <artifactId>geronimo-jms_1.1_spec</artifactId>
-                <version>${orbit.version.geronimo-jms_1.1_spec}</version>
-            </dependency>
-        
-        <dependency>
-        	<groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.analytics.hive.stub</artifactId>
-   			<version>4.1.0</version>
-        </dependency> 
-	
-        <!--  Jclouds dependencies -->
-       <dependency>
-           <groupId>org.jclouds</groupId>
-           <artifactId>jclouds-core</artifactId>
-           <version>${jclouds.version}</version>
-          </dependency>
-        <dependency>
-           <groupId>org.jclouds</groupId>
-           <artifactId>jclouds-compute</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-	 <dependency>
-            <groupId>org.jclouds.api</groupId>
-            <artifactId>vcloud</artifactId>
-            <version>1.6.0-wso2v1</version>
-        </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-bouncycastle</artifactId>
-           <version>${jclouds.version}</version>
-           <exclusions>
-              <exclusion>
-                 <groupId>org.bouncycastle</groupId>
-                 <artifactId>bcprov-jdk16</artifactId>
-              </exclusion>
-           </exclusions>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-sshj</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-log4j</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-enterprise</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.api</groupId>
-           <artifactId>ec2</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.provider</groupId>
-           <artifactId>aws-ec2</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.api</groupId>
-           <artifactId>openstack-nova</artifactId>
-           <version>${jclouds.wso2.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.api</groupId>
-           <artifactId>openstack-keystone</artifactId>
-           <version>${jclouds.wso2.version}</version>
-         </dependency>
-         <dependency>
-          <groupId>org.jclouds</groupId>
-            <artifactId>jclouds-scriptbuilder</artifactId>
-              <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-          <groupId>org.jclouds.common</groupId>
-            <artifactId>aws-common</artifactId>
-              <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-             <groupId>com.jamesmurty.utils.wso2</groupId>
-             <artifactId>java-xmlbuilder</artifactId>
-             <version>0.4.wso2v1</version>
-         </dependency>
-        <dependency>
-            <groupId>org.jclouds.api</groupId>
-            <artifactId>vcloud</artifactId>
-            <version>1.6.0-wso2v1</version>
-        </dependency>
-         <dependency>
-           <groupId>com.google.code.gson</groupId>
-           <artifactId>gson</artifactId>
-           <version>${gson2.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>com.google.guice.wso2</groupId>
-           <artifactId>guice</artifactId>
-           <version>${google.guice.wso2.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>com.google.guice.assistedinject.wso2</groupId>
-           <artifactId>guice-assistedinject</artifactId>
-           <version>${com.google.guice.assistedinject.wso2.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>com.sun.jersey</groupId>
-           <artifactId>jersey-core</artifactId>
-           <version>${sun.jersey.version}</version>
-         </dependency>
-         <dependency>
-          <groupId>net.oauth.core</groupId>
-          <artifactId>oauth</artifactId>
-          <version>20100527</version>
-         </dependency>
-         <dependency>
-           <groupId>commons-io.wso2</groupId>
-           <artifactId>commons-io</artifactId>
-           <version>2.0.0.wso2v1</version>
-         </dependency>
-         <dependency>
-           <groupId>rhino.wso2</groupId>
-           <artifactId>js</artifactId>
-           <version>1.7.0.R1-wso2v3</version>
-         </dependency>
-         <dependency>
-           <groupId>org.wso2.carbon</groupId>
-           <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
-           <version>2.1.1</version>
-         </dependency>
-         <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.databridge.agent.thrift</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.ntask.core</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-    </dependencies>
-    <properties>
-        <gson2.version>2.2</gson2.version>
-        <jclouds.version>1.5.0-beta.5</jclouds.version>
-        <jclouds.wso2.version>1.5.0-beta.5.wso2v1</jclouds.wso2.version>
-        <com.google.guice.assistedinject.wso2.version>3.0.wso2v1</com.google.guice.assistedinject.wso2.version>
-        <sun.jersey.version>1.12</sun.jersey.version>
-    </properties>
-</project>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java
deleted file mode 100644
index d6c722c..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java
+++ /dev/null
@@ -1,1263 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.axiom;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.XMLConstants;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.Source;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import javax.xml.validation.Validator;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.OMFactory;
-import org.apache.axiom.om.OMNode;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
-import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
-import org.apache.axiom.om.impl.dom.ElementImpl;
-import org.apache.axiom.om.xpath.AXIOMXPath;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jaxen.JaxenException;
-import org.w3c.dom.Element;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.exception.MalformedConfigurationFileException;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.AppType;
-import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.stratos.cloud.controller.util.PortMapping;
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-import org.wso2.securevault.SecretResolver;
-import org.wso2.securevault.SecretResolverFactory;
-
-/**
- * This class is parsing configuration files using Axiom Xpath.
- */
-public class AxiomXpathParser {
-
-	private static final Log log = LogFactory.getLog(AxiomXpathParser.class);
-	private OMElement documentElement;
-	private final File xmlSource;
-
-	public AxiomXpathParser(final File xmlFile) {
-		xmlSource = xmlFile;
-	}
-
-	/**
-     * @param cartridgeElement Cartridges section as a {@link String}
-     * @param aCartridge {@link Cartridge} instance.
-     * @param appTypesNodes nodes of App types.
-     */
-    private void getAppTypes(String cartridgeElementString, Cartridge aCartridge,
-                             List<?> appTypesNodes) {
-	    Object nodeObj;
-	    if (!appTypesNodes.isEmpty()) {
-	    	if ((nodeObj = appTypesNodes.get(0)) instanceof OMNode) {
-	    		OMNode appTypeNode = (OMNode) nodeObj;
-
-	    		if (appTypeNode.getType() == OMNode.ELEMENT_NODE) {
-
-	    			OMElement appTypesElt = (OMElement) appTypeNode;
-
-	    			for (Iterator<?> iterator =
-	    			                            appTypesElt.getChildrenWithName(new QName(
-	    			                                                                      CloudControllerConstants.APP_TYPE_ELEMENT)); iterator.hasNext();) {
-	    				OMElement appElt = (OMElement) iterator.next();
-
-	    				String name =
-	    				              appElt.getAttributeValue(new QName(
-	    				                                                 CloudControllerConstants.NAME_ATTR));
-	    				String appSpecificMapping =
-	    				                            appElt.getAttributeValue(new QName(
-	    				                                                               CloudControllerConstants.APP_SPECIFIC_MAPPING_ATTR));
-
-	    				AppType appType;
-
-	    				if (appSpecificMapping == null) {
-	    					appType = new AppType(name);
-	    				} else {
-	    					appType =
-	    					          new AppType(name,
-	    					                      Boolean.valueOf(appSpecificMapping));
-	    				}
-
-	    				aCartridge.addAppType(appType);
-	    			}
-
-	    		} else {
-	    			String msg =
-	    			             "Essential '" + CloudControllerConstants.APP_TYPE_ELEMENT +
-	    			                     "' element cannot" + " be found in " +
-	    			                     cartridgeElementString + " of " +
-	    			                     xmlSource;
-	    			handleException(msg);
-	    		}
-
-	    	}
-	    }
-    }
-
-	/**
-	 * @return a List of {@link Cartridge}s.
-	 */
-	public List<Cartridge> getCartridgesList() {
-
-		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
-
-		List<IaasProvider> iaasProviders = dataHolder.getIaasProviders();
-
-		if (iaasProviders == null) {
-			dataHolder.setIaasProviders((iaasProviders = new ArrayList<IaasProvider>()));
-		}
-
-		List<Cartridge> cartridges = new ArrayList<Cartridge>();
-
-		String xpath = CloudControllerConstants.CARTRIDGES_ELEMENT_XPATH;
-		
-		// cartridges can be found from this XPATH
-		List<?> cartridgeNodes = getMatchingNodes(xpath, documentElement);
-
-		if (cartridgeNodes == null || cartridgeNodes.isEmpty()) {
-			// or from this XPATH
-			xpath = CloudControllerConstants.CARTRIDGE_ELEMENT_XPATH;
-			cartridgeNodes = getMatchingNodes(xpath, documentElement);
-		}
-
-		if (cartridgeNodes == null || cartridgeNodes.isEmpty()) {
-			log.warn("No cartridge found in this configuration file : " + xmlSource.getPath());
-			return cartridges;
-		}
-
-		for (Object obj : cartridgeNodes) {
-
-			if (obj instanceof OMNode) {
-				OMNode cartridgeNode = (OMNode) obj;
-
-				if (cartridgeNode.getType() == OMNode.ELEMENT_NODE) {
-
-					OMElement cartridgeElement = (OMElement) cartridgeNode;
-
-					// retrieve Attributes of a Cartridge definition
-					String type = cartridgeElement.getAttributeValue(new QName(
-					                                                           CloudControllerConstants.TYPE_ATTR));
-					String host = cartridgeElement.getAttributeValue(new QName(
-					                                                           CloudControllerConstants.HOST_ATTR));
-					String provider = cartridgeElement.getAttributeValue(new QName(
-					                                                               CloudControllerConstants.PROVIDER_ATTR));
-					
-					String version =
-			                  cartridgeElement.getAttributeValue(new QName(
-			                                                               CloudControllerConstants.VERSION_ATTR));
-
-					boolean multiTenant = Boolean.valueOf(cartridgeElement.getAttributeValue(new QName(
-							CloudControllerConstants.MULTI_TENANT_ATTR)));
-
-					Cartridge aCartridge;
-
-					if ((aCartridge = dataHolder.getCartridge(type)) == null) {
-
-						aCartridge = new Cartridge(type, host, provider, version, multiTenant);
-					}
-					
-					// read displayName
-					Iterator<?> itName =
-					                 cartridgeElement.getChildrenWithName(new QName(
-					                                                                CloudControllerConstants.DISPLAY_NAME_ELEMENT));
-
-					if (itName.hasNext()) {
-						OMElement name = (OMElement) itName.next();
-
-						aCartridge.setDisplayName(name.getText());
-					}
-					
-					// read description
-					Iterator<?> it =
-					                 cartridgeElement.getChildrenWithName(new QName(
-					                                                                CloudControllerConstants.DESCRIPTION_ELEMENT));
-
-					if (it.hasNext()) {
-						OMElement desc = (OMElement) it.next();
-
-						aCartridge.setDescription(desc.getText());
-					}
-
-					// load properties of this cartridge
-					loadProperties(cartridgeElement, aCartridge.getProperties());
-
-					// retrieve the list of IaaS providers
-					List<?> iaasProviderNodes = getMatchingNodes(xpath + CloudControllerConstants.IAAS_PROVIDER_ELEMENT_XPATH,
-					                                             cartridgeElement);
-
-					getIaasProviders(iaasProviders, cartridgeElement.toString(), aCartridge, iaasProviderNodes);
-
-					// load dirs
-					List<?> deploymentNodes = getMatchingNodes(xpath + CloudControllerConstants.DEPLOYMENT_ELEMENT_XPATH,
-					                                           cartridgeElement);
-                    setDeploymentDirs(cartridgeElement.toString(), aCartridge, deploymentNodes);
-
-					// load port mappings
-					List<?> portMappingNodes =
-					                           getMatchingNodes(xpath +
-					                                                    CloudControllerConstants.PORT_MAPPING_ELEMENT_XPATH,
-					                                            cartridgeElement);
-					getPortMappings(cartridgeElement.toString(), aCartridge, portMappingNodes);
-
-					// load appTypes
-					List<?> appTypesNodes =
-					                        getMatchingNodes(xpath +
-					                                                 CloudControllerConstants.APP_TYPES_ELEMENT_XPATH,
-					                                         cartridgeElement);
-					getAppTypes(cartridgeElement.toString(), aCartridge, appTypesNodes);
-
-					cartridges.add(aCartridge);
-
-					if (dataHolder.getCartridge(type) == null) {
-						dataHolder.addCartridge(aCartridge);
-					}
-				}
-			}
-		}
-
-		return cartridges;
-
-	}
-
-	/**
-     * @param iaasProviders
-     * @param cartridgeElementString
-     * @param aCartridge
-     * @param iaasProviderNodes
-     */
-    private void getIaasProviders(List<IaasProvider> iaasProviders,
-                                  String cartridgeElementString, Cartridge aCartridge,
-                                  List<?> iaasProviderNodes) {
-	    for (Object nodeObj : iaasProviderNodes) {
-	    	if (nodeObj instanceof OMNode) {
-	    		OMNode iaasProviderNode = (OMNode) nodeObj;
-
-	    		if (iaasProviderNode.getType() == OMNode.ELEMENT_NODE) {
-
-	    			OMElement iaasElt = (OMElement) iaasProviderNode;
-
-	    			// add the IaasProvider to this cartridge
-	    			aCartridge.addIaasProvider(getIaasProvider(iaasElt, iaasProviders));
-
-	    		} else {
-	    			String msg =
-	    			             "Essential '" +
-	    			                     CloudControllerConstants.IAAS_PROVIDER_ELEMENT +
-	    			                     "' element cannot" + " be found in " +
-	    			                     cartridgeElementString + " of " +
-	    			                     xmlSource;
-	    			handleException(msg);
-	    		}
-
-	    	}
-	    }
-    }
-
-	private Element getDOMElement(final OMElement omElement) {
-
-		// Get the StAX reader from the created element
-		XMLStreamReader llomReader = omElement.getXMLStreamReader();
-
-		// Create the DOOM OMFactory
-		OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
-
-		// Create the new builder
-		StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
-
-		// Get the document element
-		OMElement newElem = doomBuilder.getDocumentElement();
-
-		return newElem instanceof Element ? (Element) newElem : null;
-	}
-
-	private OMElement getElement(final Object obj) {
-		OMNode node;
-		if ((obj instanceof OMNode) && (node = (OMNode) obj).getType() == OMNode.ELEMENT_NODE) {
-
-			OMElement element = (OMElement) node;
-
-			return element;
-
-		}
-
-		return null;
-	}
-
-	private OMElement getElement(final OMElement rootElt, final String eltStr, final String xpath) {
-		List<?> nodes = getMatchingNodes(xpath, rootElt);
-		neglectingWarn(eltStr, nodes.size());
-		OMElement element = getElement(nodes.get(0));
-		return element;
-	}
-
-	private OMElement getFirstChildElement(final OMElement root, final String childName) {
-		Iterator<?> it = root.getChildrenWithName(new QName(childName));
-		if (it.hasNext()) {
-			return (OMElement) it.next();
-		}
-
-		return null;
-	}
-
-	/**
-	 * 
-	 * @param xpath
-	 *            XPATH expression to be read.
-	 * @param elt
-	 *            OMElement to be used for the search.
-	 * @return List matching OMNode list
-	 */
-	@SuppressWarnings("unchecked")
-	public OMNode getFirstMatchingNode(final String xpath, final OMElement elt) {
-
-		AXIOMXPath axiomXpath;
-		List<OMNode> nodeList = null;
-		try {
-			axiomXpath = new AXIOMXPath(xpath);
-			nodeList = axiomXpath.selectNodes(elt);
-		} catch (JaxenException e) {
-			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-
-		return nodeList != null ? nodeList.get(0) : null;
-	}
-
-	private IaasProvider getIaasProvider(final OMNode item, List<IaasProvider> iaases) {
-
-		IaasProvider iaas = null;
-
-		if (item.getType() == OMNode.ELEMENT_NODE) {
-
-			OMElement iaasElt = (OMElement) item;
-
-			if (iaases != null) {
-				// check whether this is a reference to a predefined IaaS.
-				for (IaasProvider iaasProvider : iaases) {
-					if (iaasProvider.getType()
-					                .equals(iaasElt.getAttribute(new QName(
-					                                                       CloudControllerConstants.TYPE_ATTR))
-					                               .getAttributeValue())) {
-						iaas = new IaasProvider(iaasProvider);
-						break;
-					}
-				}
-			}
-
-			if (iaas == null) {
-				iaas = new IaasProvider();
-			}
-
-			if (iaas.getType() == null) {
-				iaas.setType(iaasElt.getAttribute(new QName(CloudControllerConstants.TYPE_ATTR))
-				                    .getAttributeValue());
-			}
-
-			if ("".equals(iaas.getType())) {
-				String msg =
-				             "'" + CloudControllerConstants.IAAS_PROVIDER_ELEMENT + "' element's '" +
-				                     CloudControllerConstants.TYPE_ATTR +
-				                     "' attribute should be specified!";
-
-				handleException(msg);
-
-			}
-
-			// this is not mandatory
-			String name =
-			              (iaasElt.getAttribute(new QName(CloudControllerConstants.NAME_ATTR)) == null)
-			                                                                                     ? iaas.getName()
-			                                                                                     : iaasElt.getAttributeValue(new QName(
-			                                                                                                                           CloudControllerConstants.NAME_ATTR));
-
-			iaas.setName(name);
-
-			String xpath = CloudControllerConstants.IAAS_PROVIDER_ELEMENT_XPATH;
-
-			// load other elements
-			loadClassName(iaas, iaasElt);
-			loadMaxInstanceLimit(iaas, iaasElt);
-			loadProperties(iaasElt, iaas.getProperties());
-			loadTemplate(iaas, iaasElt);
-			loadScalingOrders(iaas, iaasElt);
-			loadProvider(iaas, iaasElt);
-			loadIdentity(iaas, iaasElt);
-			loadCredentials(iaas, iaasElt, xpath);
-		}
-
-		return iaas;
-	}
-
-	/**
-	 * 
-	 * @param xpath
-	 *            XPATH expression to be read.
-	 * @return List matching OMNode list
-	 */
-	@SuppressWarnings("unchecked")
-	public List<OMNode> getMatchingNodes(final String xpath) {
-
-		AXIOMXPath axiomXpath;
-		List<OMNode> nodeList = null;
-		try {
-			axiomXpath = new AXIOMXPath(xpath);
-			nodeList = axiomXpath.selectNodes(documentElement);
-		} catch (JaxenException e) {
-			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-
-		return nodeList;
-	}
-
-	/**
-	 * 
-	 * @param xpath
-	 *            XPATH expression to be read.
-	 * @param elt
-	 *            OMElement to be used for the search.
-	 * @return List matching OMNode list
-	 */
-	@SuppressWarnings("unchecked")
-	public List<OMNode> getMatchingNodes(final String xpath, final OMElement elt) {
-
-		AXIOMXPath axiomXpath;
-		List<OMNode> nodeList = null;
-		try {
-			axiomXpath = new AXIOMXPath(xpath);
-			nodeList = axiomXpath.selectNodes(elt);
-		} catch (JaxenException e) {
-			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-
-		return nodeList;
-	}
-
-	/**
-     * @param cartridgeElement Cartridges section as a {@link String}
-     * @param aCartridge {@link Cartridge} instance.
-     * @param portMappingNodes nodes of port mapping elements
-     */
-    private void getPortMappings(String cartridgeElementString, Cartridge aCartridge,
-                                 List<?> portMappingNodes) {
-	    Object nodeObj;
-	    if (!portMappingNodes.isEmpty()) {
-	    	if ((nodeObj = portMappingNodes.get(0)) instanceof OMNode) {
-	    		OMNode portMappingNode = (OMNode) nodeObj;
-
-	    		if (portMappingNode.getType() == OMNode.ELEMENT_NODE) {
-
-	    			OMElement portMappingElt = (OMElement) portMappingNode;
-
-	    			for (Iterator<?> iterator =
-	    			                            portMappingElt.getChildrenWithName(new QName(
-	    			                                                                         CloudControllerConstants.HTTP_ELEMENT)); iterator.hasNext();) {
-	    				OMElement httpElt = (OMElement) iterator.next();
-
-	    				String port =
-	    				              httpElt.getAttributeValue(new QName(
-	    				                                                  CloudControllerConstants.PORT_ATTR));
-	    				String proxyPort =
-	    				                   httpElt.getAttributeValue(new QName(
-	    				                                                       CloudControllerConstants.PROXY_PORT_ATTR));
-
-	    				PortMapping mapping =
-	    				                      new PortMapping(
-	    				                                      CloudControllerConstants.HTTP_ELEMENT,
-	    				                                      port, proxyPort);
-
-	    				aCartridge.addPortMapping(mapping);
-	    			}
-
-	    			for (Iterator<?> iterator =
-	    			                            portMappingElt.getChildrenWithName(new QName(
-	    			                                                                         CloudControllerConstants.HTTPS_ELEMENT)); iterator.hasNext();) {
-	    				OMElement httpsElt = (OMElement) iterator.next();
-
-	    				String port =
-	    				              httpsElt.getAttributeValue(new QName(
-	    				                                                   CloudControllerConstants.PORT_ATTR));
-	    				String proxyPort =
-	    				                   httpsElt.getAttributeValue(new QName(
-	    				                                                        CloudControllerConstants.PROXY_PORT_ATTR));
-
-	    				PortMapping mapping =
-	    				                      new PortMapping(
-	    				                                      CloudControllerConstants.HTTPS_ELEMENT,
-	    				                                      port, proxyPort);
-
-	    				aCartridge.addPortMapping(mapping);
-	    			}
-
-	    		} else {
-	    			String msg =
-	    			             "Essential '" +
-	    			                     CloudControllerConstants.PORT_MAPPING_ELEMENT +
-	    			                     "' element cannot" + " be found in " +
-	    			                     cartridgeElementString + " of " +
-	    			                     xmlSource;
-	    			handleException(msg);
-	    		}
-
-	    	}
-	    }
-    }
-
-	public List<ServiceContext> getServiceContexts() {
-
-		List<ServiceContext> serviceContextList = new ArrayList<ServiceContext>();
-
-		// services can be found from this XPATH
-		String xpath = CloudControllerConstants.SERVICES_ELEMENT_XPATH;
-		List<?> serviceNodes = getMatchingNodes(xpath, documentElement);
-
-		if (serviceNodes == null || serviceNodes.isEmpty()) {
-			// or from this XPATH
-			xpath = CloudControllerConstants.SERVICE_ELEMENT_XPATH;
-			serviceNodes = getMatchingNodes(xpath, documentElement);
-		}
-
-		if (serviceNodes == null || serviceNodes.isEmpty()) {
-			log.warn("No service found in this configuration file : " + xmlSource.getPath());
-			return serviceContextList;
-		}
-
-		for (Object obj : serviceNodes) {
-			ServiceContext serviceCtxt = new ServiceContext();
-
-			// set the definition file
-			serviceCtxt.setFile(xmlSource);
-			
-			if (obj instanceof OMNode) {
-				OMNode serviceNode = (OMNode) obj;
-
-				if (serviceNode.getType() == OMNode.ELEMENT_NODE) {
-
-					OMElement node = (OMElement) serviceNode;
-
-					if (node.getAttribute(new QName(CloudControllerConstants.SERVICE_DOMAIN_ATTR)) == null) {
-						String msg =
-						             "Essential '" + CloudControllerConstants.SERVICE_DOMAIN_ATTR + "' " +
-						                     "attribute of '" + CloudControllerConstants.SERVICE_ELEMENT +
-						                     "' element cannot be found in " + xmlSource;
-
-						handleException(msg);
-					}
-
-					// set domain name
-					serviceCtxt.setDomainName(node.getAttribute(new QName(
-					                                                      CloudControllerConstants.SERVICE_DOMAIN_ATTR))
-					                              .getAttributeValue());
-
-					// set sub domain
-					serviceCtxt.setSubDomainName(node.getAttribute(new QName(
-					                                                         CloudControllerConstants.SERVICE_SUB_DOMAIN_ATTR))
-					                                 .getAttributeValue());
-
-					// set tenant range
-					serviceCtxt.setTenantRange(node.getAttribute(new QName(
-					                                                       CloudControllerConstants.SERVICE_TENANT_RANGE_ATTR))
-					                               .getAttributeValue());
-
-					OMNode cartridgeNode =
-					                       getFirstMatchingNode(xpath +
-					                                                    CloudControllerConstants.CARTRIDGE_ELEMENT_XPATH,
-					                                            node);
-
-					if (cartridgeNode != null && cartridgeNode.getType() == OMNode.ELEMENT_NODE) {
-
-						OMElement cartridgeElt = (OMElement) cartridgeNode;
-
-						String type =
-								cartridgeElt.getAttribute(new QName(CloudControllerConstants.TYPE_ATTR))
-						                  .getAttributeValue();
-
-						if ("".equals(type)) {
-							String msg =
-							             "Essential '" + CloudControllerConstants.TYPE_ATTR + "' " +
-							                     " attribute of '" +
-							                     CloudControllerConstants.CARTRIDGE_ELEMENT + "' of '" +
-							                     CloudControllerConstants.SERVICE_ELEMENT +
-							                     "' element cannot be found in " + xmlSource;
-
-							handleException(msg);
-						}
-						
-						// set Cartridge type
-						serviceCtxt.setCartridgeType(type);
-
-					}
-					if (serviceCtxt.getCartridgeType() == null) {
-						String msg =
-						             "Essential '" + CloudControllerConstants.CARTRIDGE_ELEMENT +
-						                     "' element" + " has not specified in " + xmlSource;
-						handleException(msg);
-					}
-
-					// load payload
-					loadPayload(getMatchingNodes(xpath + CloudControllerConstants.PAYLOAD_ELEMENT_XPATH,
-					                             node), serviceCtxt);
-
-					// load host name
-					loadHostName(getMatchingNodes(xpath + CloudControllerConstants.HOST_ELEMENT_XPATH,
-					                              node), serviceCtxt);
-
-					// load properties
-					loadProperties(node, serviceCtxt.getProperties());
-
-				}
-			}
-
-			FasterLookUpDataHolder.getInstance().addServiceContext(serviceCtxt);
-			// add each domain specific template to list
-			serviceContextList.add(serviceCtxt);
-		}
-
-		return serviceContextList;
-
-	}
-
-	public File getXmlSource() {
-		return xmlSource;
-	}
-
-	private void handleException(final String msg) {
-		log.error(msg);
-		throw new MalformedConfigurationFileException(msg);
-	}
-
-	private void handleException(final String msg, final Exception e) {
-		log.error(msg, e);
-		throw new MalformedConfigurationFileException(msg, e);
-	}
-
-	private void loadClassName(final IaasProvider iaas, final OMElement iaasElt) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(
-		                                                       CloudControllerConstants.CLASS_NAME_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement classNameElt = (OMElement) it.next();
-			iaas.setClassName(classNameElt.getText());
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " +
-			         CloudControllerConstants.CLASS_NAME_ELEMENT + " elements!" +
-			         " Elements other than the first will be neglected.");
-		}
-
-		if (iaas.getClassName() == null) {
-			String msg =
-			             "Essential '" + CloudControllerConstants.CLASS_NAME_ELEMENT + "' element " +
-			                     "has not specified in " + xmlSource;
-			handleException(msg);
-		}
-
-	}
-
-	private void loadCredentials(final IaasProvider iaas, final OMElement iaasElt,
-	                             final String xpath) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(
-		                                                       CloudControllerConstants.CREDENTIAL_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement credentialElt = (OMElement) it.next();
-
-			// retrieve the value using secure vault
-			SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
-			String alias =
-			               credentialElt.getAttributeValue(new QName(
-			                                                         CloudControllerConstants.ALIAS_ATTRIBUTE));
-
-			// retrieve the secured password
-			if (secretResolver != null && secretResolver.isInitialized() &&
-			    secretResolver.isTokenProtected(alias)) {
-
-				iaas.setCredential(secretResolver.resolve(alias));
-
-			}
-
-			// if we still cannot find a value, we try to assign the value which
-			// is specified
-			// in the element, if any
-			if (iaas.getCredential() == null) {
-				log.warn("Unable to find a value for " + CloudControllerConstants.CREDENTIAL_ELEMENT +
-				         " element from Secure Vault." +
-				         "Hence we will try to assign the plain text value (if specified).");
-				iaas.setCredential(credentialElt.getText());
-			}
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " +
-			         CloudControllerConstants.CREDENTIAL_ELEMENT + " elements!" +
-			         " Elements other than the first will be neglected.");
-		}
-
-		if (iaas.getCredential() == null) {
-			String msg =
-			             "Essential '" + CloudControllerConstants.CREDENTIAL_ELEMENT + "' element" +
-			                     " has not specified in " + xmlSource;
-			handleException(msg);
-		}
-
-	}
-	
-	private void loadHostName(final List<OMNode> nodes, final ServiceContext serviceCtxt) {
-
-		if (nodes == null || nodes.isEmpty()) {
-			return;
-		}
-
-		// read host element
-		if (nodes.get(0).getType() == OMNode.ELEMENT_NODE) {
-
-			OMElement node = (OMElement) nodes.get(0);
-
-			if (node.getText() != null) {
-				serviceCtxt.setHostName(node.getText());
-			}
-
-		}
-	}
-
-	private void loadIdentity(final IaasProvider iaas, final OMElement iaasElt) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.IDENTITY_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement identityElt = (OMElement) it.next();
-
-			// retrieve the value using secure vault
-			SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
-			String alias =
-			               identityElt.getAttributeValue(new QName(
-			                                                       CloudControllerConstants.ALIAS_ATTRIBUTE));
-
-			// retrieve the secured password
-			if (secretResolver != null && secretResolver.isInitialized() &&
-			    secretResolver.isTokenProtected(alias)) {
-
-				iaas.setIdentity(secretResolver.resolve(alias));
-
-			}
-
-			// if we still cannot find a value, we try to assign the value which
-			// is specified
-			// in the element, if any
-			if (iaas.getIdentity() == null) {
-				log.warn("Unable to find a value for " + CloudControllerConstants.IDENTITY_ELEMENT +
-				         " element from Secure Vault." +
-				         "Hence we will try to assign the plain text value (if specified).");
-				iaas.setIdentity(identityElt.getText());
-			}
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.IDENTITY_ELEMENT +
-			         " elements!" + " Elements other than the first will be neglected.");
-		}
-
-		if (iaas.getIdentity() == null) {
-			String msg =
-			             "Essential '" + CloudControllerConstants.IDENTITY_ELEMENT + "' element" +
-			                     " has not specified in " + xmlSource;
-			handleException(msg);
-		}
-
-	}
-
-	private void loadMaxInstanceLimit(IaasProvider iaas, final OMElement iaasElt) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(
-		                                                       CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement maxInstanceLimitElt = (OMElement) it.next();
-
-			try {
-				iaas.setMaxInstanceLimit(Integer.parseInt(maxInstanceLimitElt.getText()));
-			} catch (NumberFormatException e) {
-				String msg =
-				             CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT +
-				                     " element contained" + " in " + xmlSource + "" +
-				                     " has a value which is not an Integer value.";
-				handleException(msg, e);
-			}
-
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " +
-			         CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT + " elements!" +
-			         " Elements other than the first will be neglected.");
-		}
-
-	}
-
-	private void loadPayload(final List<OMNode> nodes, final ServiceContext serviceCtxt) {
-
-		if (nodes == null || nodes.isEmpty()) {
-			return;
-		}
-
-		// read payload element
-		if (nodes.get(0).getType() == OMNode.ELEMENT_NODE) {
-
-			OMElement node = (OMElement) nodes.get(0);
-
-			if (node.getText() != null) {
-				byte[] payload = CloudControllerUtil.getBytesFromFile(node.getText());
-				serviceCtxt.setPayload(payload);
-
-			}
-
-		}
-
-	}
-
-	private void loadProperties(final OMElement iaasElt, final Map<String, String> propertyMap) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROPERTY_ELEMENT));
-
-		while (it.hasNext()) {
-			OMElement prop = (OMElement) it.next();
-
-			if (prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_NAME_ATTR)) == null ||
-			    prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_VALUE_ATTR)) == null) {
-
-				String msg =
-				             "Property element's, name and value attributes should be specified " +
-				                     "in " + xmlSource;
-
-				handleException(msg);
-			}
-
-			propertyMap.put(prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_NAME_ATTR))
-			                    .getAttributeValue(),
-			                prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_VALUE_ATTR))
-			                    .getAttributeValue());
-		}
-
-	}
-
-	private void loadProvider(final IaasProvider iaas, final OMElement iaasElt) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROVIDER_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement providerElt = (OMElement) it.next();
-			iaas.setProvider(providerElt.getText());
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.PROVIDER_ELEMENT +
-			         " elements!" + " Elements other than the first will be neglected.");
-		}
-
-		if (iaas.getProvider() == null) {
-			String msg =
-			             "Essential '" + CloudControllerConstants.PROVIDER_ELEMENT + "' element " +
-			                     "has not specified in " + xmlSource;
-			handleException(msg);
-		}
-
-	}
-
-	private void loadScalingOrders(final IaasProvider iaas, final OMElement iaasElt) {
-		// set scale up order
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(
-		                                                       CloudControllerConstants.SCALE_UP_ORDER_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement scaleUpOrderElt = (OMElement) it.next();
-
-			try {
-				iaas.setScaleUpOrder(Integer.parseInt(scaleUpOrderElt.getText()));
-			} catch (NumberFormatException e) {
-				String msg =
-				             CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + " element contained" +
-				                     " in " + xmlSource + "" +
-				                     " has a value which is not an Integer value.";
-				handleException(msg, e);
-			}
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " +
-			         CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + " elements!" +
-			         " Elements other than the first will be neglected.");
-		}
-
-		if (iaas.getScaleUpOrder() == -1) {
-			String msg =
-			             "Essential '" + CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + "' element" +
-			                     " has not specified in " + xmlSource;
-			handleException(msg);
-		}
-
-		// set scale down order
-		it = iaasElt.getChildrenWithName(new QName(CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement scaleDownElt = (OMElement) it.next();
-
-			try {
-				iaas.setScaleDownOrder(Integer.parseInt(scaleDownElt.getText()));
-			} catch (NumberFormatException e) {
-				String msg =
-				             CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + " element contained" +
-				                     " in " + xmlSource + "" +
-				                     " has a value which is not an Integer value.";
-				handleException(msg, e);
-			}
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " +
-			         CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + " elements!" +
-			         " Elements other than the first will be neglected.");
-		}
-
-		if (iaas.getScaleDownOrder() == -1) {
-			String msg =
-			             "Essential '" + CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + "' element" +
-			                     " has not specified in " + xmlSource;
-			handleException(msg);
-		}
-
-	}
-
-	private void loadTemplate(final IaasProvider iaas, final OMElement iaasElt) {
-
-		Iterator<?> it =
-		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.IMAGE_ID_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement imageElt = (OMElement) it.next();
-			iaas.setImage(imageElt.getText());
-		}
-
-		if (it.hasNext()) {
-			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.IMAGE_ID_ELEMENT +
-			         " elements!" + " Elements other than the first will be neglected.");
-		}
-
-	}
-
-	private void neglectingWarn(final String elt, final int size) {
-		if (size > 1) {
-			log.warn(xmlSource + " contains more than one " + elt + " elements!" +
-			         " Elements other than the first will be neglected.");
-		}
-	}
-
-	public void parse() {
-
-		if (xmlSource.exists()) {
-			try {
-				documentElement = new StAXOMBuilder(xmlSource.getPath()).getDocumentElement();
-
-			} catch (Exception ex) {
-				String msg = "Error occurred when parsing the " + xmlSource.getPath() + ".";
-				handleException(msg, ex);
-			}
-		} else {
-			String msg = "Configuration file cannot be found : " + xmlSource.getPath();
-			handleException(msg);
-		}
-	}
-
-	private void plainTextWarn(final String elt) {
-		log.warn("Unable to find a value for " + elt + " element from Secure Vault." +
-		         "Hence we will try to assign the plain text value (if specified).");
-	}
-
-	private String resolveSecret(final OMElement elt) {
-		// retrieve the value using secure vault
-		SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
-
-		String alias = elt.getAttributeValue(new QName(CloudControllerConstants.ALIAS_ATTRIBUTE));
-
-		// retrieve the secured password
-		if (secretResolver != null && secretResolver.isInitialized() &&
-		    secretResolver.isTokenProtected(alias)) {
-
-			return secretResolver.resolve(alias);
-
-		}
-
-		return null;
-	}
-
-	public void setDataPublisherRelatedData() {
-
-		String eltStr = CloudControllerConstants.DATA_PUBLISHER_ELEMENT;
-		// get dataPublisher element
-		OMElement element =
-		                    getElement(documentElement, eltStr,
-		                               CloudControllerConstants.DATA_PUBLISHER_XPATH);
-
-		if (element == null) {
-			return;
-		}
-
-		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
-		// get enable attribute
-		boolean isEnable =
-		                   Boolean.parseBoolean(element.getAttributeValue(new QName(
-		                                                                            CloudControllerConstants.ENABLE_ATTR)));
-		dataHolder.setEnableBAMDataPublisher(isEnable);
-
-		if (isEnable) {
-			// get bam server info
-			OMElement childElement =
-			                         getFirstChildElement(element,
-			                                              CloudControllerConstants.BAM_SERVER_ELEMENT);
-			OMElement elt;
-
-			if (childElement != null) {
-				// set bam user name
-				elt =
-				      getFirstChildElement(childElement,
-				                           CloudControllerConstants.BAM_SERVER_ADMIN_USERNAME_ELEMENT);
-				if (elt != null) {
-					dataHolder.setBamUsername(elt.getText());
-				}
-				// set bam password
-				elt =
-				      getFirstChildElement(childElement,
-				                           CloudControllerConstants.BAM_SERVER_ADMIN_PASSWORD_ELEMENT);
-				if (elt != null) {
-					String password = resolveSecret(elt);
-					if (password == null) {
-						plainTextWarn(CloudControllerConstants.BAM_SERVER_ADMIN_PASSWORD_ELEMENT);
-						password = elt.getText();
-					}
-
-					if (password != null) {
-						dataHolder.setBamPassword(password);
-					}
-				}
-			}
-
-			// set cron
-			childElement = getFirstChildElement(element, CloudControllerConstants.CRON_ELEMENT);
-			if (childElement != null) {
-				dataHolder.setDataPublisherCron(childElement.getText());
-			}
-
-			// set cassandra info
-			childElement = getFirstChildElement(element, CloudControllerConstants.CASSANDRA_INFO_ELEMENT);
-
-			if (childElement != null) {
-				// set connection url
-				elt = getFirstChildElement(childElement, CloudControllerConstants.CONNECTION_URL_ELEMENT);
-				if (elt != null) {
-					dataHolder.setCassandraConnUrl(elt.getText());
-				}
-
-				// set user name
-				elt = getFirstChildElement(childElement, CloudControllerConstants.USER_NAME_ELEMENT);
-				if (elt != null) {
-					dataHolder.setCassandraUser(elt.getText());
-				}
-				// set password
-				elt = getFirstChildElement(childElement, CloudControllerConstants.PASSWORD_ELEMENT);
-				if (elt != null) {
-					String password = resolveSecret(elt);
-					if (password == null) {
-						plainTextWarn(CloudControllerConstants.PASSWORD_ELEMENT);
-						password = elt.getText();
-					}
-
-					if (password != null) {
-						dataHolder.setCassandraPassword(password);
-					}
-				}
-			}
-
-		}
-
-	}
-
-	/**
-     * @param cartridgeElement Cartridges section as a {@link String}
-     * @param aCartridge {@link Cartridge} instance.
-     * @param deploymentNodes list of deployment directory nodes
-     */
-    private void setDeploymentDirs(String cartridgeElementString, Cartridge aCartridge,
-                                   List<?> deploymentNodes) {
-	    Object nodeObj;
-	    if ((nodeObj = deploymentNodes.get(0)) instanceof OMNode) {
-	    	OMNode deploymentNode = (OMNode) nodeObj;
-
-	    	if (deploymentNode.getType() == OMNode.ELEMENT_NODE) {
-
-	    		OMElement deployElt = (OMElement) deploymentNode;
-
-	    		if (deployElt.getAttributeValue(new QName(
-	    		                                          CloudControllerConstants.BASE_DIR_ATTR)) != null) {
-
-	    			aCartridge.setBaseDir(deployElt.getAttributeValue(new QName(
-	    			                                                            CloudControllerConstants.BASE_DIR_ATTR)));
-	    		}
-
-	    		for (Iterator<?> iterator =
-	    		                            deployElt.getChildrenWithName(new QName(
-	    		                                                                    CloudControllerConstants.DIRECTORY_ELEMENT)); iterator.hasNext();) {
-	    			OMElement dir = (OMElement) iterator.next();
-	    			aCartridge.addDeploymentDir(dir.getText());
-	    		}
-
-	    	} else {
-	    		String msg =
-	    		             "Essential '" + CloudControllerConstants.DEPLOYMENT_ELEMENT +
-	    		                     "' element cannot" + " be found in " +
-	    		                     cartridgeElementString + " of " + xmlSource;
-	    		handleException(msg);
-	    	}
-
-	    }
-    }
-
-	public void setIaasProvidersList() {
-
-		List<IaasProvider> iaasProviders = FasterLookUpDataHolder.getInstance().getIaasProviders();
-
-		if (iaasProviders == null) {
-			FasterLookUpDataHolder.getInstance()
-			                      .setIaasProviders((iaasProviders = new ArrayList<IaasProvider>()));
-		}
-
-		List<OMNode> nodeList = getMatchingNodes(CloudControllerConstants.IAAS_PROVIDER_XPATH);
-
-		// this is a valid scenario. User can have 0..1 iaas provider elements
-		// in cloud-controller xml.
-		if (nodeList == null || nodeList.isEmpty()) {
-			return;
-		}
-
-		for (OMNode node : nodeList) {
-			iaasProviders.add(getIaasProvider(node, iaasProviders));
-		}
-
-	}
-
-
-	public void setTopologySyncRelatedData() {
-
-		String eltStr = CloudControllerConstants.TOPOLOGY_SYNC_ELEMENT;
-		// get topologySync element
-		OMElement element =
-		                    getElement(documentElement, eltStr,
-		                               CloudControllerConstants.TOPOLOGY_SYNC_XPATH);
-
-		if (element == null) {
-			return;
-		}
-
-		// get enable attribute
-		boolean isEnable =
-		                   Boolean.parseBoolean(element.getAttributeValue(new QName(
-		                                                                            CloudControllerConstants.ENABLE_ATTR)));
-
-		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
-		dataHolder.setEnableTopologySync(isEnable);
-
-		if (isEnable) {
-			// get MB server info
-			OMElement childElement =
-			                         getFirstChildElement(element,
-			                                              CloudControllerConstants.MB_SERVER_ELEMENT);
-
-			if (childElement != null) {
-				// set MB server IP
-				dataHolder.setMBServerUrl(childElement.getText());
-			}
-
-			// set cron
-			childElement = getFirstChildElement(element, CloudControllerConstants.CRON_ELEMENT);
-			if (childElement != null) {
-				dataHolder.setTopologySynchronizerCron(childElement.getText());
-			}
-
-		}
-
-	}
-
-	public boolean validate(final File schemaFile) throws Exception {
-		validate(documentElement, schemaFile);
-		return true;
-	}
-
-	public void validate(final OMElement omElement, final File schemaFile) throws Exception {
-
-		Element sourceElement;
-
-		// if the OMElement is created using DOM implementation use it
-		if (omElement instanceof ElementImpl) {
-			sourceElement = (Element) omElement;
-		} else { // else convert from llom to dom
-			sourceElement = getDOMElement(omElement);
-		}
-
-		// Create a SchemaFactory capable of understanding WXS schemas.
-
-		// Load a WXS schema, represented by a Schema instance.
-		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-		Source source = new StreamSource(schemaFile);
-
-		// Create a Validator object, which can be used to validate
-		// an instance document.
-		Schema schema = factory.newSchema(source);
-		Validator validator = schema.newValidator();
-
-		// Validate the DOM tree.
-		validator.validate(new DOMSource(sourceElement));
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java
deleted file mode 100644
index 43baf76..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.concurrent;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-/**
- * This class can be used to create a thread pool, and hand over new jobs to the pool.
- */
-public class ThreadExecutor {
-    private ExecutorService executor;
-
-    public ThreadExecutor(int poolSize) {
-        executor = Executors.newFixedThreadPool(poolSize);
-    }
-    
-    public void execute(Runnable job){
-        executor.execute(job);
-    }
-    
-    public void executeAll(Runnable[] jobs){
-        for (Runnable job : jobs) {
-            
-            executor.execute(job);
-        }
-    }
-    
-    public void shutdown() {
-        // This will make the executor accept no new threads
-        // and finish all existing threads in the queue
-        executor.shutdown();
-        // Wait until all threads are finished
-        while (!executor.isTerminated()) {}
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java
deleted file mode 100644
index 46f5261..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.consumers;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.BlockingQueue;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.common.conf.structure.Node;
-import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-
-/**
- * This class is responsible for generating the service topology and
- * publishing it to a topic.
- */
-public class TopologyBuilder implements Runnable {
-
-    private BlockingQueue<List<ServiceContext>> sharedQueue;
-	private static File topologyFile, backup;
-	private static final Log log = LogFactory.getLog(TopologyBuilder.class);
-	private static DeclarativeServiceReferenceHolder data = DeclarativeServiceReferenceHolder.getInstance();
-	
-	public TopologyBuilder(BlockingQueue<List<ServiceContext>> queue){
-		
-		sharedQueue = queue;
-		topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
-		backup = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH+".back");
-		
-	}
-	
-	@Override
-	public void run() {
-
-		while(true){
-            try {
-            	Object obj = sharedQueue.take();
-            	boolean isAdded = false;
-            	
-            	if(obj instanceof List<?>){
-            		@SuppressWarnings("unchecked")
-                    List<ServiceContext> ctxts = (List<ServiceContext>) obj;
-            		
-            		for (ServiceContext serviceContext : ctxts) {
-
-            			Node newNode = serviceContext.toNode();
-            			
-            			if(!topologyFile.exists()){
-            				FileUtils.writeStringToFile(topologyFile, "services {\n}");
-            			}
-            			
-            			String currentContent = FileUtils.readFileToString(topologyFile);
-            			Node currentNode = NodeBuilder.buildNode(currentContent);
-                   			
-            			for (Node aNode : currentNode.getChildNodes()) {
-            				// similar service element is present
-	                        if(aNode.getName().equals(newNode.getName())){
-	                        	// hence, we should not override, but append
-	                        	Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
-	                        	
-	                        	if(domainsNode == null){
-	                        		// existing node is useless
-	                        		currentNode.removeChildNode(aNode.getName());
-	                        		currentNode.appendChild(newNode);
-	                        		break;
-	                        	}
-	                        	
-	                        	// append the new node/s
-	                        	for (Node serNode : newNode.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
-	                                
-	                        		for (Node currentSerNode : domainsNode.getChildNodes()) {
-	                                    String prop = Constants.SUB_DOMAIN_ELEMENT;
-	                        			if(serNode.getName().equals(currentSerNode.getName()) &&
-	                        					serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
-	                        				// if domain and sub domain, are not unique, we shouldn't append, but override
-	                        				domainsNode.removeChildNode(currentSerNode.getName());
-	                        				break;
-	                        			}
-                                    }
-	                        		
-	                        		domainsNode.appendChild(serNode);
-                                }
-	                        	isAdded = true;
-	                        	break;
-	                        }
-                        }
-            			
-						if (!isAdded) {
-							currentNode.appendChild(newNode);
-						}
-						
-            			if (topologyFile.exists()) {
-            				backup.delete();
-            				topologyFile.renameTo(backup);
-            			}
-            			
-            			// overwrite the topology file
-            			FileUtils.writeStringToFile(topologyFile, currentNode.toString());
-            			
-            			// publish to the topic - to sync immediately
-            	        data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME, currentNode.toString());
-
-                    }
-            	}
-                
-            } catch (InterruptedException ignore) {
-            } catch (IOException e) {
-            	log.error(e.getMessage(), e);
-            	throw new CloudControllerException(e.getMessage(), e);
-            }
-        }
-
-	}
-	
-	public static void removeTopologyAndPublish(ServiceContext serviceContext){
-	    
-	    Node currentNodeToBeRemoved = null;
-	    Node nodeToBeRemoved = serviceContext.toNode();
-        
-        if(!topologyFile.exists()){
-            return;
-        }
-        try{
-        String currentContent = FileUtils.readFileToString(topologyFile);
-        Node currentNode = NodeBuilder.buildNode(currentContent);
-            
-        for (Node aNode : currentNode.getChildNodes()) {
-            // similar service element is present
-            if(aNode.getName().equals(nodeToBeRemoved.getName())){
-                // let's check whether the domain node exists
-                
-                Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
-                
-                if(domainsNode == null){
-                    continue;
-                }
-                
-                for (Node serNode : nodeToBeRemoved.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
-                    
-                    for (Node currentSerNode : domainsNode.getChildNodes()) {
-                        String prop = Constants.SUB_DOMAIN_ELEMENT;
-                        if(serNode.getName().equals(currentSerNode.getName()) &&
-                                serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
-                            // if domain and sub domain, are matching, we should remove the node.
-                            domainsNode.removeChildNode(currentSerNode.getName());
-                            if(domainsNode.getChildNodes().size() == 0){
-                                // if no cluster definitions remain, we shouldn't keep the node
-                                currentNodeToBeRemoved = aNode;
-                            }
-                            break;
-                        }
-                    }
-                    
-                }
-                
-            }
-        }
-        
-        if(currentNodeToBeRemoved != null){
-            // remove the node with empty clusters
-            currentNode.removeChildNode(currentNodeToBeRemoved);
-        }
-        
-        if (topologyFile.exists()) {
-            backup.delete();
-            topologyFile.renameTo(backup);
-        }
-        
-        // overwrite the topology file
-        FileUtils.writeStringToFile(topologyFile, currentNode.toString());
-        
-        // publish to the topic - to sync immediately
-        data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME, currentNode.toString());
-        
-        } catch (IOException e) {
-            log.error(e.getMessage(), e);
-            throw new CloudControllerException(e.getMessage(), e);
-        }
-
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java
deleted file mode 100644
index 9881e5f..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.deployers;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.deployment.AbstractDeployer;
-import org.apache.axis2.deployment.DeploymentException;
-import org.apache.axis2.deployment.repository.util.DeploymentFileData;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
-import org.wso2.carbon.stratos.cloud.controller.concurrent.ThreadExecutor;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * All the {@link Cartridge}s will get deployed / undeployed / updated via this class. 
- */
-public class CartridgeDeployer extends AbstractDeployer{
-    
-    private static final Log log = LogFactory.getLog(CartridgeDeployer.class);
-    
-    private FasterLookUpDataHolder serviceContextLookUpStructure;
-    private Map<String, List<Cartridge>> fileToCartridgeListMap;
-    private File cartridgesSchema, cartridgeSchema;
-
-    public void init(ConfigurationContext arg0) {
-        fileToCartridgeListMap = new ConcurrentHashMap<String, List<Cartridge>>();
-        String etcDir = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator;
-        cartridgesSchema = new File(etcDir+"cartridges.xsd");
-        cartridgeSchema = new File(etcDir+"cartridge.xsd");
-    }
-
-    public void setDirectory(String arg0) {
-        // component xml handles this
-    }
-
-    public void setExtension(String arg0) {
-        // component xml handles this
-    }
-    
-    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
-        
-        log.debug("Started to deploy the deployment artifact: "+deploymentFileData.getFile());
-        
-        AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
-        parser.parse();
-
-        try {
-        	// validate
-            validateCartridge(parser);
-            
-			// deploy - grab cartridges
-			List<Cartridge> cartridges = parser.getCartridgesList();
-
-			ThreadExecutor exec = new ThreadExecutor(3);
-			// create Jclouds objects, for each IaaS
-			for (Cartridge cartridge : cartridges) {
-				// jclouds object building is time consuming, hence I use Java executor framework
-				exec.execute(new JcloudsObjectBuilder(cartridge, deploymentFileData));
-			}
-			exec.shutdown();
-			// update map
-			fileToCartridgeListMap.put(deploymentFileData.getAbsolutePath(),
-			                           new ArrayList<Cartridge>(cartridges));
-
-			log.info("Successfully deployed the Cartridge definition specified at "+deploymentFileData.getAbsolutePath());
-			
-		} catch (Exception e) {
-			String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
-            // back up the file
-            File f = deploymentFileData.getFile();
-            f.renameTo(new File(deploymentFileData.getAbsolutePath()+".back"));
-            log.error(msg, e);
-            throw new DeploymentException(msg, e);
-		} 
-        
-        
-    }
-    
-    private void validateCartridge(AxiomXpathParser parser) throws Exception {
-        boolean validated = false;
-        Exception firstException = null;
-
-        try{
-            // first try to validate using cartridges schema
-            parser.validate(cartridgesSchema);
-            validated = true;
-            
-        }catch (Exception e) {
-            firstException = e;
-        }
-        
-        if(!validated){
-            try{
-                // Now try to validate using cartridge schema
-                parser.validate(cartridgeSchema);
-                validated = true;
-                log.debug("Cartridge validation was successful.");
-                
-            }catch (Exception e) {
-                String msg = "Cartridge XML validation failed. Invalid Cartridge XML: "+parser.getXmlSource().getAbsolutePath();
-                log.error(msg, firstException);
-                throw firstException;
-            }
-        }
-        
-        
-    }
-
-    public void undeploy(String file) throws DeploymentException {
-        
-    	serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
-    	
-        // grab the entry from Map
-        if(fileToCartridgeListMap.containsKey(file)){
-            // remove 'em
-            serviceContextLookUpStructure.removeCartridges(fileToCartridgeListMap.get(file));
-            
-            log.info("Successfully undeployed the Cartridge definition specified at "+file);
-        }
-        
-    }
-    
-    private void handleException(String msg, Exception e) {
-        log.fatal(msg, e);
-        throw new CloudControllerException(msg, e);
-    }
-    
-    /**
-     * JcloudsObjectBuilder job
-     *
-     */
-    class JcloudsObjectBuilder implements Runnable{
-    	
-    	private Cartridge cartridge;
-    	private DeploymentFileData file;
-
-    	public JcloudsObjectBuilder (Cartridge cartridge, DeploymentFileData file){
-    		this.cartridge = cartridge;
-    		this.file = file;
-    	}
-    	
-		@Override
-        public void run() {
-
-			for (IaasProvider iaasProvider : cartridge.getIaases()) {
-				try {
-					Iaas iaas = (Iaas) Class.forName(iaasProvider.getClassName()).newInstance();
-					iaas.buildComputeServiceAndTemplate(iaasProvider);
-					iaasProvider.setIaas(iaas);
-					
-				} catch (Exception e) {
-					rename();
-					handleException(e.getMessage(), e);
-				}
-			}
-			
-        }
-		
-		private void rename(){
-			// back up the file
-            File f = file.getFile();
-            f.renameTo(new File(file.getAbsolutePath()+".back"));
-		}
-    	
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java
deleted file mode 100644
index 1f9dafc..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.deployers;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.deployment.AbstractDeployer;
-import org.apache.axis2.deployment.DeploymentException;
-import org.apache.axis2.deployment.repository.util.DeploymentFileData;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-
-/**
- * All the {@link IaasProvider}s will get deployed / undeployed / updated via this class. 
- */
-public class CloudControllerDeployer extends AbstractDeployer{
-    
-    private static final Log log = LogFactory.getLog(CloudControllerDeployer.class);
-    private static final String FILE_NAME = "cloud-controller";
-    private Map<String, List<IaasProvider>> fileToIaasProviderListMap;
-
-    @Override
-    public void init(ConfigurationContext arg0) {
-    	fileToIaasProviderListMap = new ConcurrentHashMap<String, List<IaasProvider>>();
-    }
-
-    @Override
-    public void setDirectory(String arg0) {
-        // component xml handles this
-        
-    }
-
-    @Override
-    public void setExtension(String arg0) {
-        // component xml handles this
-    }
-    
-    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
-        
-        log.debug("Started to deploy the deployment artifact: "+deploymentFileData.getFile());
-        
-        // since cloud-controller.xml resides in repository/conf
-		if (deploymentFileData.getName().contains(FILE_NAME)) {
-
-			AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
-
-			// parse the file
-			parser.parse();
-
-			// deploy iaases
-			parser.setIaasProvidersList();
-			parser.setDataPublisherRelatedData();
-			parser.setTopologySyncRelatedData();
-
-			// update map
-			fileToIaasProviderListMap.put(deploymentFileData.getAbsolutePath(),
-			                              new ArrayList<IaasProvider>(
-			                                                          FasterLookUpDataHolder.getInstance()
-			                                                                                .getIaasProviders()));
-
-			log.info("Successfully deployed the cloud-controller XML file specified at " +
-			         deploymentFileData.getAbsolutePath());
-		}
-        
-    }
-    
-
-    public void undeploy(String file) throws DeploymentException {
-        
-        if (file.contains(FILE_NAME)) {
-            // reset
-            FasterLookUpDataHolder.getInstance().setSerializationDir("");
-            
-            // grab the entry from Map
-            if(fileToIaasProviderListMap.containsKey(file)){
-                // remove 'em
-                FasterLookUpDataHolder.getInstance().getIaasProviders().removeAll(fileToIaasProviderListMap.get(file));
-                
-                log.info("Successfully undeployed the cloud-controller XML file specified at "+file);
-            }
-            // only one cloud-controller file, hence delete 'em all
-//            FasterLookUpDataHolder.getInstance().setIaasProviders(new ArrayList<IaasProvider>());
-            
-        }
-        
-    }
-
-}


[03/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
deleted file mode 100644
index d5289e8..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
+++ /dev/null
@@ -1,1123 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.impl;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.ComputeMetadata;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.NodeMetadata.Status;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.internal.NodeMetadataImpl;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.ntask.common.TaskException;
-import org.wso2.carbon.ntask.core.TaskInfo;
-import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo;
-import org.wso2.carbon.ntask.core.TaskManager;
-import org.wso2.carbon.ntask.core.service.TaskService;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.stratos.cloud.controller.consumers.TopologyBuilder;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredCartridgeException;
-import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredServiceException;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
-import org.wso2.carbon.stratos.cloud.controller.persist.Deserializer;
-import org.wso2.carbon.stratos.cloud.controller.publisher.CartridgeInstanceDataPublisherTask;
-import org.wso2.carbon.stratos.cloud.controller.registry.RegistryManager;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.topic.TopologySynchronizerTask;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
-import org.wso2.carbon.stratos.cloud.controller.util.CartridgeInfo;
-import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasContext;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.stratos.cloud.controller.util.Properties;
-import org.wso2.carbon.stratos.cloud.controller.util.Property;
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-
-import com.google.common.collect.Lists;
-
-/**
- * Cloud Controller Service is responsible for starting up new server instances,
- * terminating already started instances, providing pending instance count etc.
- * 
- */
-public class CloudControllerServiceImpl implements CloudControllerService {
-
-	private static final Log log = LogFactory.getLog(CloudControllerServiceImpl.class);
-	private FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
-
-	public CloudControllerServiceImpl() {
-
-		// acquire serialized data from registry
-		acquireData();
-
-		// gets the task service
-		TaskService taskService =
-		                          DeclarativeServiceReferenceHolder.getInstance()
-		                                                               .getTaskService();
-
-		if (dataHolder.getEnableBAMDataPublisher()) {
-
-			// register and schedule, BAM data publisher task 
-			registerAndScheduleDataPublisherTask(taskService);
-		}
-
-		if (dataHolder.getEnableTopologySync()) {
-
-			// start the topology builder thread
-			startTopologyBuilder();
-
-			// register and schedule, topology synchronizer task
-			registerAndScheduleTopologySyncerTask(taskService);
-		}
-	}
-
-    private void registerAndScheduleTopologySyncerTask(TaskService taskService) {
-	    TaskInfo taskInfo;
-	    TaskManager tm = null;
-	    try {
-
-	    	if (!taskService.getRegisteredTaskTypes()
-	    	                .contains(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE)) {
-
-	    		// topology sync
-	    		taskService.registerTaskType(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE);
-
-	    		tm =
-	    		     taskService.getTaskManager(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE);
-
-	    		TriggerInfo triggerInfo =
-	    		                          new TriggerInfo(
-	    		                                          dataHolder.getTopologySynchronizerCron());
-	    		taskInfo =
-	    		           new TaskInfo(CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME,
-	    		                        TopologySynchronizerTask.class.getName(),
-	    		                        new HashMap<String, String>(), triggerInfo);
-	    		tm.registerTask(taskInfo);
-	    	}
-
-	    } catch (Exception e) {
-	    	String msg =
-	    	             "Error scheduling task: " +
-	    	                     CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME;
-	    	log.error(msg, e);
-	    	if (tm != null) {
-	    		try {
-	    			tm.deleteTask(CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME);
-	    		} catch (TaskException e1) {
-	    			log.error(e1);
-	    		}
-	    	}
-	    	throw new CloudControllerException(msg, e);
-	    }
-    }
-
-    private void startTopologyBuilder() {
-	    // initialize TopologyBuilder Consumer
-	    Thread topologyBuilder =
-	                              new Thread(
-	                                         new TopologyBuilder(
-	                                                             dataHolder.getSharedTopologyDiffQueue()));
-	    // start consumer
-	    topologyBuilder.start();
-    }
-
-    private TaskManager registerAndScheduleDataPublisherTask(TaskService taskService) {
-	    TaskInfo taskInfo;
-	    TaskManager tm = null;
-	    // initialize and schedule the data publisher task
-	    try {
-
-	    	if (!taskService.getRegisteredTaskTypes()
-	    	                .contains(CloudControllerConstants.DATA_PUB_TASK_TYPE)) {
-
-	    		taskService.registerTaskType(CloudControllerConstants.DATA_PUB_TASK_TYPE);
-
-	    		tm = taskService.getTaskManager(CloudControllerConstants.DATA_PUB_TASK_TYPE);
-
-	    		if (!tm.isTaskScheduled(CloudControllerConstants.DATA_PUB_TASK_NAME)) {
-
-	    			TriggerInfo triggerInfo =
-	    			                          new TriggerInfo(
-	    			                                          FasterLookUpDataHolder.getInstance()
-	    			                                                                .getDataPublisherCron());
-	    			taskInfo =
-	    			           new TaskInfo(CloudControllerConstants.DATA_PUB_TASK_NAME,
-	    			                        CartridgeInstanceDataPublisherTask.class.getName(),
-	    			                        new HashMap<String, String>(), triggerInfo);
-	    			tm.registerTask(taskInfo);
-
-	    			// Following code is currently not required, due to an issue in TS API.
-	    			// tm.scheduleTask(taskInfo.getName());
-	    		}
-	    	}
-
-	    } catch (Exception e) {
-	    	String msg =
-	    	             "Error scheduling task: " +
-	    	                     CloudControllerConstants.DATA_PUB_TASK_NAME;
-	    	log.error(msg, e);
-	    	if (tm != null) {
-	    		try {
-	    			tm.deleteTask(CloudControllerConstants.DATA_PUB_TASK_NAME);
-	    		} catch (TaskException e1) {
-	    			log.error(e1);
-	    		}
-	    	}
-	    	throw new CloudControllerException(msg, e);
-	    }
-	    return tm;
-    }
-
-	private void acquireData() {
-
-		Object obj = RegistryManager.getInstance().retrieve();
-		if (obj != null) {
-			try {
-				Object dataObj = Deserializer.deserializeFromByteArray((byte[]) obj);
-				if (dataObj instanceof FasterLookUpDataHolder) {
-					FasterLookUpDataHolder serializedObj = (FasterLookUpDataHolder) dataObj;
-					FasterLookUpDataHolder currentData = FasterLookUpDataHolder.getInstance();
-					
-					// assign necessary data
-					currentData.setNodeIdToServiceContextMap(serializedObj.getNodeIdToServiceContextMap());
-					
-					// traverse through current Service Contexts
-					for (ServiceContext ctxt : currentData.getServiceCtxtList()) {
-						// traverse through serialized Service Contexts
-	                    for (ServiceContext serializedCtxt : serializedObj.getServiceCtxtList()) {
-	                    	// if a matching Service Context found
-	                        if(ctxt.equals(serializedCtxt)){
-	                        	// persisted node ids of this Service Context
-	                        	List<Object> nodeIds = serializedObj.getNodeIdsOfServiceCtxt(serializedCtxt);
-	                        	for (Object nodeIdObj : nodeIds) {
-	                                String nodeId = (String) nodeIdObj;
-	                                
-	                                // assign persisted data
-	                                currentData.addNodeId(nodeId, ctxt);
-	                                
-                                }
-	                        	
-	                        	ctxt.setIaasContextMap(serializedCtxt.getIaasCtxts());
-	                        	appendToPublicIpProperty(serializedCtxt.getProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY), ctxt);
-	                        	
-	                        	// assign lastly used IaaS
-	                        	if(serializedCtxt.getCartridge() != null && serializedCtxt.getCartridge().getLastlyUsedIaas() != null){
-	                        		
-	                        		if(ctxt.getCartridge() == null){
-	                        			// load Cartridge
-	                        			ctxt.setCartridge(loadCartridge(ctxt.getCartridgeType(), ctxt.getPayload(), serializedObj.getCartridges()));
-	                        		}
-	                        		
-	                        		IaasProvider serializedIaas = serializedCtxt.getCartridge().getLastlyUsedIaas();
-	                        		ctxt.getCartridge().setLastlyUsedIaas(serializedIaas);
-	                        		
-	                        	}
-	                        }
-                        }
-                    }
-					
-					log.debug("Data is retrieved from registry.");
-				} else {
-					log.debug("No data is persisted in registry.");
-				}
-			} catch (Exception e) {
-
-				String msg =
-				             "Unable to acquire data from Registry. Hence, any historical data will not get reflected.";
-				log.warn(msg, e);
-			}
-
-		}
-	}
-
-	@Override
-	public String startInstance(String domainName, String subDomainName) {
-
-		ComputeService computeService;
-		Template template;
-		String ip = "";
-		final Lock lock = new ReentrantLock();
-
-		// check for sub domain
-		subDomainName = checkSubDomain(subDomainName);
-
-		log.info("Starting new instance of domain : " + domainName + " and sub domain : " +
-		         subDomainName);
-
-		// get the subjected ServiceContext
-		ServiceContext serviceCtxt =
-		                             FasterLookUpDataHolder.getInstance()
-		                                                   .getServiceContext(domainName,
-		                                                                      subDomainName);
-
-		if (serviceCtxt == null) {
-			String msg =
-			             "Not a registered service: domain - " + domainName + ", sub domain - " +
-			                     subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// load Cartridge
-		serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
-		                                       serviceCtxt.getPayload(),
-		                                       FasterLookUpDataHolder.getInstance().getCartridges()));
-
-		if (serviceCtxt.getCartridge() == null) {
-			String msg =
-			             "There's no registered Cartridge found. Domain - " + domainName +
-			                     ", sub domain - " + subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		if (serviceCtxt.getCartridge().getIaases().isEmpty()) {
-			String msg =
-			             "There's no registered IaaSes found for Cartridge type: " +
-			                     serviceCtxt.getCartridge().getType();
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// sort the IaasProviders according to scale up order
-		Collections.sort(serviceCtxt.getCartridge().getIaases(),
-		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_UP_SORT)));
-
-		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
-
-			IaasContext ctxt = null;
-			if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
-				ctxt = serviceCtxt.addIaasContext(iaas.getType());
-			}
-
-			if (iaas.getMaxInstanceLimit() > ctxt.getCurrentInstanceCount()) {
-				try {
-
-					iaas.getIaas().setDynamicPayload(iaas);
-
-					// get the ComputeService
-					computeService = iaas.getComputeService();
-
-					// corresponding Template
-					template = iaas.getTemplate();
-
-					if (template == null) {
-						String msg =
-						             "Failed to start an instance in " +
-						                     iaas.getType() +
-						                     ". Reason : Template is null. You have not specify a matching service " +
-						                     "element in the configuration file of Autoscaler.\n Hence, will try to " +
-						                     "start in another IaaS if available.";
-						log.error(msg);
-						continue;
-					}
-
-					// set instance name as the host name
-					// template.getOptions().userMetadata("Name",
-					// serviceCtxt.getHostName());
-					// template.getOptions().as(TemplateOptions.class).userMetadata("Name",
-					// serviceCtxt.getHostName());
-
-					// generate the group id from domain name and sub domain name.
-					// Should have lower-case ASCII letters, numbers, or dashes.
-					// Should have a length between 3-15
-					String str = domainName.concat("-" + subDomainName).substring(0, 10);
-					String group = str.replaceAll("[^a-z0-9-]", "");
-
-					NodeMetadata node;
-
-					// create and start a node
-					Set<? extends NodeMetadata> nodes =
-					                                    computeService.createNodesInGroup(group, 1,
-					                                                                      template);
-
-					node = nodes.iterator().next();
-
-					String autoAssignIpProp =
-					                          iaas.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
-
-					// acquire the lock
-					lock.tryLock();
-
-					try {
-						// reset ip
-						ip = "";
-						// default behavior is autoIpAssign=false
-						if (autoAssignIpProp == null ||
-						    (autoAssignIpProp != null && autoAssignIpProp.equals("false"))) {
-							// allocate an IP address - manual IP assigning mode
-							ip = iaas.getIaas().associateAddress(iaas, node);
-						}
-
-						if (ip.isEmpty() && node.getPublicAddresses() != null &&
-						    node.getPublicAddresses().iterator().hasNext()) {
-							ip = node.getPublicAddresses().iterator().next();
-						}
-
-						// if not public IP is assigned, we're using private IP
-						if (ip.isEmpty() && node.getPrivateAddresses() != null &&
-						    node.getPrivateAddresses().iterator().hasNext()) {
-							ip = node.getPrivateAddresses().iterator().next();
-						}
-
-						if (node.getId() == null) {
-							String msg =
-							             "Node id of the starting instance is null.\n" +
-							                     node.toString();
-							log.fatal(msg);
-							throw new CloudControllerException(msg);
-						}
-
-						// add node ID
-						ctxt.addNodeId(node.getId());
-						ctxt.addNodeToPublicIp(node.getId(), ip);
-
-						// to faster look up
-						FasterLookUpDataHolder.getInstance().addNodeId(node.getId(), serviceCtxt);
-
-						serviceCtxt.getCartridge().setLastlyUsedIaas(iaas);
-
-						// add this ip to the topology
-						appendToPublicIpProperty(ip, serviceCtxt);
-
-						ctxt.incrementCurrentInstanceCountByOne();
-						
-						// persist in registry
-						persist();
-
-						// trigger topology consumers
-						List<ServiceContext> list = new ArrayList<ServiceContext>();
-						list.add(serviceCtxt);
-						try {
-							dataHolder.getSharedTopologyDiffQueue().put(list);
-							
-							// publish data
-							CartridgeInstanceDataPublisherTask.publish();
-						} catch (InterruptedException ignore) {
-						}
-
-						if (log.isDebugEnabled()) {
-							log.debug("Node details: \n" + node.toString() + "\n***************\n");
-						}
-
-						log.info("Instance is successfully starting up in IaaS " + iaas.getType() +
-						         ".\tIP Address(public/private): " + ip + "\tNode Id: " +
-						         node.getId());
-
-						return ip;
-
-					} finally {
-						// release the lock
-						lock.unlock();
-					}
-
-				} catch (Exception e) {
-					log.warn("Failed to start an instance in " + iaas.getType() +
-					         ". Hence, will try to start in another IaaS if available.", e);
-					continue;
-				}
-			} else {
-				log.warn("Max instance limit is reached in the IaaS " + iaas.getType() +
-				          " : Max instance limit: " + iaas.getMaxInstanceLimit());
-			}
-
-		}
-
-		log.error("Failed to start an instance, in any available IaaS: " + domainName +
-		          " and sub domain : " + subDomainName);
-
-		return null;
-
-	}
-
-	/**
-	 * Appends this ip to the Service Context's {@link CloudControllerConstants#PUBLIC_IP_PROPERTY}
-     * @param ip
-     * @param serviceCtxt
-     */
-	private void appendToPublicIpProperty(String ip, ServiceContext serviceCtxt) {
-		String ipStr = serviceCtxt.getProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY);
-		if (ip != null && !"".equals(ip)) {
-			serviceCtxt.setProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY,
-			                        ("".equals(ipStr) ? ""
-			                                         : ipStr +
-			                                           CloudControllerConstants.ENTRY_SEPARATOR) +
-			                                ip);
-		}
-	}
-
-	/**
-     * Persist data in registry.
-     */
-    private void persist() {
-	    try {
-	        RegistryManager.getInstance().persist(FasterLookUpDataHolder.getInstance());
-	    } catch (RegistryException e) {
-
-	    	String msg = "Failed to persist the Cloud Controller data in registry. Further, transaction roll back also failed.";
-	    	log.fatal(msg);
-	    	throw new CloudControllerException(msg, e);
-	    }
-    }
-
-	private Cartridge loadCartridge(String cartridgeType, byte[] payload, List<Cartridge> cartridges) {
-
-		for (Cartridge cartridge : cartridges) {
-			if (cartridge.getType().equals(cartridgeType)) {
-				for (IaasProvider iaas : cartridge.getIaases()) {
-					iaas.setPayload(payload);
-				}
-				return cartridge;
-			}
-		}
-
-		return null;
-	}
-
-	@Override
-	public boolean terminateInstance(String domainName, String subDomainName) {
-
-		subDomainName = checkSubDomain(subDomainName);
-
-		log.info("Starting to terminate an instance of domain : " + domainName +
-		         " and sub domain : " + subDomainName);
-
-		ServiceContext serviceCtxt =
-		                             FasterLookUpDataHolder.getInstance()
-		                                                   .getServiceContext(domainName,
-		                                                                      subDomainName);
-
-		if (serviceCtxt == null) {
-			String msg =
-			             "Not a registered service: domain - " + domainName + ", sub domain - " +
-			                     subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// load Cartridge, if null
-		if (serviceCtxt.getCartridge() == null) {
-			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
-			                                       serviceCtxt.getPayload(),
-			                                       FasterLookUpDataHolder.getInstance()
-			                                                             .getCartridges()));
-		}
-		
-		// if still, Cartridge is null
-		if (serviceCtxt.getCartridge() == null) {
-			String msg =
-			             "There's no registered Cartridge found. Domain - " + domainName +
-			                     ", sub domain - " + subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// sort the IaasProviders according to scale down order
-		Collections.sort(serviceCtxt.getCartridge().getIaases(),
-		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
-
-		// traverse in scale down order
-		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
-
-			String msg =
-			             "Failed to terminate an instance in " + iaas.getType() +
-			                     ". Hence, will try to terminate an instance in another IaaS if possible.";
-
-			String nodeId = null;
-
-			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
-
-			// terminate the last instance first
-			for (String id : Lists.reverse(ctxt.getNodeIds())) {
-				if (id != null) {
-					nodeId = id;
-					break;
-				}
-			}
-
-			// if no matching node id can be found.
-			if (nodeId == null) {
-
-				log.warn(msg + " : Reason- No matching instance found for domain: " + domainName +
-				         " and sub domain: " + subDomainName + ".");
-				continue;
-			}
-
-			// terminate it!
-			terminate(iaas, ctxt, nodeId);
-			
-			// log information
-			logTermination(nodeId, ctxt, serviceCtxt);
-
-			return true;
-
-		}
-
-		log.info("Termination of an instance which is belong to domain '" + domainName +
-		         "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
-		         "running instance found in any available IaaS.");
-
-		return false;
-
-	}
-
-	@Override
-	public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
-
-		subDomainName = checkSubDomain(subDomainName);
-
-		log.info("Starting to terminate the last instance spawned, of domain : " + domainName +
-		         " and sub domain : " + subDomainName);
-
-		ServiceContext serviceCtxt =
-		                             FasterLookUpDataHolder.getInstance()
-		                                                   .getServiceContext(domainName,
-		                                                                      subDomainName);
-
-		if (serviceCtxt == null) {
-			String msg =
-			             "Not a registered service: domain - " + domainName + ", sub domain - " +
-			                     subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// load Cartridge, if null
-		if (serviceCtxt.getCartridge() == null) {
-			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
-			                                       serviceCtxt.getPayload(),
-			                                       FasterLookUpDataHolder.getInstance()
-			                                                             .getCartridges()));
-		}
-		
-		if (serviceCtxt.getCartridge() == null) {
-			String msg =
-			             "There's no registered Cartridge found. Domain - " + domainName +
-			                     ", sub domain - " + subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		IaasProvider iaas = serviceCtxt.getCartridge().getLastlyUsedIaas();
-		// this is required since, we need to find the correct reference.
-		// caz if the lastly used iaas retrieved from registry, it is not a reference.
-		iaas = serviceCtxt.getCartridge().getIaasProvider(iaas.getType());
-
-		if (iaas != null) {
-
-			String nodeId = null;
-			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
-
-			int i=0;
-			for (i = ctxt.getNodeIds().size()-1; i >= 0 ; i--) {
-	            String id = ctxt.getNodeIds().get(i);
-				if (id != null) {
-					nodeId = id;
-					break;
-				}
-            }
-
-			if (nodeId != null) {
-
-				// terminate it!
-				iaas = terminate(iaas, ctxt, nodeId);
-				
-				// log information
-				logTermination(nodeId, ctxt, serviceCtxt);
-
-				return true;
-			}
-
-		}
-
-		log.info("Termination of an instance which is belong to domain '" + domainName +
-		          "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
-		          "running instance found in lastly used IaaS.");
-
-		return false;
-
-	}
-
-	@Override
-	public boolean terminateAllInstances(String domainName, String subDomainName) {
-
-		boolean isAtLeastOneTerminated = false;
-		
-		subDomainName = checkSubDomain(subDomainName);
-
-		log.info("Starting to terminate all instances of domain : " + domainName +
-		         " and sub domain : " + subDomainName);
-
-		ServiceContext serviceCtxt =
-		                             FasterLookUpDataHolder.getInstance()
-		                                                   .getServiceContext(domainName,
-		                                                                      subDomainName);
-
-		if (serviceCtxt == null) {
-			String msg =
-			             "Not a registered service: domain - " + domainName + ", sub domain - " +
-			                     subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// load Cartridge, if null
-		if (serviceCtxt.getCartridge() == null) {
-			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
-			                                       serviceCtxt.getPayload(),
-			                                       FasterLookUpDataHolder.getInstance()
-			                                                             .getCartridges()));
-		}
-		
-		if (serviceCtxt.getCartridge() == null) {
-			String msg =
-			             "There's no registered Cartridge found. Domain - " + domainName +
-			                     ", sub domain - " + subDomainName;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// sort the IaasProviders according to scale down order
-		Collections.sort(serviceCtxt.getCartridge().getIaases(),
-		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
-
-		// traverse in scale down order
-		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
-
-			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
-			
-			if (ctxt == null) {
-				log.error("Iaas Context for " + iaas.getType() + " not found. Cannot terminate instances");
-				continue;
-			}
-
-			ArrayList<String> temp = new ArrayList<String>(ctxt.getNodeIds());
-			for (String id : temp) {
-				if (id != null) {
-					// terminate it!
-					terminate(iaas, ctxt, id);
-					
-					// log information
-					logTermination(id, ctxt, serviceCtxt);
-					
-					isAtLeastOneTerminated = true;
-				}
-			}
-		}
-		
-		if(isAtLeastOneTerminated){
-			return true;
-		}
-		
-		log.info("Termination of an instance which is belong to domain '" + domainName +
-		          "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
-		          "running instance found in lastly used IaaS.");
-
-		return false;
-
-	}
-	
-	public int getPendingInstanceCount(String domainName, String subDomainName) {
-
-		subDomainName = checkSubDomain(subDomainName);
-
-		int pendingInstanceCount = 0;
-
-		ServiceContext subjectedSerCtxt =
-		                                  FasterLookUpDataHolder.getInstance()
-		                                                        .getServiceContext(domainName,
-		                                                                           subDomainName);
-
-		if (subjectedSerCtxt != null && subjectedSerCtxt.getCartridgeType() != null) {
-			
-			// load cartridge
-			subjectedSerCtxt.setCartridge(loadCartridge(subjectedSerCtxt.getCartridgeType(),
-			                                            subjectedSerCtxt.getPayload(),
-			                                            FasterLookUpDataHolder.getInstance()
-			                                                                  .getCartridges()));
-			
-			if(subjectedSerCtxt.getCartridge() == null){
-				return pendingInstanceCount;
-			}
-			
-			List<IaasProvider> iaases = subjectedSerCtxt.getCartridge().getIaases();
-			
-			for (IaasProvider iaas : iaases) {
-
-				ComputeService computeService = iaas.getComputeService();
-
-				IaasContext ctxt = null;
-				if ((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null) {
-					ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
-				}
-
-				// get list of node Ids which are belong to this domain- sub
-				// domain
-				List<String> nodeIds = ctxt.getNodeIds();
-
-				if (nodeIds.isEmpty()) {
-					log.debug("Zero nodes spawned in the IaaS " + iaas.getType() + " of domain: " +
-					          domainName + " and sub domain: " + subDomainName);
-					continue;
-				}
-
-				// get all the nodes spawned by this IaasContext
-				Set<? extends ComputeMetadata> set = computeService.listNodes();
-
-				Iterator<? extends ComputeMetadata> iterator = set.iterator();
-
-				// traverse through all nodes of this ComputeService object
-				while (iterator.hasNext()) {
-					NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
-
-					// if this node belongs to the requested domain
-					if (nodeIds.contains(nodeMetadata.getId())) {
-
-						// get the status of the node
-						Status nodeStatus = nodeMetadata.getStatus();
-
-						// count nodes that are in pending state
-						if (nodeStatus.equals(Status.PENDING)) {
-							pendingInstanceCount++;
-						}
-					}
-
-				}
-			}
-		}
-
-		log.debug("Pending instance count of domain '" + domainName + "' and sub domain '" +
-		          subDomainName + "' is " + pendingInstanceCount);
-
-		return pendingInstanceCount;
-
-	}
-
-	
-	/**
-	 * A helper method to terminate an instance.
-	 */
-	private IaasProvider terminate(IaasProvider iaasTemp, IaasContext ctxt, String nodeId) {
-
-		// this is just to be safe
-		if (iaasTemp.getComputeService() == null) {
-			String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
-			log.error(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		// destroy the node
-		iaasTemp.getComputeService().destroyNode(nodeId);
-		
-		
-		String autoAssignIpProp =
-			iaasTemp.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
-		
-		// release allocated IP address
-		if (autoAssignIpProp == null ||
-			    (autoAssignIpProp != null && autoAssignIpProp.equals("false"))) {
-				// allocate an IP address - manual IP assigning mode
-			iaasTemp.getIaas().releaseAddress(iaasTemp, ctxt.getPublicIp(nodeId));
-		}		
-
-		// remove the node id
-		ctxt.removeNodeId(nodeId);
-		
-		ctxt.decrementCurrentInstanceCountByOne();
-		
-		// publish data to BAM
-		CartridgeInstanceDataPublisherTask.publish();
-
-		log.info("Node with Id: '" + nodeId + "' is terminated!");
-		return iaasTemp;
-	}
-	
-	private void logTermination(String nodeId, IaasContext ctxt, ServiceContext serviceCtxt) {
-
-		// get the ip of the terminated node
-		String ip = ctxt.getPublicIp(nodeId);
-		String ipProp = CloudControllerConstants.PUBLIC_IP_PROPERTY;
-		String ipStr = serviceCtxt.getProperty(ipProp);
-		StringBuilder newIpStr = new StringBuilder("");
-
-		for (String str : ipStr.split(CloudControllerConstants.ENTRY_SEPARATOR)) {
-			if (!str.equals(ip)) {
-				newIpStr.append(str + CloudControllerConstants.ENTRY_SEPARATOR);
-			}
-		}
-
-		// add this ip to the topology
-		serviceCtxt.setProperty(ipProp,
-		                        newIpStr.length() == 0
-		                                              ? ""
-		                                              : newIpStr.substring(0, newIpStr.length() - 1)
-		                                                        .toString());
-
-		// remove the reference
-		ctxt.removeNodeIdToPublicIp(nodeId);
-
-		// persist
-		persist();
-		
-		// trigger topology consumers
-		List<ServiceContext> list = new ArrayList<ServiceContext>();
-		list.add(serviceCtxt);
-		try {
-			dataHolder.getSharedTopologyDiffQueue().put(list);
-		} catch (InterruptedException ignore) {
-		}
-
-	}
-
-	/**
-	 * Comparator to compare {@link IaasProvider} on different attributes.
-	 */
-	public enum IaasProviderComparator implements Comparator<IaasProvider> {
-		SCALE_UP_SORT {
-			public int compare(IaasProvider o1, IaasProvider o2) {
-				return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
-			}
-		},
-		SCALE_DOWN_SORT {
-			public int compare(IaasProvider o1, IaasProvider o2) {
-				return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
-			}
-		};
-
-		public static Comparator<IaasProvider> ascending(final Comparator<IaasProvider> other) {
-			return new Comparator<IaasProvider>() {
-				public int compare(IaasProvider o1, IaasProvider o2) {
-					return other.compare(o1, o2);
-				}
-			};
-		}
-
-		public static Comparator<IaasProvider> getComparator(final IaasProviderComparator... multipleOptions) {
-			return new Comparator<IaasProvider>() {
-				public int compare(IaasProvider o1, IaasProvider o2) {
-					for (IaasProviderComparator option : multipleOptions) {
-						int result = option.compare(o1, o2);
-						if (result != 0) {
-							return result;
-						}
-					}
-					return 0;
-				}
-			};
-		}
-	}
-
-	@Override
-	public boolean registerService(String domain, String subDomain, String tenantRange,
-	                               String cartridgeType, String hostName, Properties properties, byte[] payload)
-	                                                                                     throws UnregisteredCartridgeException {
-
-		// create a ServiceContext dynamically
-		ServiceContext newServiceCtxt = new ServiceContext();
-		newServiceCtxt.setDomainName(domain);
-		newServiceCtxt.setSubDomainName(subDomain);
-		newServiceCtxt.setTenantRange(tenantRange);
-		newServiceCtxt.setHostName(hostName);
-		
-		if (properties != null && properties.getProperties() != null ) {
-			// add properties
-			for (Property property : properties.getProperties()) {
-				if (property != null && property.getName() != null) {
-					newServiceCtxt.setProperty(property.getName(), property.getValue());
-				}
-			}
-		}
-		
-		newServiceCtxt.setCartridgeType(cartridgeType);
-
-		for (Cartridge cartridge : FasterLookUpDataHolder.getInstance().getCartridges()) {
-			if (cartridge.getType().equals(cartridgeType)) {
-				newServiceCtxt.setCartridge(cartridge);
-				break;
-			}
-		}
-
-		if (newServiceCtxt.getCartridge() == null) {
-			String msg = "Registration failed - Unregistered Cartridge type: " + cartridgeType;
-			log.error(msg);
-			throw new UnregisteredCartridgeException(msg);
-		}
-
-		if (payload != null && payload.length != 0) {
-
-			// write payload file
-			try {
-				String uniqueName = domain + "-" + subDomain + ".txt";
-				FileUtils.forceMkdir(new File(CloudControllerConstants.PAYLOAD_DIR));
-				File payloadFile = new File(CloudControllerConstants.PAYLOAD_DIR + uniqueName);
-				FileUtils.writeByteArrayToFile(payloadFile, payload);
-				newServiceCtxt.setPayloadFile(payloadFile.getPath());
-
-			} catch (IOException e) {
-				String msg =
-				             "Failed while persisting the payload of domain : " + domain +
-				                     ", sub domain : " + subDomain;
-				log.error(msg, e);
-				throw new CloudControllerException(msg, e);
-			}
-
-		} else {
-			log.debug("Payload is null or empty for :\n "+newServiceCtxt.toNode().toString());
-		}
-
-		// persist
-		try {
-			String uniqueName = domain + "-" + subDomain + "-" + UUID.randomUUID() + ".xml";
-			FileUtils.writeStringToFile(new File(CloudControllerConstants.SERVICES_DIR + uniqueName),
-			                            newServiceCtxt.toXml());
-		} catch (IOException e) {
-			String msg =
-			             "Failed while persisting the service configuration - domain : " + domain +
-			                     ", sub domain : " + subDomain + ", tenant range: " + tenantRange +
-			                     ", cartridge type: " + cartridgeType;
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-
-		log.info("Service successfully registered! Domain - " + domain + ", Sub domain - " +
-		         newServiceCtxt.getSubDomainName() + ", Cartridge type - " + cartridgeType);
-
-		return true;
-	}
-
-	@Override
-	public String[] getRegisteredCartridges() {
-		// get the list of cartridges registered
-		List<Cartridge> cartridges = FasterLookUpDataHolder.getInstance().getCartridges();
-
-		if (cartridges == null) {
-			return new String[0];
-		}
-
-		String[] cartridgeTypes = new String[cartridges.size()];
-		int i = 0;
-
-		for (Cartridge cartridge : cartridges) {
-			cartridgeTypes[i] = cartridge.getType();
-			i++;
-		}
-
-		return cartridgeTypes;
-	}
-
-	@Override
-	public boolean createKeyPairFromPublicKey(String cartridgeType, String keyPairName,
-	                                          String publicKey) {
-
-		Cartridge cartridge = FasterLookUpDataHolder.getInstance().getCartridge(cartridgeType);
-
-		if (cartridge == null) {
-			String msg = "Invalid Cartridge type specified : " + cartridgeType;
-			log.fatal(msg);
-			throw new CloudControllerException(msg);
-		}
-
-		for (IaasProvider iaas : cartridge.getIaases()) {
-			String region = ComputeServiceBuilderUtil.extractRegion(iaas);
-
-			if (region == null) {
-				String msg =
-				             "Cannot find a region to create the key pair. Please add a property called 'region' under IaaS '" +
-				                     iaas.getType() + "' of Cartridge - " + cartridgeType;
-				log.fatal(msg);
-				throw new CloudControllerException(msg);
-			}
-
-			return iaas.getIaas().createKeyPairFromPublicKey(iaas, region, keyPairName, publicKey);
-		}
-
-		return false;
-	}
-
-	private String checkSubDomain(String subDomainName) {
-		// if sub domain is null, we assume it as default one.
-		if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
-			subDomainName = Constants.DEFAULT_SUB_DOMAIN;
-			log.debug("Sub domain is null, hence using the default value : " + subDomainName);
-		}
-
-		return subDomainName;
-	}
-
-	@Override
-	public CartridgeInfo getCartridgeInfo(String cartridgeType)
-	                                                           throws UnregisteredCartridgeException {
-		Cartridge cartridge = FasterLookUpDataHolder.getInstance().getCartridge(cartridgeType);
-
-		if (cartridge != null) {
-
-			return CloudControllerUtil.toCartridgeInfo(cartridge);
-
-		}
-
-		String msg =
-		             "Cannot find a Cartridge having a type of " + cartridgeType +
-		                     ". Hence unable to find information.";
-		log.error(msg);
-		throw new UnregisteredCartridgeException(msg);
-	}
-
-	@Override
-    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException{
-		
-		subDomain = checkSubDomain(subDomain);
-
-		// find the service context
-		ServiceContext subjectedSerCtxt =
-		                                  FasterLookUpDataHolder.getInstance()
-		                                                        .getServiceContext(domain,
-		                                                                           subDomain);
-		
-		if(subjectedSerCtxt == null){
-			throw new UnregisteredServiceException("No registered service found for domain: "+domain+" - sub domain: "+subDomain);
-		}
-		
-		// get the service definition file.
-		File serviceDefFile = subjectedSerCtxt.getFile();
-		
-		// delete that file, so that it gets automatically undeployed.
-	    return serviceDefFile.delete();
-    }
-
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java
deleted file mode 100644
index c33be4e..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.interfaces;
-
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredCartridgeException;
-import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredServiceException;
-import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
-import org.wso2.carbon.stratos.cloud.controller.util.CartridgeInfo;
-import org.wso2.carbon.stratos.cloud.controller.util.Properties;
-
-/**
- * This Interface provides a way to communicate with underline
- * Infrastructure which are supported by <i>JClouds</i>.
- * 
- */
-public interface CloudControllerService {
-
-    /**
-     * Creates a key pair in all IaaSes that are configured for the given cartridge,
-     * having the given name and public key.
-     * 
-     * <p/>
-     * <h4>Supported Formats</h4>
-     * <ul>
-     * <li>OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)</li>
-     * <li>Base64 encoded DER format</li>
-     * <li>SSH public key file format as specified in RFC4716</li>
-     * </ul>
-     * DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
-     * <p/>
-     * Supported lengths: 1024, 2048, and 4096.
-     * <p/>
-     * 
-     * @param cartridgeType
-     *            type of the cartridge. Note this cartridge type should be already
-     *            registered one.
-     * @param keyPairName
-     *            name of the key pair which is going to get created in IaaSes.
-     * @param publicKey
-     *            The public key.
-     * 
-     */
-	@Deprecated
-    public boolean createKeyPairFromPublicKey(String cartridgeType, String keyPairName,
-        String publicKey);
-
-    /**
-     * This method will return the information regarding the given cartridge, if present.
-     * Else this will return <code>null</code>.
-     * 
-     * @param cartridgeType
-     *            type of the cartridge.
-     * @return {@link CartridgeInfo} of the given cartridge type or <code>null</code>.
-     * @throws UnregisteredCartridgeException if there is no registered cartridge with this type.
-     */
-    public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException;
-
-    /**
-     * Calling this method will result in returning the pending instances
-     * count of a particular domain.
-     * 
-     * @param domainName
-     *            service cluster domain
-     * @param sudDomainName
-     *            service clustering sub domain of the instance to be started up.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return number of pending instances for this domain. If no instances of this
-     *         domain is present, this will return zero.
-     */
-    public int getPendingInstanceCount(String domainName, String subDomainName);
-
-    /**
-     * Calling this method will result in returning the types of {@link Cartridge}s
-     * registered in Cloud Controller.
-     * 
-     * @return String array containing types of registered {@link Cartridge}s.
-     */
-    public String[] getRegisteredCartridges();
-    
-    /**
-     * <p>
-     * Registers the details of a newly created service cluster. This will override an already
-     * present service cluster, if there is any. A service cluster is uniquely identified by its
-     * domain and sub domain combination.
-     * </p>
-     * @param domain
-     *            service cluster domain
-     * @param subDomain
-     *            service cluster sub domain
-     * @param tenantRange 
-     * 			  tenant range eg: '1-10' or '2'
-     * @param cartridgeType
-     *            cartridge type of the new service. This should be an already registered cartridge
-     *            type.
-     * @param hostName
-     * 			  host name of this service instance
-     * @param properties
-     * 			  Set of properties related to this service definition.
-     * @param payload
-     *            payload which will be passed to instance to be started. Payload shouldn't contain 
-     *            xml tags.
-     * @return whether the registration is successful or not.
-     * 
-     * @throws UnregisteredCartridgeException
-     *             when the cartridge type requested by this service is
-     *             not a registered one.
-     */
-    public boolean registerService(String domain, String subDomain, String tenantRange, String cartridgeType,
-        String hostName, Properties properties, byte[] payload) throws UnregisteredCartridgeException;
-
-    /**
-     * Calling this method will result in an instance startup, which is belong
-     * to the provided service domain. Also note that the instance that is starting up
-     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
-     * by a hyphen (<i>-</i>).
-     * 
-     * @param domainName
-     *            service clustering domain of the instance to be started up.
-     * @param subDomainName
-     *            service clustering sub domain of the instance to be started up.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return public IP which is associated with the newly started instance.
-     */
-    public String startInstance(String domainName, String subDomainName);
-
-    /**
-     * Calling this method will result in termination of all instances belong
-     * to the provided service domain and sub domain.
-     * 
-     * @param domainName
-     *            service domain of the instance to be terminated.
-     * @param sudDomainName
-     *            service clustering sub domain of the instances to be terminated.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return whether an instance terminated successfully or not.
-     */
-    public boolean terminateAllInstances(String domainName, String subDomainName);
-
-    /**
-     * Calling this method will result in termination of an instance which is belong
-     * to the provided service domain and sub domain.
-     * 
-     * @param domainName
-     *            service domain of the instance to be terminated.
-     * @param sudDomainName
-     *            service clustering sub domain of the instance to be terminated.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return whether an instance terminated successfully or not.
-     */
-    public boolean terminateInstance(String domainName, String subDomainName);
-    
-    /**
-     * Calling this method will result in termination of the lastly spawned instance which is
-     * belong to the provided service domain and sub domain.
-     * 
-     * @param domainName
-     *            service domain of the instance to be terminated.
-     * @param sudDomainName
-     *            service clustering sub domain of the instance to be terminated.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return whether the termination is successful or not.
-     */
-    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
-
-    /**
-     * Unregister the service cluster which represents by this domain and sub domain.
-     * @param domain service cluster domain
-     * @param subDomain service cluster sub domain
-     * @return whether the unregistration was successful or not.
-     * @throws UnregisteredServiceException if the service cluster requested is not a registered one.
-     */
-    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException;
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java
deleted file mode 100644
index a34a8ad..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.interfaces;
-
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.Template;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-
-/**
- * All IaaSes that are going to support by Cloud Controller, should extend this abstract class.
- */
-public abstract class Iaas {
-    
-    /**
-     * This should build the {@link ComputeService} object and the {@link Template} object,
-     * using the information from {@link IaasProvider} and should set the built 
-     * {@link ComputeService} object in the {@link IaasProvider#setComputeService(ComputeService)}
-     * and also should set the built {@link Template} object in the 
-     * {@link IaasProvider#setTemplate(Template)}.
-     * @param iaasInfo corresponding {@link IaasProvider}
-     */
-    public abstract void buildComputeServiceAndTemplate(IaasProvider iaasInfo);
-    
-    /**
-     * This method provides a way to set payload that can be obtained from {@link IaasProvider#getPayload()}
-     * in the {@link Template} of this IaaS.
-     * @param iaasInfo corresponding {@link IaasProvider}
-     */
-    public abstract void setDynamicPayload(IaasProvider iaasInfo);
-    
-    /**
-     * This will obtain an IP address from the allocated list and associate that IP with this node.
-     * @param iaasInfo corresponding {@link IaasProvider}
-     * @param node Node to be associated with an IP.
-     * @return associated public IP.
-     */
-    public abstract String associateAddress(IaasProvider iaasInfo, NodeMetadata node);
-    
-    /**
-     * This will deallocate/release the given IP address back to pool.
-     * @param iaasInfo corresponding {@link IaasProvider}
-     * @param ip public IP address to be released.
-     */
-    public abstract void releaseAddress(IaasProvider iaasInfo, String ip);
-    
-    /**
-     * This method should create a Key Pair corresponds to a given public key in the respective region having the name given.
-     * Also should override the value of the key pair in the {@link Template} of this IaaS.
-     * @param iaasInfo {@link IaasProvider} 
-     * @param region region that the key pair will get created.
-     * @param keyPairName name of the key pair. NOTE: Jclouds adds a prefix : <code>jclouds#</code>
-     * @param publicKey public key, from which the key pair will be created.
-     * @return whether the key pair creation is successful or not.
-     */
-    public abstract boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName, String publicKey);
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java
deleted file mode 100644
index a658fbf..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.ntask.core.service.TaskService;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.impl.CloudControllerServiceImpl;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.wso2.carbon.stratos.cloud.controller.topic.ConfigurationPublisher;
-import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
-
-/**
- * Registering Cloud Controller Service.
- * 
- * @scr.component name="org.wso2.carbon.stratos.cloud.controller" immediate="true"
- * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
- *                cardinality="1..1" policy="dynamic" bind="setTaskService"
- *                unbind="unsetTaskService"
- * @scr.reference name="registry.service"
- *                interface=
- *                "org.wso2.carbon.registry.core.service.RegistryService"
- *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
- *                unbind="unsetRegistryService"
- */
-public class CloudControllerDSComponent {
-
-    private static final Log log = LogFactory.getLog(CloudControllerDSComponent.class);
-
-    protected void activate(ComponentContext context) {
-        try {
-        	if (DeclarativeServiceReferenceHolder.getInstance().getConfigPub() == null) {
-        		DeclarativeServiceReferenceHolder.getInstance()
-        		.setConfigPub(new ConfigurationPublisher());
-        	}
-            
-            BundleContext bundleContext = context.getBundleContext();
-            bundleContext.registerService(CloudControllerService.class.getName(),
-                                          new CloudControllerServiceImpl(), null);
-            
-
-            log.debug("******* Cloud Controller Service bundle is activated ******* ");
-        } catch (Throwable e) {
-            log.error("******* Cloud Controller Service bundle is failed to activate ****", e);
-        }
-    }
-    
-    protected void setTaskService(TaskService taskService) {
-        if (log.isDebugEnabled()) {
-            log.debug("Setting the Task Service");
-        }
-        DeclarativeServiceReferenceHolder.getInstance().setTaskService(taskService);
-    }
-
-    protected void unsetTaskService(TaskService taskService) {
-        if (log.isDebugEnabled()) {
-            log.debug("Unsetting the Task Service");
-        }
-        DeclarativeServiceReferenceHolder.getInstance().setTaskService(null);
-    }
-    
-	protected void setRegistryService(RegistryService registryService) {
-		if (log.isDebugEnabled()) {
-			log.debug("Setting the Registry Service");
-		}
-		try {
-	        DeclarativeServiceReferenceHolder.getInstance()
-	                                             .setRegistry(registryService.getGovernanceSystemRegistry());
-        } catch (RegistryException e) {
-        	String msg = "Failed when retrieving Governance System Registry.";
-        	log.error(msg, e);
-        	throw new CloudControllerException(msg, e);
-        }
-	}
-
-	protected void unsetRegistryService(RegistryService registryService) {
-		if (log.isDebugEnabled()) {
-            log.debug("Unsetting the Registry Service");
-        }
-        DeclarativeServiceReferenceHolder.getInstance().setRegistry(null);
-	}
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
deleted file mode 100644
index 05bb39f..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.jcloud;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.jclouds.ContextBuilder;
-import org.jclouds.compute.ComputeServiceContext;
-import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
-import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
-import org.jclouds.sshj.config.SshjSshClientModule;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.inject.Module;
-
-/**
- * This class is responsible for creating a JClouds specific ComputeService object.
- */
-public class ComputeServiceBuilderUtil {
-    
-    private static final Log log = LogFactory.getLog(ComputeServiceBuilderUtil.class);
-    
-    public static byte[] getUserData(String payloadFileName) {
-        // String userData = null;
-        byte[] bytes = null;
-        try {
-            File file = new File(payloadFileName);
-            if (!file.exists()) {
-                handleException("Payload file " + payloadFileName + " does not exist");
-            }
-            if (!file.canRead()) {
-                handleException("Payload file " + payloadFileName + " does cannot be read");
-            }
-            bytes = getBytesFromFile(file);
-
-        } catch (IOException e) {
-            handleException("Cannot read data from payload file " + payloadFileName, e);
-        }
-        return bytes;
-    }
-
-    
-    public static void buildDefaultComputeService(IaasProvider iaas) {
-
-        Properties properties = new Properties();
-
-        // load properties
-        for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
-            properties.put(entry.getKey(), entry.getValue());
-        }
-
-        // set modules
-        Iterable<Module> modules =
-            ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
-                                     new EnterpriseConfigurationModule());
-
-        // build context
-        ContextBuilder builder =
-            ContextBuilder.newBuilder(iaas.getProvider())
-                          .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
-                          .overrides(properties);
-
-        // set the compute service object
-        iaas.setComputeService(builder.buildView(ComputeServiceContext.class).getComputeService());
-    }
-    
-    public static String extractRegion(IaasProvider iaas) {
-        String region;
-        // try to find region
-        if ((region = iaas.getProperty(CloudControllerConstants.REGION_PROPERTY)) == null) {
-            // if the property, isn't specified, try to obtain from the image id
-            // image id can be in following format - {region}/{UUID}
-            region = iaas.getImage().contains("/") ? iaas.getImage().split("/")[0] : null;
-        }
-
-        return region;
-    }
-    
-    /** Returns the contents of the file in a byte array
-     *
-     * @param file
-     *            - Input File
-     * @return Bytes from the file
-     * @throws java.io.IOException
-     *             , if retrieving the file contents failed.
-     */
-    public static byte[] getBytesFromFile(File file) throws IOException {
-        if (!file.exists()) {
-            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
-            return null;
-        }
-        InputStream is = new FileInputStream(file);
-        byte[] bytes;
-
-        try {
-            // Get the size of the file
-            long length = file.length();
-            
-            // You cannot create an array using a long type.
-            // It needs to be an int type.
-            // Before converting to an int type, check
-            // to ensure that file is not larger than Integer.MAX_VALUE.
-            if (length > Integer.MAX_VALUE) {
-                if (log.isDebugEnabled()) {
-                    log.debug("File is too large");
-                }
-            }
-
-            // Create the byte array to hold the data
-            bytes = new byte[(int) length];
-
-            // Read in the bytes
-            int offset = 0;
-            int numRead;
-            while (offset < bytes.length &&
-                (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
-                offset += numRead;
-            }
-
-            // Ensure all the bytes have been read in
-            if (offset < bytes.length) {
-                throw new IOException("Could not completely read file " + file.getName());
-            }
-        } finally {
-            // Close the input stream and return bytes
-            is.close();
-         }
-        
-        return bytes;
-    }
-    
-    /**
-     * handles the exception
-     * 
-     * @param msg
-     *            exception message
-     */
-    private static void handleException(String msg) {
-        log.error(msg);
-        throw new SynapseException(msg);
-    }
-
-    /**
-     * handles the exception
-     * 
-     * @param msg
-     *            exception message
-     * @param e
-     *            exception
-     */
-    private static void handleException(String msg, Exception e) {
-        log.error(msg, e);
-        throw new SynapseException(msg, e);
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java
deleted file mode 100644
index f1f1a31..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.persist;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectInputStream;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Deserializer {
-    
-    private static final Log log = LogFactory.getLog(Deserializer.class);
-
-    /**
-     * We deserialize only if the path to the serialized object file is exists.
-     * @param filePath path to the serialized object file
-     * @return the object obtained after deserialization or null if file isn't valid.
-     * @throws Exception
-     */
-    public static Object deserialize(String filePath) throws Exception {
-
-        ObjectInputStream objIn = null; 
-        Object obj = null;
-        
-        if(!new File(filePath).isFile()){
-            return obj;
-        }
-        
-        try {
-
-            objIn = new ObjectInputStream(new FileInputStream(filePath));
-            obj = objIn.readObject();
-
-        } catch (IOException e) {
-            log.error("Failed to deserialize the file at "+filePath , e);
-            throw e;
-            
-        } catch (ClassNotFoundException e) {
-            log.error("Failed to deserialize the file at "+filePath , e);
-            throw e;
-            
-        } finally{
-            objIn.close();
-        }
-        
-        return obj;
-
-    }
-    
-    /**
-     * Deserialize a byte array and retrieve the object.
-     * @param bytes bytes to be deserialized
-     * @return the deserialized {@link Object}
-     * @throws Exception if the deserialization is failed.
-     */
-    public static Object deserializeFromByteArray(byte[] bytes) throws Exception {
-
-    	ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
-    	ObjectInput in = null;
-    	try {
-    	  in = new ObjectInputStream(bis);
-    	  Object o = in.readObject(); 
-    	  
-    	  return o;
-    	  
-    	} finally {
-    	  bis.close();
-    	  in.close();
-    	}
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java
deleted file mode 100644
index 672b704..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.persist;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-
-public class Serializer {
-    
-    private static final Log log = LogFactory.getLog(Serializer.class);
-
-    public static void serializeToFile(Object serializableObj, String filePath) throws IOException {
-
-        File outFile = new File(filePath);
-        ObjectOutput ObjOut = null;
-        
-        try {
-
-            if(outFile.createNewFile()){
-                log.debug("Serialization file is created at "+filePath);
-            } else{
-                log.debug("Serialization file is already existing at "+filePath);
-            }
-            
-            ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
-            ObjOut.writeObject(serializableObj);
-
-        } catch (IOException e) {
-            log.error("Failed to serialize the object "+serializableObj.toString()
-                      + " to file "+filePath , e);
-            throw e;
-            
-        } finally{
-            ObjOut.close();
-        }
-
-    }
-    
-    /**
-     * Serialize a {@link FasterLookUpDataHolder} to a byte array.
-     * @param serializableObj
-     * @return byte[] 
-     * @throws IOException
-     */
-    public static byte[] serializeToByteArray(FasterLookUpDataHolder serializableObj) throws IOException {
-
-    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
-    	ObjectOutput out = null;
-    	try {
-    	  out = new ObjectOutputStream(bos);   
-    	  out.writeObject(serializableObj);
-    	  
-    	  return bos.toByteArray();
-    	  
-    	} finally {
-    	  out.close();
-    	  bos.close();
-    	}
-
-    }
-
-}


[06/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasContext.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasContext.java
new file mode 100644
index 0000000..5ab68a1
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasContext.java
@@ -0,0 +1,149 @@
+package org.apache.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.jclouds.compute.domain.NodeMetadata;
+
+/**
+ * 
+ * Holds runtime data of an IaaS
+ */
+public class IaasContext implements Serializable{
+	
+    private static final long serialVersionUID = 3370272526949562217L;
+
+	private String type;
+	
+	private List<String> nodeIds;
+	
+	private Map<String, String> nodeToPublicIp;
+	
+	private transient Map<String, NodeMetadata> nodes;
+	
+	private List<String> toBeRemovedNodeIds;
+	
+	private int currentInstanceCount = 0;
+	
+	public IaasContext(String iaasType) {
+		this.type = iaasType;
+		nodeToPublicIp = new HashMap<String, String>();
+		nodeIds = new ArrayList<String>();
+		nodes = new HashMap<String, NodeMetadata>();
+		toBeRemovedNodeIds = new ArrayList<String>();
+    }
+
+	public Map<String, String> getNodeToPublicIp() {
+		return nodeToPublicIp;
+	}
+	
+	public Map<String, NodeMetadata> getNodes() {
+		return nodes;
+	}
+	
+	public void setToBeRemovedNodeIds(List<String> list) {
+		this.toBeRemovedNodeIds = list;
+	}
+	
+	public List<String> getAllNodeIds() {
+		List<String> allNodeIds = new ArrayList<String>(nodeIds);
+		allNodeIds.addAll(toBeRemovedNodeIds);
+		return allNodeIds;
+	}
+	
+	public List<String> getNodeIds() {
+		return nodeIds;
+	}
+	
+	public List<String> getToBeRemovedNodeIds() {
+		return toBeRemovedNodeIds;
+	}
+	
+	public boolean didISpawn(String nodeId) {
+		if(nodeIds.contains(nodeId) || toBeRemovedNodeIds.contains(nodeId)){
+			return true;
+		}
+		return false;
+	}
+	
+	public void addNodeId(String nodeId) {
+		nodeIds.add(nodeId);
+	}
+	
+	public void addNodeToPublicIp(String nodeId, String publicIp) {
+		nodeToPublicIp.put(nodeId, publicIp);
+	}
+	
+	public void addToBeRemovedNodeId(String nodeId) {
+		toBeRemovedNodeIds.add(nodeId);
+	}
+	
+	public void removeNodeId(String nodeId) {
+		if(nodeIds.remove(nodeId)){
+			toBeRemovedNodeIds.add(nodeId);
+		}
+	}
+	
+	public void removeToBeRemovedNodeId(String nodeId) {
+		toBeRemovedNodeIds.remove(nodeId);
+	}
+	
+	public void setNodeIds(List<String> nodeIds) {
+		this.nodeIds = nodeIds;
+	}
+	
+	public String lastlySpawnedNode() {
+		return nodeIds.get(nodeIds.size()-1);
+	}
+	
+	public void addNodeMetadata(NodeMetadata node) {
+	    if(nodes == null){
+	        nodes = new HashMap<String, NodeMetadata>();
+	    }
+		nodes.put(node.getId(), node);
+	}
+	
+    public void removeNodeMetadata(NodeMetadata node) {
+        if (nodes != null) {
+            nodes.remove(node.getId());
+        }
+    }
+	
+	public void removeNodeIdToPublicIp(String nodeId){
+		nodeToPublicIp.remove(nodeId);
+	}
+	
+	public NodeMetadata getNode(String nodeId) {
+	    if(nodes == null) {
+	        return null;
+	    }
+		return nodes.get(nodeId);
+	}
+	
+	public String getPublicIp(String nodeId){
+		return nodeToPublicIp.get(nodeId);
+	}
+
+	public String getType() {
+        return type;
+    }
+
+	public void setType(String type) {
+        this.type = type;
+    }
+
+	public int getCurrentInstanceCount() {
+	    return currentInstanceCount;
+    }
+
+	public void incrementCurrentInstanceCountByOne() {
+	    this.currentInstanceCount += 1;
+    }
+	
+	public void decrementCurrentInstanceCountByOne() {
+	    this.currentInstanceCount -= 1;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasProvider.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasProvider.java
new file mode 100644
index 0000000..5388689
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/IaasProvider.java
@@ -0,0 +1,263 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.stratos.cloud.controller.interfaces.Iaas;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.Template;
+
+/**
+ * This is the basic data structure which holds an IaaS specific details.
+ * NOTE: If you add a new attribute, please assign it in the constructor too.
+ */
+public class IaasProvider implements Serializable{
+   
+    private static final long serialVersionUID = -940288190885166118L;
+
+	/**
+     * Unique id to identify this IaaS provider.
+     */
+    private String type;
+    
+    /**
+     * Fully qualified class name of an implementation of {@link org.apache.stratos.cloud.controller.interfaces.Iaas}
+     */
+    private String className;
+    
+    /**
+     * human description of this IaaS provider
+     */
+    private String name;
+    
+    /**
+     * Property map of this IaaS provider.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    /**
+     * Image identifier.
+     */
+    private String image;
+    
+    /**
+     * Max instance limit that an IaaS can spawn.
+     */
+    private int maxInstanceLimit = -1;
+    
+    /**
+     * Scale up order and scale down order of the IaaS.
+     */
+    private int scaleUpOrder = -1, scaleDownOrder = -1;
+    
+    private String provider, identity, credential;
+    
+    private transient ComputeService computeService;
+    
+    private transient Template template;
+    
+    private byte[] payload;
+    
+    /** 
+     * Corresponding {@link org.apache.stratos.cloud.controller.interfaces.Iaas} implementation
+     */
+    private transient Iaas iaas;
+    
+    public IaasProvider(){}
+    
+    public IaasProvider(IaasProvider anIaasProvider){
+    	this.type = anIaasProvider.getType();
+    	this.name = anIaasProvider.getName();
+    	this.className = anIaasProvider.getClassName();
+    	this.properties = anIaasProvider.getProperties();
+    	this.image = anIaasProvider.getImage();
+    	this.scaleUpOrder = anIaasProvider.getScaleUpOrder();
+    	this.scaleDownOrder = anIaasProvider.getScaleDownOrder();
+    	this.provider = anIaasProvider.getProvider();
+    	this.identity = anIaasProvider.getIdentity();
+    	this.credential = anIaasProvider.getCredential();
+    	this.computeService = anIaasProvider.getComputeService();
+    	this.template = anIaasProvider.getTemplate();
+    	this.payload = anIaasProvider.getPayload();
+    	this.iaas = anIaasProvider.getIaas();
+    	this.maxInstanceLimit = anIaasProvider.getMaxInstanceLimit();
+    }
+    
+    public String getType() {
+        return type;
+    }
+    
+    public void setType(String id) {
+        this.type = id;
+    }
+    
+    public String getProperty(String key) {
+        return properties.get(key);
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+    
+    public void setProperty(String key, String value) {
+        
+        if(key != null && value != null){
+            properties.put(key, value);
+        }
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+
+    public String getImage() {
+        return image;
+    }
+
+    public void setImage(String image) {
+        this.image = image;
+    }
+
+    public int getScaleUpOrder() {
+        return scaleUpOrder;
+    }
+
+    public void setScaleUpOrder(int scaleUpOrder) {
+        this.scaleUpOrder = scaleUpOrder;
+    }
+
+    public int getScaleDownOrder() {
+        return scaleDownOrder;
+    }
+
+    public void setScaleDownOrder(int scaleDownOrder) {
+        this.scaleDownOrder = scaleDownOrder;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getProvider() {
+        return provider;
+    }
+
+    public void setProvider(String provider) {
+        this.provider = provider;
+    }
+
+    public String getIdentity() {
+        return identity;
+    }
+
+    public void setIdentity(String identity) {
+        this.identity = identity;
+    }
+
+    public String getCredential() {
+        return credential;
+    }
+
+    public void setCredential(String credential) {
+        this.credential = credential;
+    }
+
+    public ComputeService getComputeService() {
+        return computeService;
+    }
+
+    public void setComputeService(ComputeService computeService) {
+        this.computeService = computeService;
+    }
+
+    public Template getTemplate() {
+        return template;
+    }
+
+    public void setTemplate(Template template) {
+        this.template = template;
+    }
+    
+    
+
+    public boolean equals(Object o) {
+        if(o instanceof IaasProvider){
+            return ((IaasProvider) o).getType().equals(this.getType());
+        }
+        
+        return false;
+    }
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(type).
+            toHashCode();
+    }
+    
+    public IaasProvider copy(){
+		return new IaasProvider(this);
+	}
+
+    public String getClassName() {
+        return className;
+    }
+
+    public void setClassName(String className) {
+        this.className = className;
+    }
+
+    public byte[] getPayload() {
+        return payload;
+    }
+
+    public void setPayload(byte[] payload) {
+        this.payload = payload;
+    }
+
+    public Iaas getIaas() {
+        return iaas;
+    }
+
+    public void setIaas(Iaas iaas) {
+        this.iaas = iaas;
+    }
+    
+    public void reset(){
+//    	nodeIds = new ArrayList<String>();
+//    	nodes = new HashMap<String, NodeMetadata>();
+//    	toBeRemovedNodeIds = new ArrayList<String>();
+    }
+
+	public int getMaxInstanceLimit() {
+	    return this.maxInstanceLimit;
+    }
+
+	public void setMaxInstanceLimit(int maxInstanceLimit) {
+	    this.maxInstanceLimit = maxInstanceLimit;
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/PortMapping.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/PortMapping.java
new file mode 100644
index 0000000..df099f9
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/PortMapping.java
@@ -0,0 +1,46 @@
+package org.apache.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+
+public class PortMapping implements Serializable{
+	
+    private static final long serialVersionUID = -5387564414633460306L;
+	private String protocol;
+	private String port;
+	private String proxyPort;
+	
+	public PortMapping(){
+		
+	}
+	
+	public PortMapping(String protocol, String port, String proxyPort){
+		this.protocol = protocol;
+		this.port = port;
+		this.proxyPort = proxyPort;
+	}
+
+	public String getProtocol() {
+    	return protocol;
+    }
+
+	public void setProtocol(String protocol) {
+    	this.protocol = protocol;
+    }
+
+	public String getPort() {
+    	return port;
+    }
+
+	public void setPort(String port) {
+    	this.port = port;
+    }
+
+	public String getProxyPort() {
+    	return proxyPort;
+    }
+
+	public void setProxyPort(String proxyPort) {
+    	this.proxyPort = proxyPort;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Properties.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Properties.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Properties.java
new file mode 100644
index 0000000..1cf607a
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Properties.java
@@ -0,0 +1,36 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+/**
+ * Had to wrap {@link Property} array using a class, since there's a bug in current 
+ * stub generation.
+ */
+public class Properties {
+
+	private Property[] properties;
+
+	public Property[] getProperties() {
+	    return properties;
+    }
+
+	public void setProperties(Property[] properties) {
+	    this.properties = properties;
+    }
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Property.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Property.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Property.java
new file mode 100644
index 0000000..5ca5b13
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Property.java
@@ -0,0 +1,35 @@
+package org.apache.stratos.cloud.controller.util;
+/**
+ * Holds a property 
+ */
+public class Property {
+	
+	private String name;
+	private String value;
+	
+	public Property(){
+		
+	}
+	
+	public Property(String name, String value){
+		this.setName(name);
+		this.setValue(value);
+	}
+
+	public String getName() {
+	    return name;
+    }
+
+	public void setName(String name) {
+	    this.name = name;
+    }
+
+	public String getValue() {
+	    return value;
+    }
+
+	public void setValue(String value) {
+	    this.value = value;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/ServiceContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/ServiceContext.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/ServiceContext.java
new file mode 100644
index 0000000..ed21d21
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/ServiceContext.java
@@ -0,0 +1,283 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import java.io.File;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+/**
+ * We keep information regarding a service (i.e. a cartridge instance)
+ * in this object.
+ */
+public class ServiceContext implements Serializable{
+
+    private static final long serialVersionUID = -6740964802890082678L;
+    private File file;
+	private String domainName;
+    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+    private String tenantRange;
+    private String hostName;
+    private String payloadFilePath;
+    private String cartridgeType;
+    private Cartridge cartridge;
+    private byte[] payload;
+    /**
+     * Key - Value pair.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    /**
+     * Key - IaaS Type
+     * Value - {@link IaasContext} object
+     */
+    private Map<String, IaasContext> iaasCtxts = new HashMap<String, IaasContext>();
+	
+    public Map<String, IaasContext> getIaasCtxts() {
+    	return iaasCtxts;
+    }
+
+	public String getDomainName() {
+        return domainName;
+    }
+    
+    public boolean setDomainName(String domainName) {
+        if (!"".equals(domainName)) {
+            this.domainName = domainName;
+            return true;
+        }
+        
+        return false;
+    }
+    
+    public void setProperty(String key, String value) {
+        properties.put(key, value);
+    }
+    
+    public String getProperty(String key) {
+        
+        if(properties.containsKey(key)){
+            return properties.get(key);
+        }
+        
+        return "";
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public String getSubDomainName() {
+        return subDomainName;
+    }
+
+    public void setSubDomainName(String subDomainName) {
+        if(subDomainName == null || "".equals(subDomainName)){
+            return;
+        }
+        this.subDomainName = subDomainName;
+    }
+
+    public Cartridge getCartridge() {
+        return cartridge;
+    }
+
+    public void setCartridge(Cartridge cartridge) {
+        this.cartridge = cartridge;
+    }
+
+	public String getTenantRange() {
+	    return tenantRange;
+    }
+
+	public void setTenantRange(String tenantRange) {
+	    this.tenantRange = tenantRange;
+    }
+	
+	public IaasContext addIaasContext(String iaasType){
+		IaasContext ctxt = new IaasContext(iaasType);
+		iaasCtxts.put(iaasType, ctxt);
+		return ctxt;
+	}
+	
+	public IaasContext getIaasContext(String type){
+		return iaasCtxts.get(type);
+	}
+	
+	public void setIaasContextMap(Map<String, IaasContext> map){
+		iaasCtxts = map;
+	}
+	
+//	public byte[] getPayload() {
+//    	return payload;
+//    }
+//
+//	public void setPayload(byte[] payload) {
+//    	this.payload = payload;
+//    }
+
+
+	public String getPayloadFile() {
+	    return payloadFilePath;
+    }
+
+	public void setPayloadFile(String payloadFile) {
+	    this.payloadFilePath = payloadFile;
+    }
+
+	public String getHostName() {
+		if(cartridge != null && (hostName == null || hostName.isEmpty())){
+			return cartridge.getHostName();
+		}
+	    return hostName;
+    }
+
+	public void setHostName(String hostName) {
+	    this.hostName = hostName;
+    }
+
+	public String getCartridgeType() {
+	    return cartridgeType;
+    }
+
+	public void setCartridgeType(String cartridgeType) {
+	    this.cartridgeType = cartridgeType;
+    }
+
+	public byte[] getPayload() {
+	    return payload;
+    }
+
+	public void setPayload(byte[] payload) {
+	    this.payload = payload;
+    }
+	
+	public String toXml() {
+		String str =
+				payloadFilePath == null ? "<service domain=\"" + domainName +
+				                        "\" subDomain=\"" + subDomainName +
+				                        "\" tenantRange=\"" + tenantRange + "\">\n" +
+				                        "\t<cartridge type=\"" + cartridgeType +
+				                        "\"/>\n" + "\t<host>" + hostName +
+				                        "</host>\n" + "</service>"
+				                        
+		                                    : "<service domain=\"" + domainName +
+		                                    "\" subDomain=\"" + subDomainName +
+		                                    "\" tenantRange=\"" + tenantRange + "\">\n" +
+		                                    "\t<cartridge type=\"" + cartridgeType +
+		                                    "\"/>\n"  + "\t<host>" + hostName +
+		                                    "</host>\n" + "\t<payload>" + payloadFilePath +
+		                                    "</payload>\n" +
+		                                    propertiesToXml() +
+		                                    "</service>";
+		return str;
+	}
+	
+	public Node toNode() {
+		Node node = new Node();
+		node.setName(cartridgeType);
+		String sbrace = Constants.NGINX_NODE_START_BRACE;
+		String ebrace = Constants.NGINX_NODE_END_BRACE;
+		String delimiter = Constants.NGINX_LINE_DELIMITER;
+		String newLine = "\n";
+		String nginx = 
+				Constants.DOMAIN_ELEMENT+sbrace+newLine+
+				domainName+sbrace+newLine+
+				Constants.HOSTS_ELEMENT+" "+hostName+delimiter+newLine+
+				Constants.SUB_DOMAIN_ELEMENT+" "+subDomainName+delimiter+newLine+
+				Constants.TENANT_RANGE_ELEMENT+" "+tenantRange+delimiter+newLine+
+				propertiesToNginx()+
+				ebrace+newLine+
+				ebrace+newLine;
+		
+		return NodeBuilder.buildNode(node, nginx);
+		
+	}
+	
+	/**
+	 * Had to made this public in order to access from a test case.
+	 * @return
+	 */
+	public String propertiesToNginx() {
+		StringBuilder builder = new StringBuilder("");
+		for (Iterator<Entry<String, String>> iterator = getProperties().entrySet().iterator(); iterator.hasNext();) {
+			Map.Entry<String, String> prop = (Map.Entry<String, String>) iterator.next();
+
+			String key = prop.getKey();
+			String value = prop.getValue();
+			if (key != null) {
+				builder.append(key + " " + (value == null ? "" : value) +
+				               Constants.NGINX_LINE_DELIMITER + "\n");
+			}
+
+		}
+
+		return builder.toString();
+	}
+	
+	public String propertiesToXml() {
+		StringBuilder builder = new StringBuilder("");
+		for (Iterator<Entry<String, String>> iterator = getProperties().entrySet().iterator(); iterator.hasNext();) {
+			Map.Entry<String, String> prop = (Map.Entry<String, String>) iterator.next();
+
+			String key = prop.getKey();
+			String value = prop.getValue();
+			if (key != null) {
+				builder.append("\t<property name=\""+key +"\" value=\"" + (value == null ? "" : value) +"\"/>\n");
+			}
+
+		}
+
+		return builder.toString();
+	}
+	
+	public File getFile() {
+		return file;
+	}
+	
+	public void setFile(File file) {
+		this.file = file;
+	}
+	
+	public boolean equals(Object obj) {
+		if (obj instanceof ServiceContext) {
+			return this.domainName.equals(((ServiceContext) obj).getDomainName()) &&
+			       this.subDomainName.equals(((ServiceContext) obj).getSubDomainName());
+		}
+		return false;
+	}
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(domainName).
+            append(subDomainName).
+            toHashCode();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..09cc707
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
@@ -0,0 +1,36 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. 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.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <deployers>
+    	<deployer>
+            <directory>../../conf</directory>
+            <extension>xml</extension>
+            <class>org.apache.stratos.cloud.controller.deployers.CloudControllerDeployer</class>
+        </deployer>
+        <deployer>
+            <directory>cartridges</directory>
+            <extension>xml</extension>
+            <class>org.apache.stratos.cloud.controller.deployers.CartridgeDeployer</class>
+        </deployer>
+        <deployer>
+            <directory>services</directory>
+            <extension>xml</extension>
+            <class>org.apache.stratos.cloud.controller.deployers.ServiceDeployer</class>
+        </deployer>
+    </deployers>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..f931ba7
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="CloudControllerService" scope="application">
+        <parameter name="ServiceClass">org.apache.stratos.cloud.controller.impl.CloudControllerServiceImpl</parameter>
+        <messageReceivers>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
+    </messageReceivers>
+    </service>
+</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
new file mode 100644
index 0000000..6887211
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="cartridge">
+    <xs:annotation>
+      <xs:documentation>You can have 1..n cartridge elements.</xs:documentation>
+    </xs:annotation>
+    <xs:complexType>
+    	<xs:choice maxOccurs="unbounded">
+    		<xs:element name="property" maxOccurs="unbounded"
+    			minOccurs="0">
+    			<xs:annotation>
+    				<xs:documentation>
+    					cartridge element can have 0..n properties, and
+    					they'll be overwritten by the properties
+    					specified under iaasProvider child elements of
+    					cartridge element.
+    				</xs:documentation>
+    			</xs:annotation>
+    			<xs:complexType>
+    				<xs:simpleContent>
+    					<xs:extension base="xs:string">
+    						<xs:attribute type="xs:string" name="name" />
+    						<xs:attribute type="xs:string" name="value" />
+    					</xs:extension>
+    				</xs:simpleContent>
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="displayName" maxOccurs="1" minOccurs="0" />
+    		<xs:element name="description" maxOccurs="1" minOccurs="0" />
+    		<xs:element name="iaasProvider" maxOccurs="unbounded"
+    			minOccurs="1">
+    			<xs:annotation>
+    				<xs:documentation>
+    					A cartridge element should add a reference to an
+    					existing IaaS provider (specified in the above
+    					&amp;lt;iaasProviders&amp;gt; section) or it can
+    					create a completely new IaaS Provider (which
+    					should have a unique "type" attribute.
+    				</xs:documentation>
+    			</xs:annotation>
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+                        <xs:element type="xs:string" name="scaleUpOrder"
+    						minOccurs="0" maxOccurs="1" />
+                        <xs:element type="xs:string" name="scaleDownOrder"
+    						minOccurs="0" maxOccurs="1" />
+                        <xs:element type="xs:string" name="maxInstanceLimit"
+    						minOccurs="0" maxOccurs="1" />
+    					<xs:element type="xs:string" name="imageId"
+    						minOccurs="0" maxOccurs="1" />
+    					<xs:element name="property"
+    						maxOccurs="unbounded" minOccurs="0">
+    						<xs:complexType>
+    							<xs:simpleContent>
+    								<xs:extension base="xs:string">
+    									<xs:attribute type="xs:string"
+    										name="name" />
+    									<xs:attribute type="xs:string"
+    										name="value" />
+    								</xs:extension>
+    							</xs:simpleContent>
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    				<xs:attribute type="xs:string" name="type" />
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="deployment" maxOccurs="1" minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="dir" maxOccurs="unbounded"
+    						minOccurs="0" type="xs:string">
+    					</xs:element>
+    				</xs:choice>
+    				<xs:attribute name="baseDir" type="xs:string">
+    				</xs:attribute>
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="portMapping" maxOccurs="1"
+    			minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="http" maxOccurs="1"
+    						minOccurs="1">
+    						<xs:complexType>
+    							<xs:attribute name="port"
+    								type="xs:string" />
+    							<xs:attribute name="proxyPort"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    					<xs:element name="https" maxOccurs="1"
+    						minOccurs="0">
+    						<xs:complexType>
+    							<xs:attribute name="port"
+    								type="xs:string" />
+    							<xs:attribute name="proxyPort"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="appTypes" maxOccurs="1"
+    			minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="appType" maxOccurs="unbounded"
+    						minOccurs="1">
+    						<xs:complexType>
+                                    <xs:attribute name="name" type="xs:string" use="required" />
+                                    <xs:attribute name="appSpecificMapping"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    			</xs:complexType>
+    		</xs:element>
+    	</xs:choice>
+    	<xs:attribute type="xs:string" name="type" />
+    	<xs:attribute type="xs:string" name="host" />
+    	<xs:attribute type="xs:string" name="provider" />
+    	<xs:attribute type="xs:string" name="version" />
+    	<xs:attribute type="xs:boolean" name="multiTenant" />
+    </xs:complexType>
+  </xs:element>
+
+  <!-- <xs:complexType name="deploymentType">
+  	<xs:sequence>
+  		<xs:element name="dir" type="xs:string" maxOccurs="1" minOccurs="1"></xs:element>
+  	</xs:sequence>
+  </xs:complexType> -->
+</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
new file mode 100644
index 0000000..3b187a7
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
@@ -0,0 +1,144 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="cartridges" >
+    <xs:annotation>
+      <xs:documentation>Use below section to specify properties that are needed in order to start Cartridges.</xs:documentation>
+    </xs:annotation>
+    <xs:complexType>
+    <xs:sequence>
+      <xs:choice maxOccurs="unbounded">
+        <xs:element name="cartridge" maxOccurs="unbounded" minOccurs="1">
+          <xs:annotation>
+            <xs:documentation>You can have 1..n cartridge elements.</xs:documentation>
+          </xs:annotation>
+          <xs:complexType>
+            <xs:choice maxOccurs="unbounded">
+            	<xs:element name="property" maxOccurs="unbounded"
+            		minOccurs="0">
+            		<xs:annotation>
+            			<xs:documentation>
+            				cartridge element can have 0..n properties,
+            				and they'll be overwritten by the properties
+            				specified under iaasProvider child elements
+            				of cartridge element.
+            			</xs:documentation>
+            		</xs:annotation>
+            		<xs:complexType>
+            			<xs:simpleContent>
+            				<xs:extension base="xs:string">
+            					<xs:attribute type="xs:string"
+            						name="name" />
+            					<xs:attribute type="xs:string"
+            						name="value" />
+            				</xs:extension>
+            			</xs:simpleContent>
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="displayName" maxOccurs="1"
+            		minOccurs="0" />
+            	<xs:element name="description" maxOccurs="1"
+            		minOccurs="0" />
+            	<xs:element name="iaasProvider" maxOccurs="unbounded"
+            		minOccurs="1">
+            		<xs:annotation>
+            			<xs:documentation>
+            				A cartridge element should add a reference
+            				to an existing IaaS provider (specified in
+            				the above &amp;lt;iaasProviders&amp;gt;
+            				section) or it can create a completely new
+            				IaaS Provider (which should have a unique
+            				"type" attribute.
+            			</xs:documentation>
+            		</xs:annotation>
+            		<xs:complexType>
+            			<xs:choice maxOccurs="unbounded">
+                            <xs:element type="xs:string" name="scaleUpOrder"
+    						    minOccurs="0" maxOccurs="1" />
+                            <xs:element type="xs:string" name="scaleDownOrder"
+    						    minOccurs="0" maxOccurs="1" />
+                            <xs:element type="xs:string" name="maxInstanceLimit"
+    						    minOccurs="0" maxOccurs="1" />
+            				<xs:element type="xs:string" name="imageId"
+            					minOccurs="0" maxOccurs="1" />
+            				<xs:element name="property"
+            					maxOccurs="unbounded" minOccurs="0">
+            					<xs:complexType>
+            						<xs:simpleContent>
+            							<xs:extension
+            								base="xs:string">
+            								<xs:attribute
+            									type="xs:string" name="name" />
+            								<xs:attribute
+            									type="xs:string" name="value" />
+            							</xs:extension>
+            						</xs:simpleContent>
+            					</xs:complexType>
+            				</xs:element>
+            			</xs:choice>
+            			<xs:attribute type="xs:string" name="type" />
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="deployment" maxOccurs="1">
+            		<xs:complexType>
+            			<xs:choice maxOccurs="unbounded">
+            				<xs:element name="dir" maxOccurs="unbounded"
+            					minOccurs="0" type="xs:string">
+            				</xs:element>
+            			</xs:choice>
+            			<xs:attribute name="baseDir" type="xs:string">
+            			</xs:attribute>
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="portMapping" maxOccurs="1"
+            		minOccurs="1">
+            		<xs:complexType>
+            			<xs:choice maxOccurs="unbounded">
+            				<xs:element name="http" maxOccurs="1"
+            					minOccurs="1">
+            					<xs:complexType>
+            						<xs:attribute name="port"
+            							type="xs:string" />
+            						<xs:attribute name="proxyPort"
+            							type="xs:string" />
+            					</xs:complexType>
+            				</xs:element>
+            				<xs:element name="https" maxOccurs="1"
+            					minOccurs="0">
+            					<xs:complexType>
+            						<xs:attribute name="port"
+            							type="xs:string" />
+            						<xs:attribute name="proxyPort"
+            							type="xs:string" />
+            					</xs:complexType>
+            				</xs:element>
+            			</xs:choice>
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="appTypes" maxOccurs="1"
+    			minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="appType" maxOccurs="unbounded"
+    						minOccurs="1">
+    						<xs:complexType>
+                                    <xs:attribute name="name" type="xs:string" use="required" />
+                                    <xs:attribute name="appSpecificMapping"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    			</xs:complexType>
+    		</xs:element>
+            </xs:choice>
+            <xs:attribute type="xs:string" name="type"/>
+            <xs:attribute type="xs:string" name="host" />
+            <xs:attribute type="xs:string" name="provider" />
+            <xs:attribute type="xs:string" name="version" />
+            <xs:attribute type="xs:boolean" name="multiTenant" />
+          </xs:complexType>
+        </xs:element>
+      </xs:choice>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
new file mode 100644
index 0000000..48a8532
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+        <xs:element name="service">
+          <xs:annotation>
+            <xs:documentation>you can have 0..n service elements</xs:documentation>
+          </xs:annotation>
+          <xs:complexType>
+          	<xs:choice maxOccurs="unbounded">
+          		<xs:element name="cartridge">
+          			<xs:annotation>
+          				<xs:documentation>
+          					this element's value should be a reference
+          					to an existing cartridge
+          				</xs:documentation>
+          			</xs:annotation>
+          			<xs:complexType>
+          				<xs:simpleContent>
+          					<xs:extension base="xs:string">
+          						<xs:attribute type="xs:string"
+          							name="type" />
+          					</xs:extension>
+          				</xs:simpleContent>
+          			</xs:complexType>
+          		</xs:element>
+          		<xs:element name="payload" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+          		<xs:element name="host" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+          		<xs:element name="property"
+    						maxOccurs="unbounded" minOccurs="0">
+    						<xs:complexType>
+    							<xs:simpleContent>
+    								<xs:extension base="xs:string">
+    									<xs:attribute type="xs:string"
+    										name="name" />
+    									<xs:attribute type="xs:string"
+    										name="value" />
+    								</xs:extension>
+    							</xs:simpleContent>
+    						</xs:complexType>
+    					</xs:element>
+          	</xs:choice>
+          	<xs:attribute type="xs:string" name="domain" />
+          	<xs:attribute type="xs:string" name="tenantRange" />
+          	<xs:attribute type="xs:string" name="subDomain" />
+          </xs:complexType>
+        </xs:element>
+</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
new file mode 100644
index 0000000..5fc9fb7
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="services">
+    <xs:annotation>
+      <xs:documentation>Here you specify the service domains related details.</xs:documentation>
+    </xs:annotation>
+    <xs:complexType>
+      <xs:choice maxOccurs="unbounded">
+        <xs:element name="service" maxOccurs="unbounded" minOccurs="1">
+          <xs:annotation>
+            <xs:documentation>you can have 0..n service elements</xs:documentation>
+          </xs:annotation>
+          <xs:complexType>
+            <xs:choice maxOccurs="unbounded">
+              <xs:element name="cartridge">
+                <xs:annotation>
+                  <xs:documentation>this element's value should be a reference to an existing cartridge</xs:documentation>
+                </xs:annotation>
+                <xs:complexType>
+                  <xs:simpleContent>
+                    <xs:extension base="xs:string">
+                      <xs:attribute type="xs:string" name="type"/>
+                    </xs:extension>
+                  </xs:simpleContent>
+                </xs:complexType>
+              </xs:element>
+              <xs:element name="payload" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+              <xs:element name="host" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+              <xs:element name="property"
+    						maxOccurs="unbounded" minOccurs="0">
+    						<xs:complexType>
+    							<xs:simpleContent>
+    								<xs:extension base="xs:string">
+    									<xs:attribute type="xs:string"
+    										name="name" />
+    									<xs:attribute type="xs:string"
+    										name="value" />
+    								</xs:extension>
+    							</xs:simpleContent>
+    						</xs:complexType>
+    					</xs:element>
+            </xs:choice>
+            <xs:attribute type="xs:string" name="domain"/>
+            <xs:attribute type="xs:string" name="subDomain"/>
+            <xs:attribute type="xs:string" name="tenantRange" />
+          </xs:complexType>
+        </xs:element>
+      </xs:choice>
+    </xs:complexType>
+  </xs:element>
+</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomValidationTest.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
new file mode 100644
index 0000000..8611f9d
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
@@ -0,0 +1,125 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cartridge.autoscaler.service.axiom;
+
+import java.io.File;
+
+import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.xml.sax.SAXParseException;
+
+import junit.framework.TestCase;
+
+public class AxiomValidationTest extends TestCase {
+    
+    AxiomXpathParser util1, util2, util3, util4, util5, util6, util7, util8, util9;
+    File xmlSchemaCartridges = new File("src/main/resources/cartridges.xsd");
+    File xmlSchemaCartridge = new File("src/main/resources/cartridge.xsd");
+    String dir = "src/test/resources/";
+
+    public AxiomValidationTest(String name) {
+        super(name);
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        util1 = new AxiomXpathParser(new File(dir+"cartridges-1.xml"));
+        util2 = new AxiomXpathParser(new File(dir+"cartridges-2.xml"));
+        util3 = new AxiomXpathParser(new File(dir+"cartridges-3.xml"));
+        util4 = new AxiomXpathParser(new File(dir+"cartridges-4.xml"));
+        util5 = new AxiomXpathParser(new File(dir+"cartridges-5.xml"));
+        util6 = new AxiomXpathParser(new File(dir+"cartridges-6.xml"));
+        util7 = new AxiomXpathParser(new File(dir+"cartridges-7.xml"));
+        util8 = new AxiomXpathParser(new File(dir+"cartridges-8.xml"));
+        util9 = new AxiomXpathParser(new File(dir+"cartridges-9.xml"));
+        util1.parse();
+        util2.parse();
+        util3.parse();
+        util4.parse();
+        util5.parse();
+        util6.parse();
+        util7.parse();
+        util8.parse();
+        util9.parse();
+    }
+
+    public final void testCartridgeValidation() throws Exception {
+        
+        // schema 1 - cartridges 
+        assertEquals(true, util1.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util5.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util6.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util7.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util9.validate(xmlSchemaCartridges));
+        
+        // schema 2 - cartridge
+        assertEquals(true, util2.validate(xmlSchemaCartridge));
+        
+        assertEquals(true, util8.validate(xmlSchemaCartridge));
+    }
+    
+    public final void testCartridgeInvalidation() {
+        
+     // schema 1 - cartridges 
+        try {
+            util2.validate(xmlSchemaCartridges);
+        } catch (Exception e) {
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util3.validate(xmlSchemaCartridges);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util4.validate(xmlSchemaCartridges);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        // schema 2 - cartridge
+        
+        try {
+            util1.validate(xmlSchemaCartridge);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util3.validate(xmlSchemaCartridge);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util4.validate(xmlSchemaCartridge);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
new file mode 100644
index 0000000..8163637
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
@@ -0,0 +1,51 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cartridge.autoscaler.service.axiom;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.axiom.om.OMNode;
+import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+
+import junit.framework.TestCase;
+
+public class AxiomXpathParserTest extends TestCase {
+    AxiomXpathParser parser;
+    File xmlFile = new File("src/test/resources/cloud-controller.xml");
+
+    public AxiomXpathParserTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        parser = new AxiomXpathParser(xmlFile);
+        parser.parse();
+    }
+    
+    public void testGetMatchingNodes(){
+        List<OMNode> list = parser.getMatchingNodes("/cloudController/iaasProviders/iaasProvider/provider");
+        assertEquals(1, list.size());
+        parser.setIaasProvidersList();
+        assertEquals(1, FasterLookUpDataHolder.getInstance().getIaasProviders().size());
+        assertEquals(5, FasterLookUpDataHolder.getInstance().getIaasProviders().get(0).getMaxInstanceLimit());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/util/ServiceContextTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/util/ServiceContextTest.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/util/ServiceContextTest.java
new file mode 100644
index 0000000..dad9471
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/java/org/apache/cartridge/autoscaler/service/util/ServiceContextTest.java
@@ -0,0 +1,49 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cartridge.autoscaler.service.util;
+
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+import junit.framework.TestCase;
+
+public class ServiceContextTest extends TestCase {
+    
+    ServiceContext ctxt = new ServiceContext();
+
+    public ServiceContextTest(String name) {
+        super(name);
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        ctxt.setProperty("min_app_instances", "2");
+        ctxt.setProperty("max_app_instances", "5");
+        ctxt.setProperty("public_ip", null);
+    }
+
+    public final void testPropertiesToNginx() throws Exception {
+    	assertEquals(true, ctxt.propertiesToNginx().contains("min_app_instances 2;\n"));
+    	assertEquals(true, ctxt.propertiesToNginx().contains("max_app_instances 5;\n"));
+    	assertEquals(true, ctxt.propertiesToNginx().contains("public_ip ;\n"));
+    }
+    
+    public final void testPropertiesToXml() throws Exception {
+    	System.out.println(ctxt.propertiesToXml());
+    	assertEquals(true, ctxt.propertiesToXml().contains("name=\"min_app_instances\" value=\"2\""));
+    }
+   
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
new file mode 100644
index 0000000..2eccd3d
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
@@ -0,0 +1,33 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" host="abc.com" provider="carbon">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<property name="ss" value="slsls"/>
+			<description>This is a php cartridge.</description>
+			<deployment baseDir="xyz">
+				<dir>abc</dir>
+			</deployment>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
new file mode 100644
index 0000000..b0fe963
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+	<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc/def</dir>
+			</deployment>
+			
+			<appTypes>
+				<appType name="axis2services" appSpecificMapping="true"/>
+				<appType name="webapps" appSpecificMapping="false"/>
+			</appTypes>
+		</cartridge>
+	
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
new file mode 100644
index 0000000..eb6d565
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
@@ -0,0 +1,16 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+		
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
new file mode 100644
index 0000000..2f82ce8
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
@@ -0,0 +1,32 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge>
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+
+			<deployment>
+				<dir>abc</dir>
+				<dir>def</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
new file mode 100644
index 0000000..705d020
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
@@ -0,0 +1,29 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
new file mode 100644
index 0000000..28ac6fb
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
@@ -0,0 +1,19 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+			</iaasProvider>
+		
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
new file mode 100644
index 0000000..0baa407
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
@@ -0,0 +1,40 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5.1">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+			</iaasProvider>
+		
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5.1">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+			</iaasProvider>
+		
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
new file mode 100644
index 0000000..8d43239
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+	<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc/def</dir>
+			</deployment>
+			
+			<appTypes>
+				<appType name="axis2services" appSpecificMapping="true"/>
+				<appType name="webapps" appSpecificMapping="false"/>
+			</appTypes>
+		</cartridge>
+	
+<?xml version="1.0" encoding="ISO-8859-1"?>
+	<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc/def</dir>
+			</deployment>
+			
+			<appTypes>
+				<appType name="axis2services" appSpecificMapping="true"/>
+				<appType name="webapps" appSpecificMapping="false"/>
+			</appTypes>
+		</cartridge>
+	
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
new file mode 100644
index 0000000..969091a
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
@@ -0,0 +1,66 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="as" host="abc.com" provider="carbon" version="5.1.0" multiTenant="true">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<property name="ss" value="slsls"/>
+			<description>This is a WSO2 AS cartridge.</description>
+			<deployment baseDir="xyz">
+				<dir>abc</dir>
+			</deployment>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+		</cartridge>
+	
+	</cartridges>
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="as" host="abc.com" provider="carbon" version="5.1.0" multiTenant="true">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<property name="ss" value="slsls"/>
+			<description>This is a WSO2 AS cartridge.</description>
+			<deployment baseDir="xyz">
+				<dir>abc</dir>
+			</deployment>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
new file mode 100644
index 0000000..9f02ace
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<!--
+  ~ Copyright 2005-2011 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+  
+<cloudController xmlns:svns="http://org.wso2.securevault/configuration">
+
+	<svns:secureVault
+		provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler" />
+	
+	<dataPublisher enable="false">
+		<!-- BAM Server Info - default values are 'admin' and 'admin' 
+			 Optional element. -->
+		<bamServer>
+			<adminUserName>admin</adminUserName>
+			<adminPassword svns:secretAlias="cloud.controller.bam.server.admin.password">admin</adminPassword>
+		</bamServer>
+		<!-- Default cron expression is '1 * * * * ? *' meaning 'first second of every minute'.
+			 Optional element. -->
+		<cron>1 * * * * ? *</cron>
+		<!-- Cassandra cluster related info -->
+		<cassandraInfo>
+			<connectionUrl>localhost:9160</connectionUrl>
+			<userName>admin</userName>
+			<password svns:secretAlias="cloud.controller.cassandra.server.password">admin</password>
+		</cassandraInfo>
+	</dataPublisher>
+	
+	<topologySync enable="true">
+		<!-- MB server info -->
+		<mbServerUrl>localhost:5672</mbServerUrl>
+		<cron>1 * * * * ? *</cron>
+	</topologySync>
+	
+	<!-- Specify the properties that are common to an IaaS here. This element 
+		is not necessary [0..1]. But you can use this section to avoid specifying 
+		same property over and over again. -->
+	<iaasProviders>
+		<!--<iaasProvider type="ec2" name="EC2 specific details"> <provider>aws-ec2</provider> 
+			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity> 
+			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential> 
+			<scaleUpOrder>2</scaleUpOrder> <scaleDownOrder>1</scaleDownOrder> <property 
+			name="A.x" value="a"/> <property name="B" value="b"/> <imageId>tempEC2</imageId> 
+			</iaasProvider> -->
+		<iaasProvider type="openstack" name="openstack specific details">
+			<className>org.apache.stratos.cloud.controller.iaases.OpenstackNovaIaas</className>
+			<provider>openstack-nova</provider>
+			<identity svns:secretAlias="cloud.controller.openstack.identity">demo:demo</identity>
+			<credential svns:secretAlias="cloud.controller.openstack.credential">openstack</credential>
+			<property name="jclouds.endpoint" value="http://172.17.0.1:5000/" />
+			<property name="jclouds.api-version" value="2.0/" />
+			<scaleUpOrder>1</scaleUpOrder>
+			<scaleDownOrder>2</scaleDownOrder>
+			<maxInstanceLimit>5</maxInstanceLimit>
+			<property name="region" value="x" />
+			<property name="Y" value="y" />
+			<imageId>tempLXC</imageId>
+		</iaasProvider>
+	</iaasProviders>
+</cloudController>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/pom.xml
----------------------------------------------------------------------
diff --git a/components/pom.xml b/components/pom.xml
index da6c17a..37d505e 100644
--- a/components/pom.xml
+++ b/components/pom.xml
@@ -191,7 +191,8 @@
     	<axiom.osgi.version.range>[1.2.11.wso2v4, 1.3.0)</axiom.osgi.version.range>
         <version.tomcat>7.0.34</version.tomcat>	
 	<axis2.wso2.version>1.6.1.wso2v9</axis2.wso2.version>
-
+	 <orbit.version.geronimo-jms_1.1_spec>1.1.0.wso2v1</orbit.version.geronimo-jms_1.1_spec>
+         <google.guice.wso2.version>3.0.wso2v1</google.guice.wso2.version>
         <!--eclipse.osgi.version>3.5.0.v20090520</eclipse.osgi.version>
         <eclipse.osgi.services.version>3.2.0.v20090520-1800</eclipse.osgi.services.version>
         <equinox.commons.logging.version>1.0.4.v200706111724</equinox.commons.logging.version>


[04/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java
deleted file mode 100644
index a66bf8a..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.deployers;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.deployment.AbstractDeployer;
-import org.apache.axis2.deployment.DeploymentException;
-import org.apache.axis2.deployment.repository.util.DeploymentFileData;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
-import org.wso2.carbon.stratos.cloud.controller.consumers.TopologyBuilder;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * All the {@link Cartridge}s will get deployed / undeployed / updated via this class. 
- */
-public class ServiceDeployer extends AbstractDeployer{
-    
-    private static final Log log = LogFactory.getLog(ServiceDeployer.class);
-    
-    private FasterLookUpDataHolder serviceContextLookUpStructure;
-    private Map<String, List<ServiceContext>> fileToServiceContextListMap;
-    private File servicesSchema, serviceSchema;
-
-    @Override
-    public void init(ConfigurationContext arg0) {
-        fileToServiceContextListMap = new ConcurrentHashMap<String, List<ServiceContext>>();
-        String etcDir = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator;
-        servicesSchema = new File(etcDir+"services.xsd");
-        serviceSchema = new File(etcDir+"service.xsd");
-    }
-
-    @Override
-    public void setDirectory(String arg0) {
-        // component xml handles this
-    }
-
-    @Override
-    public void setExtension(String arg0) {
-        // component xml handles this
-    }
-    
-    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
-        
-        log.debug("Started to deploy the deployment artefact: "+deploymentFileData.getFile());
-        serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
-        
-        AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
-        parser.parse();
-        
-        // validate
-        try {
-            validateService(parser);
-            
-        } catch (Exception e) {
-            String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
-            // back up the file
-            File f = deploymentFileData.getFile();
-            f.renameTo(new File(deploymentFileData.getAbsolutePath()+".back"));
-            log.error(msg, e);
-            throw new DeploymentException(msg, e);
-        }
-        
-        // deploy
-        List<ServiceContext> services = parser.getServiceContexts();
-        
-        // notify consumer by adding the diff
-        try {
-	        serviceContextLookUpStructure.getSharedTopologyDiffQueue().put(services);
-        } catch (InterruptedException ignore) {
-        }
-        
-        // update map
-        fileToServiceContextListMap.put(deploymentFileData.getAbsolutePath(), new ArrayList<ServiceContext>(services));
-        
-        log.info("Successfully deployed the Service definition specified at "+deploymentFileData.getAbsolutePath());
-    }
-    
-    private void validateService(AxiomXpathParser parser) throws Exception {
-        boolean validated = false;
-        Exception firstException = null;
-
-        try{
-            // first try to validate using services schema
-            parser.validate(servicesSchema);
-            validated = true;
-            log.debug("Service validation was successful.");
-            
-        }catch (Exception e) {
-            firstException = e;
-        }
-        
-        if(!validated){
-            try{
-                // Now try to validate using service schema
-                parser.validate(serviceSchema);
-                validated = true;
-                log.debug("Service validation was successful.");
-                
-            }catch (Exception e) {
-                String msg = "Service XML validation failed. Invalid Service XML: "+parser.getXmlSource().getAbsolutePath();
-                log.error(msg, firstException);
-                throw firstException;
-            }
-        }
-        
-        
-    }
-
-    public void undeploy(String file) throws DeploymentException {
-
-        serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
-
-        // grab the entry from Map
-        if(fileToServiceContextListMap.containsKey(file)){
-            // remove 'em all
-            for (ServiceContext ctxt : fileToServiceContextListMap.get(file)) {
-                serviceContextLookUpStructure.removeServiceContext(ctxt);
-                // remove from the topology
-                TopologyBuilder.removeTopologyAndPublish(ctxt);
-            }
-            
-            log.info("Successfully undeployed the Service definition specified at "+file);
-        }
-        
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java
deleted file mode 100644
index f911de5..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class CloudControllerException extends RuntimeException {
-    
-    private static final long serialVersionUID = -6326227079367867222L;
-
-    public CloudControllerException(String msg) {
-        super(msg);
-    }
-    
-    public CloudControllerException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java
deleted file mode 100644
index 3b0ae7d..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class DeserializationException extends RuntimeException {
-    
-    private static final long serialVersionUID = -2426068347954381831L;
-
-    public DeserializationException(String msg) {
-        super(msg);
-    }
-    
-    public DeserializationException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
deleted file mode 100644
index aa93b15..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class InvalidCartridgeDefinitionException extends Exception {
-    
-    private static final long serialVersionUID = -6326227079367867222L;
-
-    public InvalidCartridgeDefinitionException(String msg) {
-        super(msg);
-    }
-    
-    public InvalidCartridgeDefinitionException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java
deleted file mode 100644
index fd14187..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class InvalidXMLException extends RuntimeException {
-    
-    private static final long serialVersionUID = -6326227079367867222L;
-
-    public InvalidXMLException(String msg) {
-        super(msg);
-    }
-    
-    public InvalidXMLException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-    
-    public InvalidXMLException(Exception ex) {
-        super(ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
deleted file mode 100644
index 8b9240f..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class MalformedConfigurationFileException extends RuntimeException {
-
-    private static final long serialVersionUID = -1662095377704279326L;
-    
-    public MalformedConfigurationFileException(String msg) {
-        super(msg);
-    }
-    
-    public MalformedConfigurationFileException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java
deleted file mode 100644
index ba8cb65..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-/**
- * This will throw when no instance is found
- */
-public class NoInstanceFoundException extends Exception {
-
-    /**
-     * For serializing requirement
-     */
-    private static final long serialVersionUID = -435060299292679892L;
-
-
-    public NoInstanceFoundException(String msg) {
-        super(msg);
-    }
-    
-    public NoInstanceFoundException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java
deleted file mode 100644
index fd40f0a..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class SerializationException extends RuntimeException {
-    
-    private static final long serialVersionUID = -3701458642228072331L;
-
-    public SerializationException(String msg) {
-        super(msg);
-    }
-    
-    public SerializationException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
deleted file mode 100644
index 3640bc2..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class UnregisteredCartridgeException extends Exception {
-    
-    private static final long serialVersionUID = -6326227079367867222L;
-
-    public UnregisteredCartridgeException(String msg) {
-        super(msg);
-    }
-    
-    public UnregisteredCartridgeException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java
deleted file mode 100644
index 2060553..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.exception;
-
-public class UnregisteredServiceException extends Exception {
-    
-    private static final long serialVersionUID = -6326227079367867222L;
-
-    public UnregisteredServiceException(String msg) {
-        super(msg);
-    }
-    
-    public UnregisteredServiceException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java
deleted file mode 100644
index c1f5686..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.hector;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-
-import me.prettyprint.cassandra.model.BasicColumnDefinition;
-import me.prettyprint.cassandra.model.BasicColumnFamilyDefinition;
-import me.prettyprint.cassandra.model.CqlQuery;
-import me.prettyprint.cassandra.model.CqlRows;
-import me.prettyprint.cassandra.serializers.StringSerializer;
-import me.prettyprint.cassandra.service.CassandraHostConfigurator;
-import me.prettyprint.cassandra.service.ThriftCfDef;
-import me.prettyprint.hector.api.Cluster;
-import me.prettyprint.hector.api.Keyspace;
-import me.prettyprint.hector.api.beans.HColumn;
-import me.prettyprint.hector.api.beans.Row;
-import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
-import me.prettyprint.hector.api.ddl.ColumnIndexType;
-import me.prettyprint.hector.api.ddl.ComparatorType;
-import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
-import me.prettyprint.hector.api.factory.HFactory;
-import me.prettyprint.hector.api.query.QueryResult;
-
-public class CassandraDataRetriever {
-
-    private static final Log log = LogFactory.getLog(CassandraDataRetriever.class);
-    private static FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
-    private final static StringSerializer se = StringSerializer.get();
-    private static Cluster cluster;
-    private static Keyspace keyspace;
-    private static boolean isInit;
-    
-    public static void init() {
-
-        if(isInit){
-            return;
-        }
-        getCassandraKeyspace();
-        indexCounterColumn("payload_status");
-        isInit = true;
-    }
-    
-    public static void connect() {
-        
-        if(keyspace == null){
-            handleException("Cannot find the key space.");
-        }
-        
-        String colFamily = CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY;
-        
-        CqlQuery<String,String,String> cqlQuery = new CqlQuery<String,String,String>(keyspace, se, se, se);
-        cqlQuery.setQuery("select payload_nodeId from "+colFamily+" where payload_status='RUNNING'");
-//        cqlQuery.setQuery("select * from "+colFamily+" where payload_domain='nirmal'");
-        QueryResult<CqlRows<String,String,String>> result = cqlQuery.execute();
-        
-        if (result != null && result.get() != null) {
-            List<Row<String, String, String>> list = result.get().getList();
-            for (Row<?, ?, ?> row : list) {
-                System.out.println(".");
-                List<?> columns = row.getColumnSlice().getColumns();
-                for (Iterator<?> iterator = columns.iterator(); iterator.hasNext();) {
-                    HColumn<?, ?> column = (HColumn<?, ?>) iterator.next();
-                    System.out.print(column.getName() + ":" + column.getValue()
-                            + "\t");
-                }
-                System.out.println("");
-            }
-        }
-        
-//        ColumnQuery<String, String, String> columnQuery =
-//                HFactory.createStringColumnQuery(keyspace);
-//        KeyIterator<String> keyIterator = new KeyIterator<String>(keyspace, colFamily, StringSerializer.get());
-//        for ( String key : keyIterator ) {
-//            
-//            columnQuery.setColumnFamily(colFamily).setKey(key).setName("payload_nodeId");
-//            QueryResult<HColumn<String, String>> result = columnQuery.execute();
-//            HColumn<String, String> hColumn = result.get();
-//            System.out.println("Column: " + hColumn.getName() + " Value : " + hColumn.getValue() + "\n");
-//        }
-        
-//        //Read Data
-//        for (String key : keyList) {
-//            System.out.println("\nretrieving Key " + rowKey + "From Column Family " + columnFamily + "\n");
-//            for (String columnName : columnList.split(":")) {
-//                //sout data
-//            }
-//        }
-        
-        
-    }
-    
-    private static void indexCounterColumn(String idxColumnName) {
-
-        KeyspaceDefinition keyspaceDefinition = cluster.describeKeyspace(CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE);
-
-        List<ColumnFamilyDefinition> cdfs = keyspaceDefinition.getCfDefs();
-        ColumnFamilyDefinition cfd = null;
-        for (ColumnFamilyDefinition c : cdfs) {
-            if (c.getName().equals(CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY)) {
-                System.out.println(c.getName());
-                cfd = c;
-                break;
-            }
-        }
-
-        BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(cfd);
-
-        BasicColumnDefinition bcdf = new BasicColumnDefinition();
-        bcdf.setName(StringSerializer.get().toByteBuffer(idxColumnName));
-        bcdf.setIndexName(idxColumnName + "index");
-        bcdf.setIndexType(ColumnIndexType.KEYS);
-        bcdf.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
-
-        columnFamilyDefinition.addColumnDefinition(bcdf);
-        cluster.updateColumnFamily(new ThriftCfDef(columnFamilyDefinition));
-
-    } 
-    
-    private static void getCassandraKeyspace() {
-        if (cluster == null) {
-            Map<String, String> credentials = new HashMap<String, String>();
-            credentials.put("username", dataHolder.getCassandraUser());
-            credentials.put("password", dataHolder.getCassandraPassword());
-
-            cluster =
-                      retrieveCassandraCluster(CloudControllerConstants.DEFAULT_CASSANDRA_CLUSTER_NAME,
-                                               dataHolder.getCassandraConnUrl(), credentials);
-
-            keyspace =
-                       HFactory.createKeyspace(CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE,
-                                               cluster);
-        }
-        
-    }
-    
-    private static Cluster retrieveCassandraCluster(String clusterName, String connectionUrl,
-        Map<String, String> credentials) {
-
-        CassandraHostConfigurator hostConfigurator = new CassandraHostConfigurator(connectionUrl);
-        hostConfigurator.setRetryDownedHosts(false);
-        Cluster cluster = HFactory.createCluster(clusterName, hostConfigurator, credentials);
-        return cluster;
-    }
-
-    private static void handleException(String msg) {
-
-        log.error(msg);
-        throw new CloudControllerException(msg);
-    }
-    
-//    private void handleException(String msg, Exception e) {
-//
-//        log.error(msg, e);
-//        throw new AutoscalerServiceException(msg, e);
-//    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java
deleted file mode 100644
index 64efe7a..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.hive;
-
-import java.rmi.RemoteException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.client.Options;
-import org.apache.axis2.client.ServiceClient;
-import org.apache.axis2.transport.http.HttpTransportProperties;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceHiveExecutionException;
-import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub;
-import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub.QueryResult;
-import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub.QueryResultRow;
-import org.wso2.carbon.base.ServerConfiguration;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.utils.CarbonUtils;
-
-public class HiveQueryExecutor {
-    private static final Log log = LogFactory.getLog(HiveQueryExecutor.class);
-    private HiveExecutionServiceStub hiveService;
-    private String payloadPrefix = CloudControllerConstants.PAYLOAD_PREFIX;
-    private String hiveTable = "cloudController";
-    private FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
-    
-    public HiveQueryExecutor() {
-
-        ServerConfiguration serverConfig =  CarbonUtils.getServerConfiguration();
-        String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");
-        String serviceName = "HiveExecutionService";
-        HttpTransportProperties.Authenticator authenticator;
-        
-        try {
-            hiveService = new HiveExecutionServiceStub(bamServerUrl+"/services/"+serviceName);
-            
-            // admin service authentication
-            authenticator = new HttpTransportProperties.Authenticator();
-            authenticator.setUsername(dataHolder.getBamUsername());
-            authenticator.setPassword(dataHolder.getBamPassword());
-            authenticator.setPreemptiveAuthentication(true);
-            
-            ServiceClient client = hiveService._getServiceClient();
-            Options option = client.getOptions();
-            option.setManageSession(true);
-            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
-            option.setTimeOutInMilliSeconds(120000);
-
-        } catch (AxisFault e) {
-            String msg = "Cannot get a connection to "+serviceName;
-            handleException(msg, e);
-        }
-    }
-    
-    public QueryResult[] execute(String query){
-        try {
-            return hiveService.executeHiveScript(query);
-        } catch (RemoteException e) {
-            handleException("Query : '"+query+"' - "+e.getMessage(), e);
-        } catch (HiveExecutionServiceHiveExecutionException e) {
-            handleException("Query : '"+query+"' - "+e.getMessage(), e);
-        }
-        
-        return new QueryResult[0];
-    }
-    
-    public void createHiveTable(){
-        String query = 
-                "CREATE EXTERNAL TABLE IF NOT EXISTS "+hiveTable+" (id STRING, " +
-                payloadPrefix+CloudControllerConstants.NODE_ID_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.CARTRIDGE_TYPE_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.DOMAIN_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.HOST_NAME_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.HYPERVISOR_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.IAAS_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.IMAGE_ID_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.LOGIN_PORT_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.PRIV_IP_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.PUB_IP_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.STATUS_COL+" STRING," +
-                payloadPrefix+CloudControllerConstants.SUB_DOMAIN_COL+" STRING" +
-                ") STORED BY 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' " +
-                "WITH SERDEPROPERTIES ( \"cassandra.host\" = \""+dataHolder.getCassandraConnUrl().split(":")[0]+"\"," +
-                "\"cassandra.port\" = \""+dataHolder.getCassandraConnUrl().split(":")[1]+
-                "\",\"cassandra.ks.name\" = \""+CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE+"\"," +
-                "\"cassandra.ks.username\" = \""+dataHolder.getCassandraUser()+
-                "\", \"cassandra.ks.password\" = \""+dataHolder.getCassandraPassword()+"\"," +
-                "\"cassandra.cf.name\" = \""+CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY+"\"," +
-                "\"cassandra.columns.mapping\" = \"" +
-                payloadPrefix+CloudControllerConstants.NODE_ID_COL+"," +
-                payloadPrefix+CloudControllerConstants.CARTRIDGE_TYPE_COL+"," +
-                payloadPrefix+CloudControllerConstants.DOMAIN_COL+"," +
-                payloadPrefix+CloudControllerConstants.HOST_NAME_COL+"," +
-                payloadPrefix+CloudControllerConstants.HYPERVISOR_COL+"," +
-                payloadPrefix+CloudControllerConstants.IAAS_COL+"," +
-                payloadPrefix+CloudControllerConstants.IMAGE_ID_COL+"," +
-                payloadPrefix+CloudControllerConstants.LOGIN_PORT_COL+"," +
-                payloadPrefix+CloudControllerConstants.PRIV_IP_COL+"," +
-                payloadPrefix+CloudControllerConstants.PUB_IP_COL+"," +
-                payloadPrefix+CloudControllerConstants.STATUS_COL+"," +
-                payloadPrefix+CloudControllerConstants.SUB_DOMAIN_COL +
-                "\");";
-        
-        execute(query);
-    }
-    
-    public List<String> getRunningNodeIds() {
-        List<String> nodeIds = new ArrayList<String>();
-        String query =
-//                       "select " + payloadPrefix + AutoscalerConstant.NODE_ID_COL + " from " +
-//                               hiveTable + " where payload_status='RUNNING' OR payload_status='PENDING' ;";
-
-//        "select id1 from (select distinct payload_nodeId from cloud1  where payload_status='RUNNING' OR payload_status='PENDING') table1
-//LEFT OUTER JOIN
-//(select distinct payload_nodeId as nodeId from cloud1  where payload_status='TERMINATED') table2
-//ON(table2.nodeId = table1.payload_nodeId)
-//where table2.nodeId is null;";
-                "select table1.id1 from (select distinct "+payloadPrefix+CloudControllerConstants.NODE_ID_COL+
-                " as id1 from "+ hiveTable +" where "+payloadPrefix+CloudControllerConstants.STATUS_COL+
-                "='RUNNING' OR "+payloadPrefix+CloudControllerConstants.STATUS_COL+"='PENDING') table1 " +
-                "LEFT OUTER JOIN " +"(select distinct "+payloadPrefix+CloudControllerConstants.NODE_ID_COL+
-                " as id2 from "+hiveTable+" where "+payloadPrefix+CloudControllerConstants.STATUS_COL+"='TERMINATED') table2 " +
-                "ON(table1.id1 = table2.id2) where table2.id2 is null;";
-        
-        QueryResult[] result = execute(query);
-
-        for (QueryResult queryResult : result) {
-            if(queryResult == null || queryResult.getResultRows() == null){
-                continue;
-            }
-            for (QueryResultRow row : queryResult.getResultRows()) {
-                if (row != null && row.getColumnValues() != null && row.getColumnValues().length != 0) {
-                    nodeIds.add(row.getColumnValues()[0]);
-                }
-            }
-        }
-        
-        return nodeIds;
-
-    }
-    
-    private void handleException(String msg, Exception e){
-        log.error(msg, e);
-        throw new CloudControllerException(msg, e);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java
deleted file mode 100644
index 8c3b78a..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.iaases;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jclouds.aws.ec2.AWSEC2AsyncClient;
-import org.jclouds.aws.ec2.AWSEC2Client;
-import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
-import org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;
-import org.jclouds.aws.ec2.functions.ImportOrReturnExistingKeypair;
-import org.jclouds.compute.ComputeServiceContext;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.ec2.domain.KeyPair;
-import org.jclouds.ec2.domain.PublicIpInstanceIdPair;
-import org.jclouds.rest.RestContext;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
-import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-public class AWSEC2Iaas extends Iaas{
-    
-    private static final Log log = LogFactory.getLog(AWSEC2Iaas.class);
-    private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
-    private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
-
-    @Override
-    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
-
-        // builds and sets Compute Service
-        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
-        
-        // builds and sets Template
-        buildTemplate(iaasInfo);
-        
-    }
-    
-    private void buildTemplate(IaasProvider iaas) {
-        if (iaas.getComputeService() == null) {
-            String msg = "Compute service is null for IaaS provider: " + iaas.getName();
-            log.fatal(msg);
-            throw new CloudControllerException(msg);
-        }
-
-        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
-
-        // set image id specified
-        templateBuilder.imageId(iaas.getImage());
-
-        if (iaas.getProperty("instanceType") != null) {
-            // set instance type eg: m1.large
-            templateBuilder.hardwareId(iaas.getProperty("instanceType"));
-        }
-
-		// build the Template
-		Template template = templateBuilder.build();
-
-		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
-		// wish to assign IPs manually, it can be non-blocking.
-		// is auto-assign-ip mode or manual-assign-ip mode?
-		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
-		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-        
-        // this is required in order to avoid creation of additional security groups by jclouds.
-        template.getOptions().as(TemplateOptions.class).inboundPorts(new int[]{});
-
-        // set EC2 specific options
-		if (iaas.getProperty("subnetId") != null) {
-			template.getOptions().as(AWSEC2TemplateOptions.class).subnetId(iaas.getProperty("subnetId"));
-		}
-
-        if (iaas.getProperty("availabilityZone") != null) {
-            template.getOptions().as(AWSEC2TemplateOptions.class)
-                    .placementGroup(iaas.getProperty("availabilityZone"));
-        }
-
-        if (iaas.getProperty("securityGroups") != null) {
-            template.getOptions()
-                    .as(AWSEC2TemplateOptions.class)
-                    .securityGroups(iaas.getProperty("securityGroups")
-                                        .split(CloudControllerConstants.ENTRY_SEPARATOR));
-
-        }
-
-        if (iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER) != null) {
-            template.getOptions()
-                    .as(AWSEC2TemplateOptions.class)
-                    .userData(ComputeServiceBuilderUtil.getUserData(CarbonUtils.getCarbonHome() +
-                                                                File.separator +
-                                                                iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER)));
-        }
-
-        if (iaas.getProperty("keyPair") != null) {
-            template.getOptions().as(AWSEC2TemplateOptions.class)
-                    .keyPair(iaas.getProperty("keyPair"));
-        }
-
-        // set Template
-        iaas.setTemplate(template);
-    }
-
-    @Override
-    public void setDynamicPayload(IaasProvider iaasInfo) {
-
-        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
-
-            iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
-                    .userData(iaasInfo.getPayload());
-        }
-
-    }
-
-    @Override
-    public synchronized boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
-        String publicKey) {
-
-        String ec2Msg = " ec2. Region: "+region+" - Key Pair Name: ";
-        
-        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-        @SuppressWarnings("unchecked")
-        RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext = context.unwrap(RestContext.class);
-        AWSEC2Client ec2Client = restContext.getApi();
-        
-        ImportOrReturnExistingKeypair importer = new ImportOrReturnExistingKeypair(ec2Client);
-        
-        RegionNameAndPublicKeyMaterial regionNameAndKey = new RegionNameAndPublicKeyMaterial(region, keyPairName, publicKey);
-        KeyPair keyPair = importer.apply(regionNameAndKey);
-        
-        if (keyPair != null) {
-
-            iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
-                    .keyPair(keyPair.getKeyName());
-
-            log.info(SUCCESSFUL_LOG_LINE + ec2Msg + keyPair.getKeyName());
-            return true;
-        }
-        
-        log.error(FAILED_LOG_LINE+ec2Msg);
-        
-        return false;
-    }
-
-    @Override
-	public synchronized String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
-
-		ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-		@SuppressWarnings("unchecked")
-		RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext =
-		                                                           context.unwrap(RestContext.class);
-		AWSEC2Client ec2Client = restContext.getApi();
-		String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
-
-		String ip = null;
-		
-		// first try to find an unassigned IP.
-		ArrayList<PublicIpInstanceIdPair> unassignedIps =
-		                                                  Lists.newArrayList(Iterables.filter(ec2Client.getElasticIPAddressServices()
-		                                                                                               .describeAddressesInRegion(region,
-		                                                                                                                          new String[0]),
-		                                                                                      new Predicate<PublicIpInstanceIdPair>() {
-
-			                                                                                      @Override
-			                                                                                      public boolean apply(PublicIpInstanceIdPair arg0) {
-				                                                                                      return arg0.getInstanceId() == null;
-			                                                                                      }
-
-		                                                                                      }));
-		
-		
-		if (!unassignedIps.isEmpty()) {
-			// try to prevent multiple parallel launches from choosing the same
-			// ip.
-			Collections.shuffle(unassignedIps);
-			ip = Iterables.getLast(unassignedIps).getPublicIp();
-		}
-		
-		// if no unassigned IP is available, we'll try to allocate an IP.
-		if (ip == null || ip.isEmpty()) {
-			try {
-				ip = ec2Client.getElasticIPAddressServices().allocateAddressInRegion(region);
-				log.info("Assigned ip [" + ip +"]");
-
-			} catch (Exception e) {
-				String msg = "Failed to allocate an IP address. All IP addresses are in use.";
-				log.error(msg, e);
-				throw new CloudControllerException(msg, e);
-			}
-		}
-
-		String id = node.getProviderId();
-
-		// wait till the fixed IP address gets assigned - this is needed before we associate a
-		// public IP
-
-		while (node.getPrivateAddresses() == null) {
-			CloudControllerUtil.sleep(1000);
-		}
-
-		int retries = 0;
-		while (retries < 12 && !associatePublicIp(ec2Client, region, ip, id)) {
-
-			// wait for 5s
-			CloudControllerUtil.sleep(5000);
-			retries++;
-		}
-
-		// FIXME make this debug
-		log.info("Successfully associated an IP address " + ip + " for node with id: " +
-		         node.getId());
-
-		return ip;
-
-	}
-
-	/**
-     * @param ec2Client
-     * @param region
-     * @param ip
-     * @param id
-     */
-	private boolean associatePublicIp(AWSEC2Client ec2Client, String region, String ip, String id) {
-		try {
-			ec2Client.getElasticIPAddressServices().associateAddressInRegion(region, ip, id);
-			log.info("Successfully associated public IP ");
-			return true;
-		} catch (Exception e) {
-			log.error("Exception in associating public IP " + e.getMessage());
-			return false;
-		}
-	}
-
-	@Override
-    public synchronized void releaseAddress(IaasProvider iaasInfo, String ip) {
-	    
-		ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-		@SuppressWarnings("unchecked")
-		RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext =
-		                                                           context.unwrap(RestContext.class);
-		AWSEC2Client ec2Client = restContext.getApi();
-		String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
-
-		ec2Client.getElasticIPAddressServices().disassociateAddressInRegion(region, ip);
-		ec2Client.getElasticIPAddressServices().releaseAddressInRegion(region, ip);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
deleted file mode 100644
index f763144..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.iaases;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jclouds.compute.ComputeServiceContext;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.NodeMetadataBuilder;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.openstack.nova.v2_0.NovaAsyncClient;
-import org.jclouds.openstack.nova.v2_0.NovaClient;
-import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
-import org.jclouds.openstack.nova.v2_0.domain.FloatingIP;
-import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
-import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPClient;
-import org.jclouds.openstack.nova.v2_0.extensions.KeyPairClient;
-import org.jclouds.rest.InsufficientResourcesException;
-import org.jclouds.rest.RestContext;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
-import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-public class OpenstackNovaIaas extends Iaas{
-    
-    private static final Log log = LogFactory.getLog(OpenstackNovaIaas.class);
-    private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
-    private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
-
-    @Override
-    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
-
-        // builds and sets Compute Service
-        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
-        
-        // builds and sets Template
-        buildTemplate(iaasInfo);
-        
-    }
-    
-    private void buildTemplate(IaasProvider iaas) {
-        if (iaas.getComputeService() == null) {
-            throw new CloudControllerException("Compute service is null for IaaS provider: " +
-                                                 iaas.getName());
-        }
-
-        // // if domain to template map is null
-        // if (entity.getDomainToTemplateMap() == null) {
-        // // we initialize it
-        // entity.setDomainToTemplateMap(new HashMap<String, Template>());
-        // }
-
-        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
-        templateBuilder.imageId(iaas.getImage());
-
-        // to avoid creation of template objects in each and every time, we create all
-        // at once!
-        // for (org.wso2.carbon.cartridge.autoscaler.service.util.ServiceContext temp :
-        // serviceContexts) {
-
-        String instanceType;
-
-        // set instance type
-        if (((instanceType = iaas.getProperty("instanceType")) != null)) {
-
-            templateBuilder.hardwareId(instanceType);
-        }
-
-        Template template = templateBuilder.build();
-        
-		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
-		// wish to assign IPs manually, it can be non-blocking.
-		// is auto-assign-ip mode or manual-assign-ip mode?
-		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
-		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-
-		// this is required in order to avoid creation of additional security groups by Jclouds.
-        template.getOptions().as(TemplateOptions.class).inboundPorts(new int[]{});
-
-        if (iaas.getProperty("securityGroups") != null) {
-            template.getOptions()
-                    .as(NovaTemplateOptions.class)
-                    .securityGroupNames(iaas.getProperty("securityGroups")
-                                            .split(CloudControllerConstants.ENTRY_SEPARATOR));
-        }
-
-        if (iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER) != null) {
-            template.getOptions()
-                    .as(NovaTemplateOptions.class)
-                    .userData(ComputeServiceBuilderUtil.getUserData(CarbonUtils.getCarbonHome() +
-                                                                File.separator +
-                                                                iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER)));
-        }
-
-        if (iaas.getProperty("keyPair") != null) {
-            template.getOptions().as(NovaTemplateOptions.class)
-                    .keyPairName(iaas.getProperty("keyPair"));
-        }
-
-        // set Template
-        iaas.setTemplate(template);
-    }
-
-    @Override
-    public void setDynamicPayload(IaasProvider iaasInfo) {
-        
-        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
-
-            iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class).userData(iaasInfo.getPayload());
-        }
-
-    }
-
-    @Override
-    public synchronized boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
-        String publicKey) {
-
-        String openstackNovaMsg = " Openstack-nova. Region: " + region + " - Name: ";
-
-        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-        @SuppressWarnings("unchecked")
-        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
-        
-        KeyPairClient api = restContext.getApi().getKeyPairExtensionForZone(region).get();
-        
-        KeyPair keyPair = api.createKeyPairWithPublicKey(keyPairName, publicKey);
-
-        if (keyPair != null) {
-            
-            iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class)
-            .keyPairName(keyPair.getName());
-            
-            log.info(SUCCESSFUL_LOG_LINE + openstackNovaMsg + keyPair.getName());
-            return true;
-        }
-
-        log.error(FAILED_LOG_LINE + openstackNovaMsg);
-        return false;
-
-    }
-
-    @Override
-    public synchronized String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
-
-        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-        @SuppressWarnings("unchecked")
-        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
-        
-        NovaClient novaClient = restContext.getApi();
-        String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
-        
-        FloatingIPClient floatingIp = novaClient.getFloatingIPExtensionForZone(region).get();
-        
-        String ip=null;
-        // first try to find an unassigned IP.
-        ArrayList<FloatingIP> unassignedIps =
-        		Lists.newArrayList(Iterables.filter(floatingIp.listFloatingIPs(),
-        		                                    new Predicate<FloatingIP>() {
-        			
-        			@Override
-        			public boolean apply(FloatingIP arg0) {
-        				//FIXME is this the correct filter?
-        				return arg0.getFixedIp() == null;
-        			}
-        			
-        		}));
-        
-		if (!unassignedIps.isEmpty()) {
-			// try to prevent multiple parallel launches from choosing the same
-			// ip.
-			Collections.shuffle(unassignedIps);
-			ip = Iterables.getLast(unassignedIps).getIp();
-		}
-        
-        // if no unassigned IP is available, we'll try to allocate an IP.
-		if (ip == null || ip.isEmpty()) {
-
-			try {
-				ip = floatingIp.allocate().getIp();
-
-			} catch (InsufficientResourcesException e) {
-				String msg = "Failed to allocate an IP address. All IP addresses are in use.";
-				log.error(msg, e);
-				throw new CloudControllerException(msg, e);
-			}
-		}
-
-        // wait till the fixed IP address gets assigned - this is needed before we associate a public IP
-        
-        while(node.getPrivateAddresses() == null){
-        	CloudControllerUtil.sleep(1000);
-        }
-
-        int retries =0;
-        while(retries < 5 && !associateIp(floatingIp, ip, node.getProviderId()) ){
-        	
-        	// wait for 5s
-        	CloudControllerUtil.sleep(5000);
-        	retries++;
-        }
-        
-        NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip)).build();
-      
-        log.info("Successfully associated an IP address "+ip+" for node with id: "+node.getId());
-        
-        return ip;
-    }
-    
-    @Override
-    public synchronized void releaseAddress(IaasProvider iaasInfo, String ip){
-    	
-    	ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-        @SuppressWarnings("unchecked")
-        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
-        
-        NovaClient novaClient = restContext.getApi();
-        String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
-        
-        FloatingIPClient floatingIpClient = novaClient.getFloatingIPExtensionForZone(region).get();
-        
-        for (FloatingIP floatingIP: floatingIpClient.listFloatingIPs()) {
-	        if(floatingIP.getIp().equals(ip)){
-	        	floatingIpClient.deallocate(floatingIP.getId());
-	        	break;
-	        }
-        }
-        
-    }
-    
-    private boolean associateIp(FloatingIPClient client, String ip, String id){
-    	try{
-    		client.addFloatingIPToServer(ip, id);
-    		return true;
-    	}catch(RuntimeException ex){
-    		return false;
-    	}
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java
deleted file mode 100644
index 42d3e69..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.iaases;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.vcloud.compute.options.VCloudTemplateOptions;
-import org.jclouds.vcloud.domain.network.IpAddressAllocationMode;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
-import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-
-public class VCloudIaas extends Iaas{
-    
-    private static final Log log = LogFactory.getLog(VCloudIaas.class);
-
-    @Override
-    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
-
-        // builds and sets Compute Service
-        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
-        
-        // builds and sets Template
-        buildTemplate(iaasInfo);
-        
-    }
-    
-    private void buildTemplate(IaasProvider iaas) {
-        if (iaas.getComputeService() == null) {
-            String msg = "Compute service is null for IaaS provider: " + iaas.getName();
-            log.fatal(msg);
-            throw new CloudControllerException(msg);
-        }
-
-        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
-
-        // set image id specified
-        templateBuilder.imageId(iaas.getImage());
-
-        // build the Template
-        Template template = templateBuilder.build();
-
-		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
-		// wish to assign IPs manually, it can be non-blocking.
-		// is auto-assign-ip mode or manual-assign-ip mode? - default mode is non-blocking 
-		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
-		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-		
-        // this is required in order to avoid creation of additional security groups by Jclouds.
-        template.getOptions().as(TemplateOptions.class).inboundPorts(22, 80, 8080, 443, 8243);
-
-        template.getOptions().as(VCloudTemplateOptions.class).ipAddressAllocationMode(IpAddressAllocationMode.POOL);
-
-        // set Template
-        iaas.setTemplate(template);
-    }
-
-    @Override
-    public void setDynamicPayload(IaasProvider iaasInfo) {
-
-    	// in VCloud case we need to run a script
-        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
-
-        	Template template = iaasInfo.getTemplate();
-        	String script = "";
-        	String launchParams ="", key="";
-        	
-            // open the zip file stream
-            ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(iaasInfo.getPayload()));
-
-            try
-            {
-
-                // now iterate through each item in the stream. The get next
-                // entry call will return a ZipEntry for each file in the
-                // stream
-                ZipEntry entry;
-                while((entry = stream.getNextEntry())!=null)
-                {
-                	StringWriter writer = new StringWriter();
-                	IOUtils.copy(stream, writer);
-                	
-                	if(entry.getName().contains("launch-params")){
-                		launchParams = writer.toString();
-                	} else if(entry.getName().contains("id_rsa")){
-                		key = writer.toString();
-                	}
-                	
-                }
-            } catch (IOException e) {
-	            log.error(e.getMessage(), e);
-            }
-            finally
-            {
-                // we must always close the zip file.
-                try {
-	                stream.close();
-                } catch (IOException e) {
-
-                	log.error("failed to close the ZIP stream", e);
-                }
-            }
-            
-            script = "mkdir /var/lib/cloud && mkdir /var/lib/cloud/instance && mkdir /var/lib/cloud/instance/payload && " +
-            		 "echo \""+launchParams+"\" > /var/lib/cloud/instance/payload/launch-params && " +
-            		 "echo \""+key+"\" > /var/lib/cloud/instance/payload/id_rsa && " +
-            		 "cd /opt/ && " +
-            		 "chmod 755 wso2-openstack-init.sh && "+
-            		 "./wso2-openstack-init.sh";
-        	
-        	template.getOptions().overrideLoginUser(iaasInfo.getProperty("loginUser")).overrideLoginPassword(iaasInfo.getProperty("loginPassword")).runScript(script);
-        }
-
-    }
-
-    @Override
-    public boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
-        String publicKey) {
-        
-    	//TODO
-        return false;
-    }
-
-    @Override
-    public String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
-
-    	// TODO
-        return "";
-        
-    }
-
-	@Override
-    public void releaseAddress(IaasProvider iaasInfo, String ip) {
-		//TODO
-    }
-	
-}


[02/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
deleted file mode 100644
index dccd471..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.publisher;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.ComputeMetadata;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.internal.NodeMetadataImpl;
-import org.wso2.carbon.base.ServerConfiguration;
-import org.wso2.carbon.databridge.agent.thrift.Agent;
-import org.wso2.carbon.databridge.agent.thrift.DataPublisher;
-import org.wso2.carbon.databridge.agent.thrift.conf.AgentConfiguration;
-import org.wso2.carbon.databridge.commons.Event;
-import org.wso2.carbon.databridge.commons.exception.NoStreamDefinitionExistException;
-import org.wso2.carbon.ntask.core.Task;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.CartridgeInstanceData;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasContext;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import com.google.common.collect.MapDifference;
-import com.google.common.collect.MapDifference.ValueDifference;
-import com.google.common.collect.Maps;
-
-public class CartridgeInstanceDataPublisherTask implements Task{
-    
-    private static final Log log = LogFactory.getLog(CartridgeInstanceDataPublisherTask.class);
-    private static DataPublisher dataPublisher;
-    private static String streamId;
-    private static final String cloudControllerEventStreamVersion = "1.0.0";
-    private static List<CartridgeInstanceData> dataToBePublished ;
-
-    protected enum NodeStatus {
-        PENDING, RUNNING, SUSPENDED, TERMINATED, ERROR, UNRECOGNIZED
-    };   
-
-    @Override
-    public void execute() {
-        
-        publish();
-    }
-    
-    public static void publish(){
-        if(FasterLookUpDataHolder.getInstance().isPublisherRunning() ||
-                // this is a temporary fix to avoid task execution - limitation with ntask
-                !FasterLookUpDataHolder.getInstance().getEnableBAMDataPublisher()){
-            return;
-        }
-        
-        log.debug(CloudControllerConstants.DATA_PUB_TASK_NAME+" cycle started.");
-        FasterLookUpDataHolder.getInstance().setPublisherRunning(true);
-        dataToBePublished = new ArrayList<CartridgeInstanceData>();
-
-        if(dataPublisher==null){
-            createDataPublisher();
-
-            //If we cannot create a data publisher we should give up
-            //this means data will not be published
-            if(dataPublisher == null){
-                log.error("Data Publisher cannot be created or found.");
-                release();
-                return;
-            }
-        }
-
-        if(streamId == null){
-            try{
-                streamId = dataPublisher.findStream(CloudControllerConstants.CLOUD_CONTROLLER_EVENT_STREAM, cloudControllerEventStreamVersion);
-            }catch (NoStreamDefinitionExistException e){
-                log.info("Defining the event stream because it was not found in BAM");
-                try{
-                    defineStream();
-                } catch(Exception ex){
-                    String msg = "Error occurred while defining the event stream for publishing Cloud Controller data. " + ex.getMessage();
-                    log.error(msg, ex);
-                    //We do not want to proceed without an event stream. Therefore we return.
-                    release();
-                    return;
-                }
-            }catch (Exception exc){
-                log.error("Error occurred while searching for stream id. " + exc.getMessage(), exc);
-                //We do not want to proceed without an event stream. Therefore we return.
-                release();
-                return;
-            }
-        }
-        
-        // build the new node - state Map
-        Map<String, String> newNodeToStateMap;
-        try{
-            newNodeToStateMap = getNodeIdToStatusMap();
-        }catch (Exception e) {
-
-            release();
-            throw new CloudControllerException(e.getMessage(), e);
-            
-        } 
-        
-        // compare it with old map and populate data to be published with ones newly added
-        // and once whose state got changed
-        populateNewlyAddedOrStateChangedNodes(newNodeToStateMap);
-        
-        // issue events for the ones obtained from above
-        for (CartridgeInstanceData dataObj : dataToBePublished) {
-            StringBuffer temp = new StringBuffer("");
-            
-            String privateIpAddresses="";
-            // Concatenate private IP addresses
-            for (String ip : dataObj.getMetaData().getPrivateAddresses()) {
-                temp.append(ip+",");
-            }
-            
-            if(!"".equals(temp.toString())){
-                // remove comma at the end of the string
-                privateIpAddresses = temp.toString().substring(0, temp.toString().length()-1);
-            }
-            
-            temp = new StringBuffer("");
-            String publicIpAddresses="";
-            // Concatenate public IP addresses
-            for (String ip : dataObj.getMetaData().getPublicAddresses()) {
-                temp.append(ip+",");
-            }
-            
-            if(!"".equals(temp.toString())){
-                // remove comma at the end of the string
-                publicIpAddresses = temp.toString().substring(0, temp.toString().length()-1);
-            }
-            
-            try {
-
-                Event cloudControllerEvent = new Event(streamId, System.currentTimeMillis(), new Object[]{}, null,
-                                            new Object[]{dataObj.getNodeId(),
-                                                         dataObj.getType(),
-                                                         dataObj.getDomain(),
-                                                         dataObj.getSubDomain(),
-                                                         dataObj.getAlias(),
-                                                         dataObj.getTenantRange(),
-                                                         String.valueOf(dataObj.isMultiTenant()),
-                                                         dataObj.getIaas(),
-                                                         dataObj.getStatus(),
-                                                         dataObj.getMetaData().getHostname(),
-                                                         dataObj.getMetaData().getHardware().getHypervisor(),
-                                                         String.valueOf(dataObj.getMetaData().getHardware().getRam()),
-                                                         dataObj.getMetaData().getImageId(),
-                                                         String.valueOf(dataObj.getMetaData().getLoginPort()),
-                                                         dataObj.getMetaData().getOperatingSystem().getName(),
-                                                         dataObj.getMetaData().getOperatingSystem().getVersion(),
-                                                         dataObj.getMetaData().getOperatingSystem().getArch(),
-                                                         String.valueOf(dataObj.getMetaData().getOperatingSystem().is64Bit()),
-                                                         privateIpAddresses,
-                                                         publicIpAddresses});
-
-                dataPublisher.publish(cloudControllerEvent);
-                
-                log.debug("Data published : "+cloudControllerEvent.toString());
-
-            } catch (Exception e) {
-                String msg = "Error occurred while publishing Cartridge instance event to BAM. ";
-                log.error(msg, e);
-                release();
-                throw new CloudControllerException(msg, e);
-            }
-            
-        }
-        
-        // replace old map with new one only if data is published
-        FasterLookUpDataHolder.getInstance().setNodeIdToStatusMap(newNodeToStateMap);
-        
-        //TODO remove
-//        CassandraDataRetriever.init();
-//        CassandraDataRetriever.connect();
-//        HiveQueryExecutor hive = new HiveQueryExecutor();
-//        hive.createHiveTable();
-//        System.out.println("***********");
-//        for (String str : hive.getRunningNodeIds()) {
-//         
-//            System.out.println(str);
-//        }
-//        System.out.println("***********");
-        release();
-    }
-    
-    private static void release(){
-        FasterLookUpDataHolder.getInstance().setPublisherRunning(false);
-    }
-    
-    private static void defineStream() throws Exception {
-        streamId = dataPublisher.
-                defineStream("{" +
-                        "  'name':'" + CloudControllerConstants.CLOUD_CONTROLLER_EVENT_STREAM +"'," +
-                        "  'version':'" + cloudControllerEventStreamVersion +"'," +
-                        "  'nickName': 'cloud.controller'," +
-                        "  'description': 'Instances booted up by the Cloud Controller '," +
-                        "  'metaData':[]," +
-                        "  'payloadData':[" +
-                        "          {'name':'"+CloudControllerConstants.NODE_ID_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.CARTRIDGE_TYPE_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.DOMAIN_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.SUB_DOMAIN_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.ALIAS_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.TENANT_RANGE_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.IS_MULTI_TENANT_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.IAAS_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.STATUS_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.HOST_NAME_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.HYPERVISOR_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.RAM_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.IMAGE_ID_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.LOGIN_PORT_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.OS_NAME_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.OS_VERSION_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.OS_ARCH_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.OS_BIT_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.PRIV_IP_COL+"','type':'STRING'}," +
-                        "          {'name':'"+CloudControllerConstants.PUB_IP_COL+"','type':'STRING'}" +
-                        "  ]" +
-                        "}");
-        
-    }
-
-    @Override
-    public void init() {
-
-    	// this is a temporary fix to avoid task execution - limitation with ntask
-		if(!FasterLookUpDataHolder.getInstance().getEnableBAMDataPublisher()){
-			log.debug("BAM data publisher is disabled. ");
-			return;
-		}
-		
-        if((dataPublisher = FasterLookUpDataHolder.getInstance().getDataPublisher()) == null){
-            createDataPublisher();
-        }
-        streamId = FasterLookUpDataHolder.getInstance().getStreamId();
-        
-    }
-
-    @Override
-    public void setProperties(Map<String, String> arg0) {}
-    
-    private static void createDataPublisher(){
-        //creating the agent
-        AgentConfiguration agentConfiguration = new AgentConfiguration();
-
-        ServerConfiguration serverConfig =  CarbonUtils.getServerConfiguration();
-        String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
-        String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");
-        String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");
-        String adminUsername = FasterLookUpDataHolder.getInstance().getBamUsername();
-        String adminPassword = FasterLookUpDataHolder.getInstance().getBamPassword();
-
-        System.setProperty("javax.net.ssl.trustStore", trustStorePath);
-        System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
-
-        Agent agent = new Agent(agentConfiguration);
-
-        try {
-            dataPublisher = new DataPublisher(bamServerUrl, adminUsername, adminPassword, agent);
-            FasterLookUpDataHolder.getInstance().setDataPublisher(dataPublisher);
-            
-        } catch (Exception e) {
-            String msg = "Unable to create a data publisher to " + bamServerUrl +
-                    ". Usage Agent will not function properly. ";
-            log.error(msg, e);
-            throw new CloudControllerException(msg, e);
-        }
-        
-    }
-    
-    private static void bundleData(String key, String val, ServiceContext serviceCtxt) {
-        
-        CartridgeInstanceData instanceData = new CartridgeInstanceData();
-        instanceData.setNodeId(key);
-        instanceData.setStatus(val);
-        instanceData.setDomain(serviceCtxt.getDomainName());
-        instanceData.setSubDomain(serviceCtxt.getSubDomainName());
-        instanceData.setAlias("".equals(serviceCtxt.getProperty(CloudControllerConstants.ALIAS_PROPERTY))
-            ? "NULL"
-                : serviceCtxt.getProperty(CloudControllerConstants.ALIAS_PROPERTY));
-        instanceData.setTenantRange("".equals(serviceCtxt.getProperty(CloudControllerConstants.TENANT_ID_PROPERTY))
-            ? serviceCtxt.getTenantRange()
-                : serviceCtxt.getProperty(CloudControllerConstants.TENANT_ID_PROPERTY));
-        
-        if (serviceCtxt.getCartridge() != null) {
-            instanceData.setMultiTenant(serviceCtxt.getCartridge().isMultiTenant());
-
-            for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
-
-                IaasContext ctxt = null;
-                if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
-                    ctxt = serviceCtxt.addIaasContext(iaas.getType());
-                }
-
-                if (ctxt.didISpawn(key)) {
-                    instanceData.setIaas(iaas.getType());
-                    instanceData.setMetaData(ctxt.getNode(key));
-
-                    // clear to be removed data
-                    ctxt.removeToBeRemovedNodeId(key);
-
-                    // if the node is terminated
-                    if (val.equals(NodeStatus.TERMINATED.toString())) {
-                        // since this node is terminated
-                        FasterLookUpDataHolder.getInstance().removeNodeId(key);
-
-                        // remove node meta data
-                        ctxt.removeNodeMetadata(ctxt.getNode(key));
-                    }
-
-                    break;
-                }
-            }
-
-            instanceData.setType(serviceCtxt.getCartridge().getType());
-        } else {
-            log.warn("Cartridge is null for Service Context : (domain: " +
-                serviceCtxt.getDomainName() +
-                    ", sub domain: " +
-                    serviceCtxt.getSubDomainName() +
-                    ")");
-        }
-        
-        dataToBePublished.add(instanceData);
-        
-    }
-    
-    private static Map<String, String> getNodeIdToStatusMap() throws Exception {
-        
-        Map<String, String> statusMap = new HashMap<String, String>();
-        
-        // iterate through all ServiceContexts
-        for (Iterator<?> it1 = FasterLookUpDataHolder.getInstance().getServiceContexts().entrySet().iterator(); it1.hasNext();) {
-            @SuppressWarnings("unchecked")
-            Map.Entry<String, Map<String, ServiceContext>> entry = (Map.Entry<String, Map<String, ServiceContext>>) it1.next();
-            
-            Map<String, ServiceContext> map = (Map<String, ServiceContext>) entry.getValue();
-            
-            for (Iterator<ServiceContext> it2 = map.values().iterator(); it2.hasNext();) {
-                ServiceContext subjectedSerCtxt = (ServiceContext) it2.next();
-                
-                if (subjectedSerCtxt != null && subjectedSerCtxt.getCartridge() != null) {
-                    List<IaasProvider> iaases = subjectedSerCtxt.getCartridge().getIaases();
-
-                    for (IaasProvider iaas : iaases) {
-
-                        ComputeService computeService = iaas.getComputeService();
-                        
-                        if(computeService == null){
-                            continue;
-                        }
-                        
-                        IaasContext ctxt = null;
-                        if((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null){
-                        	ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
-                        }
-
-                        // get list of node Ids
-                        List<String> nodeIds = ctxt.getAllNodeIds();
-
-                        if (nodeIds.isEmpty()) {
-                            
-                            continue;
-                        }
-                        
-                        try {
-
-                            // get all the nodes spawned by this IaasContext
-                            Set<? extends ComputeMetadata> set = computeService.listNodes();
-
-                            Iterator<? extends ComputeMetadata> iterator = set.iterator();
-
-                            // traverse through all nodes of this ComputeService object
-                            while (iterator.hasNext()) {
-                                NodeMetadata nodeMetadata = (NodeMetadataImpl) iterator.next();
-
-                                // if this node belongs to the requested domain
-                                if (nodeIds.contains(nodeMetadata.getId())) {
-
-                                    statusMap.put(nodeMetadata.getId(), nodeMetadata.getStatus()
-                                                                                    .toString());
-
-                                    ctxt.addNodeMetadata(nodeMetadata);
-                                }
-
-                            }
-
-                        }catch (Exception e) {
-                            log.error(e.getMessage(), e);
-                            throw e;
-                        }
-
-                    }
-                }
-            }
-            
-            
-        }
-        return statusMap;
-
-    }
-    
-    private static void populateNewlyAddedOrStateChangedNodes(Map<String, String> newMap){
-        
-        MapDifference<String, String> diff = Maps.difference(newMap, 
-                                                             FasterLookUpDataHolder.getInstance().getNodeIdToStatusMap());
-        
-        // adding newly added nodes
-        Map<String, String> newlyAddedNodes = diff.entriesOnlyOnLeft();
-        
-        for (Iterator<?> it = newlyAddedNodes.entrySet().iterator(); it.hasNext();) {
-            @SuppressWarnings("unchecked")
-            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
-            String key = entry.getKey();
-            String val = entry.getValue();
-            ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);
-            
-            log.debug("------ Node id: "+key+" --- node status: "+val+" -------- ctxt: "+ctxt);
-            
-            if (ctxt != null && key != null && val != null) {
-                // bundle the data to be published
-                bundleData(key, val, ctxt);
-            }   
-                    
-        }
-        
-        // adding nodes with state changes
-        Map<String, ValueDifference<String>> stateChangedNodes = diff.entriesDiffering();
-        
-        for (Iterator<?> it = stateChangedNodes.entrySet().iterator(); it.hasNext();) {
-            @SuppressWarnings("unchecked")
-            Map.Entry<String, ValueDifference<String>> entry = (Map.Entry<String, ValueDifference<String>>) it.next();
-            
-            String key = entry.getKey();
-            String newState = entry.getValue().leftValue();
-            ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);
-            
-            log.debug("------- Node id: "+key+" --- node status: "+newState+" -------- ctxt: "+ctxt);
-            
-            if (ctxt != null && key != null && newState != null) {
-                // bundle the data to be published
-                bundleData(key, newState, ctxt);
-            }  
-            
-        }
-
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java
deleted file mode 100644
index 8d86d67..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java
+++ /dev/null
@@ -1,101 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.registry;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.registry.core.Registry;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.persist.Serializer;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
-import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException;
-
-/**
- *
- */
-public class RegistryManager {
-	private final static Log log = LogFactory.getLog(RegistryManager.class);
-	private static Registry registryService;
-	private static RegistryManager registryManager;
-	
-	public static RegistryManager getInstance() {
-
-		registryService = DeclarativeServiceReferenceHolder.getInstance().getRegistry();
-				
-		if (registryManager == null) {
-			synchronized(RegistryManager.class){
-				if (registryManager == null) {
-					if(registryService == null){
-//						log.warn("Registry Service is null. Hence unable to fetch data from registry.");
-						return registryManager;
-					}
-					registryManager = new RegistryManager();
-				}
-			}
-		}
-
-		return registryManager;
-	}
-	
-	private RegistryManager() {
-		try {
-			if (!registryService.resourceExists(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE)) {
-				registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE,
-				                    registryService.newCollection());
-			}
-		} catch (RegistryException e) {
-			String msg =
-			             "Failed to create the registry resource " +
-			                     CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE;
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-	}
-
-	/**
-     * Persist an object in the local registry.
-     * @param dataObj object to be persisted.
-     */
-	public void persist(FasterLookUpDataHolder dataObj) throws RegistryException {
-		try {
-
-			registryService.beginTransaction();
-			
-			Resource nodeResource = registryService.newResource();
-
-			nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
-
-			registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE, nodeResource);
-			
-			registryService.commitTransaction();
-			
-		} catch (Exception e) {
-			String msg = "Failed to persist the cloud controller data in registry.";
-			registryService.rollbackTransaction();
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-			
-		} 
-	}
-	
-	public Object retrieve(){
-		
-		try {
-	        Resource resource = registryService.get(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE);
-	        
-	        return resource.getContent();
-	        
-        } catch (ResourceNotFoundException ignore) {
-        	// this means, we've never persisted CC info in registry
-        	return null;
-        }catch (RegistryException e) {
-        	String msg = "Failed to retrieve cloud controller data from registry.";
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-        }
-		
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back
deleted file mode 100644
index 3ab6681..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back
+++ /dev/null
@@ -1,96 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.registry;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.registry.core.Registry;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.persist.Serializer;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerServiceReferenceHolder;
-
-/**
- *
- */
-public class RegistryManager {
-	private final static Log log = LogFactory.getLog(RegistryManager.class);
-	private static Registry registryService = CloudControllerServiceReferenceHolder.getInstance().getRegistry();
-	private static RegistryManager registryManager;
-	
-	public static RegistryManager getInstance() {
-
-		if (registryManager == null) {
-			synchronized(RegistryManager.class){
-				if (registryManager == null) {
-					if(registryService == null){
-						log.warn("Registry Service is null. Hence unable to fetch data from registry.");
-						return registryManager;
-					}
-					registryManager = new RegistryManager();
-				}
-			}
-		}
-
-		return registryManager;
-	}
-	
-	private RegistryManager() {
-		try {
-			if (!registryService.resourceExists(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE)) {
-				registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE,
-				                    registryService.newCollection());
-			}
-		} catch (RegistryException e) {
-			String msg =
-			             "Failed to create the registry resource " +
-			                     CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE;
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-	}
-
-	/**
-     * Persist a node id in the local registry.
-     * @param nodeId node id to be persisted.
-     */
-	public void persist(Object dataObj) throws RegistryException {
-		try {
-
-			registryService.beginTransaction();
-			
-			Resource nodeResource = registryService.newResource();
-
-			nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
-
-			registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE, nodeResource);
-			
-			registryService.commitTransaction();
-			
-		} catch (Exception e) {
-			String msg = "Failed to persist the cloud controller data in registry.";
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-			
-		} finally{
-			registryService.rollbackTransaction();
-			
-		}
-	}
-	
-	public Object retrieve(){
-		
-		try {
-	        Resource resource = registryService.get(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE);
-	        
-	        return resource.getContent();
-	        
-        } catch (RegistryException e) {
-        	String msg = "Failed to retrieve cloud controller data from registry.";
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-        }
-		
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
deleted file mode 100644
index d990738..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.runtime;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.wso2.carbon.databridge.agent.thrift.DataPublisher;
-import org.wso2.carbon.stratos.cloud.controller.registry.RegistryManager;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
-import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
-import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
-
-/**
- * This object holds all runtime data and provides faster access. This is a Singleton class.
- */
-public class FasterLookUpDataHolder implements Serializable{
-
-    private static final long serialVersionUID = -2662307358852779897L;
-
-	private static volatile FasterLookUpDataHolder ctxt;
-
-	/* We keep following maps in order to make the look up time, small. */
-
-	/**
-	 * Map of maps.
-	 * Map 1:
-	 * Key - domain
-	 * Value - is another map
-	 * Map 2:
-	 * key - sub domain
-	 * value - {@link ServiceContext}
-	 */
-	private Map<String, Map<String, ServiceContext>> serviceCtxts;
-	
-	/**
-	 * To make data retrieval from registry faster.
-	 */
-	private List<ServiceContext> serviceCtxtList;
-
-	public List<ServiceContext> getServiceCtxtList() {
-    	return serviceCtxtList;
-    }
-
-	/**
-	 * Key - node id
-	 * Value - {@link ServiceContext}
-	 */
-	private Map<String, ServiceContext> nodeIdToServiceCtxt;
-	
-	/**
-	 * List of registered {@link Cartridge}s
-	 */
-	private List<Cartridge> cartridges;
-
-	/**
-	 * List of IaaS Providers.
-	 */
-	private List<IaasProvider> iaasProviders;
-
-	private String serializationDir;
-	private boolean enableBAMDataPublisher;
-	private boolean enableTopologySync;
-	private String bamUsername = CloudControllerConstants.DEFAULT_BAM_SERVER_USER_NAME;
-	private String bamPassword = CloudControllerConstants.DEFAULT_BAM_SERVER_PASSWORD;
-	private String dataPublisherCron = CloudControllerConstants.PUB_CRON_EXPRESSION;
-	private String cassandraConnUrl = CloudControllerConstants.DEFAULT_CASSANDRA_URL;
-	private String cassandraUser = CloudControllerConstants.DEFAULT_CASSANDRA_USER;
-	private String cassandraPassword = CloudControllerConstants.DEFAULT_CASSANDRA_PASSWORD;
-	/**
-	 * Key - node id 
-	 * Value - Status of the instance
-	 * This map is only used by BAM data publisher in CC.
-	 */
-	private Map<String, String> nodeIdToStatusMap = new HashMap<String, String>();
-	private transient DataPublisher dataPublisher;
-	private String streamId;
-	private boolean isPublisherRunning;
-	private boolean isTopologySyncRunning;
-	private String topologySynchronizerCron = CloudControllerConstants.TOPOLOGY_SYNC_CRON;
-
-	private BlockingQueue<List<ServiceContext>> sharedTopologyDiffQueue = new LinkedBlockingQueue<List<ServiceContext>>();
-
-
-	private String mbServerUrl = CloudControllerConstants.MB_SERVER_URL;
-
-	public static FasterLookUpDataHolder getInstance() {
-
-		if (ctxt == null) {
-			synchronized (FasterLookUpDataHolder.class) {
-				if (ctxt == null && RegistryManager.getInstance() != null) {
-
-					Object obj = RegistryManager.getInstance().retrieve();
-					if (obj != null) {
-						if (obj instanceof FasterLookUpDataHolder) {
-							ctxt = (FasterLookUpDataHolder) obj;
-							System.out.println("*********** FasterLookUpDataHolder ********");
-						} else {
-							System.out.println("*********** Not a FasterLookUpDataHolder *******");
-						}
-
-					} 
-					
-				}
-				if(ctxt == null) {
-					ctxt = new FasterLookUpDataHolder();
-				}
-			}
-		}
-
-		return ctxt;
-	}
-
-	private FasterLookUpDataHolder() {
-
-		serviceCtxtList = new ArrayList<ServiceContext>();
-		serviceCtxts = new ConcurrentHashMap<String, Map<String, ServiceContext>>();
-		nodeIdToServiceCtxt = new LinkedHashMap<String, ServiceContext>();
-		cartridges = new ArrayList<Cartridge>();
-
-	}
-
-	public void addServiceContext(ServiceContext ctx) {
-
-		if (ctx == null) {
-			return;
-		}
-
-		String domain = ctx.getDomainName();
-		String subDomain = ctx.getSubDomainName();
-
-		if (domain != null && subDomain != null) {
-			addToServiceCtxts(domain, subDomain, ctx);
-		}
-
-	}
-
-	public void removeServiceContext(ServiceContext ctxt) {
-
-		if (ctxt == null) {
-			return;
-		}
-
-		String domain = ctxt.getDomainName();
-		String subDomain = ctxt.getSubDomainName();
-
-		if (domain != null && subDomain != null) {
-			if (serviceCtxts.containsKey(domain)) {
-				Map<String, ServiceContext> subDomainMap = serviceCtxts.get(domain);
-				subDomainMap.remove(subDomain);
-			}
-		}
-		
-		serviceCtxtList.remove(ctxt);
-
-	}
-
-	public ServiceContext getServiceContext(String domain, String subDomain) {
-
-		if (serviceCtxts.get(domain) != null) {
-			return serviceCtxts.get(domain).get(subDomain);
-		}
-		return null;
-	}
-
-	public ServiceContext getServiceContext(String nodeId) {
-
-		return nodeIdToServiceCtxt.get(nodeId);
-	}
-	
-	public List<Object> getNodeIdsOfServiceCtxt(ServiceContext ctxt){
-		return CloudControllerUtil.getKeysFromValue(nodeIdToServiceCtxt, ctxt);
-	}
-
-	public Map<String, Map<String, ServiceContext>> getServiceContexts() {
-		return serviceCtxts;
-	}
-
-	public void addNodeId(String nodeId, ServiceContext ctxt) {
-		nodeIdToServiceCtxt.put(nodeId, ctxt);
-	}
-
-	public void removeNodeId(String nodeId) {
-		nodeIdToServiceCtxt.remove(nodeId);
-	}
-	
-	public void setNodeIdToServiceContextMap(Map<String, ServiceContext> map) {
-		nodeIdToServiceCtxt = map;
-	}
-
-	public Map<String, ServiceContext> getNodeIdToServiceContextMap() {
-		return nodeIdToServiceCtxt;
-	}
-
-	private void addToServiceCtxts(String domainName, String subDomainName, ServiceContext ctxt) {
-
-		Map<String, ServiceContext> map;
-
-		if (serviceCtxts.get(domainName) == null) {
-			map = new HashMap<String, ServiceContext>();
-
-		} else {
-			map = serviceCtxts.get(domainName);
-		}
-
-		map.put(subDomainName, ctxt);
-		serviceCtxts.put(domainName, map);
-		
-		serviceCtxtList.add(ctxt);
-
-	}
-
-	public List<Cartridge> getCartridges() {
-		return cartridges;
-	}
-
-	public Cartridge getCartridge(String cartridgeType) {
-		for (Cartridge cartridge : cartridges) {
-			if (cartridge.getType().equals(cartridgeType)) {
-				return cartridge;
-			}
-		}
-
-		return null;
-
-	}
-
-//	public void addCartridges(List<Cartridge> newCartridges) {
-//		if (this.cartridges == null) {
-//			this.cartridges = newCartridges;
-//		} else {
-//			for (Cartridge cartridge : newCartridges) {
-//				int idx;
-//				if ((idx = cartridges.indexOf(cartridge)) != -1) {
-//					Cartridge ref = cartridges.get(idx);
-//					ref = cartridge;
-//				} else {
-//					cartridges.add(cartridge);
-//				}
-//			}
-//		}
-//
-//	}
-	
-	public void addCartridge(Cartridge newCartridges) {
-	
-		cartridges.add(newCartridges);
-	}
-
-	public void removeCartridges(List<Cartridge> cartridges) {
-		if (this.cartridges != null) {
-			this.cartridges.removeAll(cartridges);
-		}
-
-	}
-
-	public List<IaasProvider> getIaasProviders() {
-		return iaasProviders;
-	}
-
-	public void setIaasProviders(List<IaasProvider> iaasProviders) {
-		this.iaasProviders = iaasProviders;
-	}
-
-	public String getSerializationDir() {
-		return serializationDir;
-	}
-
-	public void setSerializationDir(String serializationDir) {
-		this.serializationDir = serializationDir;
-	}
-
-	public String getBamUsername() {
-		return bamUsername;
-	}
-
-	public void setBamUsername(String bamUsername) {
-		this.bamUsername = bamUsername;
-	}
-
-	public String getBamPassword() {
-		return bamPassword;
-	}
-
-	public void setBamPassword(String bamPassword) {
-		this.bamPassword = bamPassword;
-	}
-
-	public String getDataPublisherCron() {
-		return dataPublisherCron;
-	}
-
-	public void setDataPublisherCron(String dataPublisherCron) {
-		this.dataPublisherCron = dataPublisherCron;
-	}
-
-	public Map<String, String> getNodeIdToStatusMap() {
-		return nodeIdToStatusMap;
-	}
-
-	public void setNodeIdToStatusMap(Map<String, String> nodeIdToStatusMap) {
-		this.nodeIdToStatusMap = nodeIdToStatusMap;
-	}
-
-	public DataPublisher getDataPublisher() {
-		return dataPublisher;
-	}
-
-	public void setDataPublisher(DataPublisher dataPublisher) {
-		this.dataPublisher = dataPublisher;
-	}
-
-	public String getStreamId() {
-		return streamId;
-	}
-
-	public void setStreamId(String streamId) {
-		this.streamId = streamId;
-	}
-
-	public boolean getEnableBAMDataPublisher() {
-		return enableBAMDataPublisher;
-	}
-
-	public void setEnableBAMDataPublisher(boolean enableBAMDataPublisher) {
-		this.enableBAMDataPublisher = enableBAMDataPublisher;
-	}
-
-	public String getCassandraConnUrl() {
-		return cassandraConnUrl;
-	}
-
-	public void setCassandraConnUrl(String cassandraHostAddr) {
-		this.cassandraConnUrl = cassandraHostAddr;
-	}
-
-	public String getCassandraUser() {
-		return cassandraUser;
-	}
-
-	public void setCassandraUser(String cassandraUser) {
-		this.cassandraUser = cassandraUser;
-	}
-
-	public String getCassandraPassword() {
-		return cassandraPassword;
-	}
-
-	public void setCassandraPassword(String cassandraPassword) {
-		this.cassandraPassword = cassandraPassword;
-	}
-
-	public boolean isPublisherRunning() {
-		return isPublisherRunning;
-	}
-
-	public void setPublisherRunning(boolean isPublisherRunning) {
-		this.isPublisherRunning = isPublisherRunning;
-	}
-
-	public BlockingQueue<List<ServiceContext>> getSharedTopologyDiffQueue() {
-		return sharedTopologyDiffQueue;
-	}
-
-	public void setSharedTopologyDiffQueue(BlockingQueue<List<ServiceContext>> sharedTopologyDiffQueue) {
-		this.sharedTopologyDiffQueue = sharedTopologyDiffQueue;
-	}
-
-	public String getTopologySynchronizerCron() {
-		return topologySynchronizerCron;
-	}
-
-	public void setTopologySynchronizerCron(String topologySynchronizerCron) {
-		this.topologySynchronizerCron = topologySynchronizerCron;
-	}
-
-	public void setMBServerUrl(String ip) {
-		this.mbServerUrl = ip;
-	}
-
-	public String getMBServerUrl() {
-		return mbServerUrl;
-	}
-
-	public boolean getEnableTopologySync() {
-		return enableTopologySync;
-	}
-
-	public void setEnableTopologySync(boolean enableTopologySync) {
-		this.enableTopologySync = enableTopologySync;
-	}
-
-	public boolean isTopologySyncRunning() {
-	    return isTopologySyncRunning;
-    }
-
-	public void setTopologySyncRunning(boolean isTopologySyncRunning) {
-	    this.isTopologySyncRunning = isTopologySyncRunning;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java
deleted file mode 100644
index 20ac038..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.topic;
-
-import java.util.Properties;
-
-import javax.jms.*;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-
-public class ConfigurationPublisher {
-	private TopicPublisher topicPublisher;
-	private TopicSession topicSession;
-	private TopicConnection topicConnection;
-	private TopicConnectionFactory topicConnectionFactory;
-	private static final Log log = LogFactory.getLog(ConfigurationPublisher.class);
-	
-	
-	public ConfigurationPublisher() {
-	    
-		Properties initialContextProperties = new Properties();
-		initialContextProperties.put("java.naming.factory.initial",
-				"org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
-		String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://"+FasterLookUpDataHolder.getInstance().getMBServerUrl()+"'";
-		initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
-		
-		try {
-			InitialContext initialContext = new InitialContext(initialContextProperties);
-			topicConnectionFactory =
-					(TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
-			
-//			topicConnection.stop();
-//			topicConnection.close();
-			
-		} catch (NamingException e) {
-			log.error(e.getMessage(), e);
-		} 
-    }
-
-	
-	public void publish(String topicName, String message) {
-		try {
-			topicConnection = topicConnectionFactory.createTopicConnection();
-			topicConnection.start();
-			topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
-
-			Topic topic = topicSession.createTopic(topicName);
-			topicPublisher = topicSession.createPublisher(topic);
-			TextMessage textMessage = topicSession.createTextMessage(message);
-
-			topicPublisher.publish(textMessage);
-			
-			topicPublisher.close();
-			topicSession.close();
-			topicConnection.stop();
-			topicConnection.close();
-			
-		}  catch (JMSException e) {
-			log.error(e.getMessage(), e);
-		}
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java
deleted file mode 100644
index 6a9c155..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.topic;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.ntask.core.Task;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
-import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
-
-public class TopologySynchronizerTask implements Task{
-    
-    private static final Log log = LogFactory.getLog(TopologySynchronizerTask.class);
-    private DeclarativeServiceReferenceHolder data = DeclarativeServiceReferenceHolder.getInstance();
-    private File topologyFile;
-    
-    @Override
-    public void execute() {
-    	if(FasterLookUpDataHolder.getInstance().isTopologySyncRunning()||
-        		// this is a temporary fix to avoid task execution - limitation with ntask
-        		!FasterLookUpDataHolder.getInstance().getEnableTopologySync()){
-            return;
-        }
-    	
-    	log.debug("TopologySynchronizerTask ... ");
-        
-    	// publish to the topic 
-		try {
-			if (topologyFile.exists()) {
-				data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME,
-				                               FileUtils.readFileToString(topologyFile));
-			}
-		} catch (IOException e) {
-        	String msg = "Failed when publishing to the topic "+CloudControllerConstants.TOPIC_NAME+
-        			" - Reason : Failed while reading topology from "+topologyFile.getAbsolutePath();
-        	log.error(msg, e);
-        	throw new CloudControllerException(msg, e);
-        }
-    }
-    
-    @Override
-    public void init() {
-
-    	// this is a temporary fix to avoid task execution - limitation with ntask
-		if(!FasterLookUpDataHolder.getInstance().getEnableTopologySync()){
-			log.debug("Topology Sync is disabled.");
-			return;
-		}
-    	
-    	topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
-        
-    }
-
-    @Override
-    public void setProperties(Map<String, String> arg0) {}
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java
deleted file mode 100644
index ee8e209..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.Serializable;
-
-/**
- * domain mapping related data.
- *
- */
-public class AppType implements Serializable{
-	
-    private static final long serialVersionUID = 3550489774139807168L;
-	private String name;
-	private boolean appSpecificMapping = true;
-	
-	public AppType(){
-		
-	}
-	
-	public AppType(String name){
-		this.setName(name);
-	}
-	
-	public AppType(String name, boolean appSpecificMapping){
-		this.setName(name);
-		this.setAppSpecificMapping(appSpecificMapping);
-	}
-
-	public String getName() {
-	    return name;
-    }
-
-	public void setName(String name) {
-	    this.name = name;
-    }
-
-	public boolean isAppSpecificMapping() {
-	    return appSpecificMapping;
-    }
-
-	public void setAppSpecificMapping(boolean appSpecificMapping) {
-	    this.appSpecificMapping = appSpecificMapping;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java
deleted file mode 100644
index c9042fa..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-
-/**
- * Holds information regarding a Cartridge.
- */
-public class Cartridge implements Serializable{
-
-    private static final long serialVersionUID = 6637409027085059072L;
-
-	private String type;
-    
-    private String hostName;
-    
-    private String provider;
-    
-    private String displayName;
-    
-    private String description;
-    
-    private String baseDir;
-    
-    private String version;
-    
-    private boolean multiTenant;
-    
-    private List<PortMapping> portMappings = new ArrayList<PortMapping>();
-    
-    private List<AppType> appTypeMappings = new ArrayList<AppType>();
-    
-    /**
-     * Property map of this Cartridge.
-     */
-    private Map<String, String> properties = new HashMap<String, String>();
-    
-    /**
-     * A Cartridge can have 1..n {@link IaasProvider}s
-     */
-    private List<IaasProvider> iaases = new ArrayList<IaasProvider>();
-    
-    private List<String> deploymentDirs = new ArrayList<String>();
-    
-    private IaasProvider lastlyUsedIaas;
-    
-    public Cartridge(){}
-    
-    public Cartridge(String type, String host, String provider, String version, boolean multiTenant) {
-        this.type = type;
-        this.hostName = host;
-        this.provider = provider;
-        this.version = version;
-        this.multiTenant = multiTenant;
-    }
-
-    public String getType() {
-        return type;
-    }
-
-    public void setType(String type) {
-        this.type = type;
-    }
-
-    public Map<String, String> getProperties() {
-        return properties;
-    }
-    
-    public String getProperty(String key) {
-        return properties.get(key);
-    }
-
-    public void setProperties(Map<String, String> properties) {
-        this.properties = properties;
-    }
-    
-    public void addIaasProvider(IaasProvider iaas) {
-        for (IaasProvider anIaas : iaases) {
-            if(anIaas.equals(iaas)){
-                int idx = iaases.indexOf(anIaas);
-                iaases.remove(idx);
-                iaases.add(idx, iaas);
-                return;
-            }
-        }
-        this.iaases.add(iaas);
-    }
-    
-    public IaasProvider getIaasProvider(String iaasType){
-    	for (IaasProvider iaas : iaases) {
-	        if(iaas.getType().equals(iaasType)){
-	        	return iaas;
-	        }
-        }
-    	
-    	return null;
-    }
-
-    public List<IaasProvider> getIaases() {
-        return iaases;
-    }
-
-    public void setIaases(List<IaasProvider> iaases) {
-        this.iaases = iaases;
-    }
-    
-	public boolean equals(Object obj) {
-		if (obj instanceof Cartridge) {
-			return this.type.equals(((Cartridge)obj).getType());
-		}
-		return false;
-	}
-    
-    public int hashCode() {
-        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
-            append(type).
-            toHashCode();
-    }
-
-    public IaasProvider getLastlyUsedIaas() {
-        return lastlyUsedIaas;
-    }
-
-    public void setLastlyUsedIaas(IaasProvider lastlyUsedIaas) {
-        this.lastlyUsedIaas = lastlyUsedIaas;
-    }
-
-//    public boolean isJcloudsObjectsBuilt() {
-//        return isJcloudsObjectsBuilt;
-//    }
-//
-//    public void setJcloudsObjectsBuilt(boolean isJcloudsObjectsBuilt) {
-//        this.isJcloudsObjectsBuilt = isJcloudsObjectsBuilt;
-//    }
-
-	public String getDisplayName() {
-		return displayName;
-	}
-
-	public void setDisplayName(String displayName) {
-		this.displayName = displayName;
-	}
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-	public String getHostName() {
-	    return hostName;
-    }
-
-	public void setHostName(String hostName) {
-	    this.hostName = hostName;
-    }
-	
-	public void reset(){
-//		lastlyUsedIaas = null;
-	}
-
-	public List<String> getDeploymentDirs() {
-	    return deploymentDirs;
-    }
-
-	public void setDeploymentDirs(List<String> deploymentDirs) {
-	    this.deploymentDirs = deploymentDirs;
-    }
-	
-	public void addDeploymentDir(String dir){
-		deploymentDirs.add(dir);
-	}
-	
-	public void addPortMapping(PortMapping mapping){
-		portMappings.add(mapping);
-	}
-	
-	public void addAppType(AppType type){
-		appTypeMappings.add(type);
-	}
-
-	public String getProvider() {
-	    return provider;
-    }
-
-	public void setProvider(String provider) {
-	    this.provider = provider;
-    }
-
-	public String getVersion() {
-		return version;
-	}
-
-	public void setVersion(String version) {
-		this.version = version;
-	}
-
-	public boolean isMultiTenant() {
-		return multiTenant;
-	}
-
-	public void setMultiTenant(boolean multiTenant) {
-		this.multiTenant = multiTenant;
-	}
-
-	public String getBaseDir() {
-	    return baseDir;
-    }
-
-	public void setBaseDir(String baseDir) {
-	    this.baseDir = baseDir;
-    }
-
-	public List<PortMapping> getPortMappings() {
-	    return portMappings;
-    }
-
-	public void setPortMappings(List<PortMapping> portMappings) {
-	    this.portMappings = portMappings;
-    }
-
-	public List<AppType> getAppTypeMappings() {
-    	return appTypeMappings;
-    }
-
-	public void setAppTypeMappings(List<AppType> appTypeMappings) {
-    	this.appTypeMappings = appTypeMappings;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java
deleted file mode 100644
index fd02233..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Holds useful information for externals, regarding a Cartridge.
- */
-public class CartridgeInfo {
-
-    private String type;
-    
-    private String hostName;
-    
-    private String displayName;
-    
-    private String description;
-    
-    private String[] deploymentDirs;
-    
-    private PortMapping[] portMappings;
-    
-    private AppType[] appTypes;
-    
-    private String provider;
-    
-    private String version;
-    
-    private boolean multiTenant;
-    
-    private String baseDir;
-    
-    private Property[] properties;
-    
-    public CartridgeInfo(){
-    	
-    }
-    
-    public CartridgeInfo(String type, String host, String desc, List<String> deploymentDirs, String provider) {
-        this.type = type;
-        this.hostName = host;
-    }
-
-    public String getType() {
-        return type;
-    }
-
-    public void setType(String type) {
-        this.type = type;
-    }
-
-    public String getDisplayName() {
-		return displayName;
-	}
-
-	public void setDisplayName(String displayName) {
-		this.displayName = displayName;
-	}
-
-	public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-	public String getHostName() {
-	    return hostName;
-    }
-
-	public void setHostName(String hostName) {
-	    this.hostName = hostName;
-    }
-
-	public String[] getDeploymentDirs() {
-	    return deploymentDirs;
-    }
-
-	public void setDeploymentDirs(List<String> deploymentDirsList) {
-		if(deploymentDirsList == null){
-			deploymentDirsList = new ArrayList<String>();
-		}
-	    this.deploymentDirs = new String[deploymentDirsList.size()];
-	    
-	    deploymentDirsList.toArray(deploymentDirs);
-	    
-    }
-	
-    public String getProvider() {
-	    return provider;
-    }
-
-	public void setProvider(String provider) {
-	    this.provider = provider;
-    }
-
-	public String getVersion() {
-		return version;
-	}
-
-	public void setVersion(String version) {
-		this.version = version;
-	}
-
-	public boolean isMultiTenant() {
-		return multiTenant;
-	}
-
-	public void setMultiTenant(boolean multiTenant) {
-		this.multiTenant = multiTenant;
-	}
-
-	public String getBaseDir() {
-	    return baseDir;
-    }
-
-	public void setBaseDir(String baseDir) {
-	    this.baseDir = baseDir;
-    }
-
-	public PortMapping[] getPortMappings() {
-	    return portMappings;
-    }
-
-	public void setPortMappings(PortMapping[] portMappings) {
-	    this.portMappings = portMappings;
-    }
-
-	public AppType[] getAppTypes() {
-	    return appTypes;
-    }
-
-	public void setAppTypes(AppType[] appTypes) {
-	    this.appTypes = appTypes;
-    }
-
-	public Property[] getProperties() {
-	    return properties;
-    }
-
-	public void setProperties(Property[] properties) {
-	    this.properties = properties;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java
deleted file mode 100644
index b828cb2..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import org.jclouds.compute.domain.NodeMetadata;
-
-/**
- * This class holds the data to be published to BAM.
- */
-public class CartridgeInstanceData {
-
-    // Cartridge type
-    private String type;
-    
-    private String nodeId;
-    
-    private String domain;
-    
-    private String subDomain;
-    
-    private String iaas;
-    
-    private String status;
-    
-    private String tenantRange;
-    
-    private String alias;
-    
-    private boolean isMultiTenant;
-    
-    private NodeMetadata metaData;
-
-    public String getType() {
-        return type;
-    }
-
-    public void setType(String type) {
-        this.type = type;
-    }
-
-    public String getNodeId() {
-        return nodeId;
-    }
-
-    public void setNodeId(String nodeId) {
-        this.nodeId = nodeId;
-    }
-
-    public String getDomain() {
-        return domain;
-    }
-
-    public void setDomain(String domain) {
-        this.domain = domain;
-    }
-
-    public String getSubDomain() {
-        return subDomain;
-    }
-
-    public void setSubDomain(String subDomain) {
-        this.subDomain = subDomain;
-    }
-
-    public String getIaas() {
-        return iaas;
-    }
-
-    public void setIaas(String iaas) {
-        this.iaas = iaas;
-    }
-
-    public String getStatus() {
-        return status;
-    }
-
-    public void setStatus(String status) {
-        this.status = status;
-    }
-
-    public NodeMetadata getMetaData() {
-        return metaData;
-    }
-
-    public void setMetaData(NodeMetadata metaData) {
-        this.metaData = metaData;
-    }
-
-    public String getTenantRange() {
-        return tenantRange;
-    }
-
-    public void setTenantRange(String tenantRange) {
-        this.tenantRange = tenantRange;
-    }
-
-    public boolean isMultiTenant() {
-        return isMultiTenant;
-    }
-
-    public void setMultiTenant(boolean isMultiTenant) {
-        this.isMultiTenant = isMultiTenant;
-    }
-
-    public String getAlias() {
-        return alias;
-    }
-
-    public void setAlias(String alias) {
-        this.alias = alias;
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java
deleted file mode 100644
index cb537a1..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.File;
-
-import org.wso2.carbon.utils.CarbonUtils;
-
-public final class CloudControllerConstants {
-
-    /**
-     * cloud-controller XML file's elements
-     */
-    public static final String CLOUD_CONTROLLER_ELEMENT = "cloudController";
-    public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
-    public static final String IAAS_PROVIDERS_ELEMENT = "iaasProviders";
-    public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
-    public static final String DEPLOYMENT_ELEMENT = "deployment";
-    public static final String PORT_MAPPING_ELEMENT = "portMapping";
-    public static final String APP_TYPES_ELEMENT = "appTypes";
-    public static final String TYPE_ATTR = "type";
-    public static final String HOST_ATTR = "host";
-    public static final String BASE_DIR_ATTR = "baseDir";
-    public static final String PROVIDER_ATTR = "provider";
-    public static final String VERSION_ATTR = "version";
-    public static final String MULTI_TENANT_ATTR = "multiTenant";
-    public static final String PORT_ATTR = "port";
-    public static final String PROXY_PORT_ATTR = "proxyPort";
-    public static final String NAME_ATTR = "name";
-    public static final String APP_SPECIFIC_MAPPING_ATTR = "appSpecificMapping";
-    
-    public static final String CARTRIDGES_ELEMENT = "cartridges";
-    public static final String CARTRIDGE_ELEMENT = "cartridge";
-    
-    public static final String DISPLAY_NAME_ELEMENT = "displayName";
-    public static final String DESCRIPTION_ELEMENT = "description";
-    public static final String PROPERTY_ELEMENT = "property";
-    public static final String PROPERTY_NAME_ATTR= "name";
-    public static final String PROPERTY_VALUE_ATTR = "value";
-    public static final String IMAGE_ID_ELEMENT = "imageId";
-    public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
-    public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
-    public static final String CLASS_NAME_ELEMENT = "className";
-    public static final String MAX_INSTANCE_LIMIT_ELEMENT = "maxInstanceLimit";
-    public static final String PROVIDER_ELEMENT = "provider";
-    public static final String IDENTITY_ELEMENT = "identity";
-    public static final String CREDENTIAL_ELEMENT = "credential";
-    public static final String DEFAULT_SERVICE_ELEMENT = "default";
-    public static final String SERVICE_ELEMENT = "service";
-    public static final String SERVICES_ELEMENT = "services";
-    public static final String DIRECTORY_ELEMENT = "dir";
-    public static final String HTTP_ELEMENT = "http";
-    public static final String HTTPS_ELEMENT = "https";
-    public static final String APP_TYPE_ELEMENT = "appType";
-    public static final String SERVICE_DOMAIN_ATTR = "domain";
-    public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
-    public static final String SERVICE_TENANT_RANGE_ATTR = "tenantRange";
-    public static final String PAYLOAD_ELEMENT = "payload";
-    public static final String DATA_PUBLISHER_ELEMENT = "dataPublisher";
-    public static final String TOPOLOGY_SYNC_ELEMENT = "topologySync";
-    public static final String ENABLE_ATTR = "enable";
-    public static final String BAM_SERVER_ELEMENT = "bamServer";
-    public static final String MB_SERVER_ELEMENT = "mbServerUrl";
-    public static final String CRON_ELEMENT = "cron";
-    public static final String BAM_SERVER_ADMIN_USERNAME_ELEMENT = "adminUserName";
-    public static final String BAM_SERVER_ADMIN_PASSWORD_ELEMENT = "adminPassword";
-    public static final String CASSANDRA_INFO_ELEMENT = "cassandraInfo";
-    public static final String HOST_ELEMENT = "host";
-    public static final String CONNECTION_URL_ELEMENT = "connectionUrl";
-    public static final String HOST_PORT_ELEMENT = "port";
-    public static final String USER_NAME_ELEMENT = "userName";
-    public static final String PASSWORD_ELEMENT = "password";
-    public static final String CLOUD_CONTROLLER_EVENT_STREAM = "org.wso2.stratos.cloud.controller";
-    public static final String CLOUD_CONTROLLER_COL_FAMILY = CLOUD_CONTROLLER_EVENT_STREAM.replaceAll("[/.]", "_");
-    
-    /**
-     * column names
-     */
-    public static final String PAYLOAD_PREFIX = "payload_";
-    public static final String NODE_ID_COL = "nodeId";
-    public static final String CARTRIDGE_TYPE_COL = "cartridgeType";
-    public static final String DOMAIN_COL = "domain";
-    public static final String SUB_DOMAIN_COL = "subDomain";
-    public static final String ALIAS_COL = "alias";
-    public static final String TENANT_RANGE_COL = "tenantRange";
-    public static final String IS_MULTI_TENANT_COL = "isMultiTenant";
-    public static final String IAAS_COL = "iaas";
-    public static final String STATUS_COL = "status";
-    public static final String HOST_NAME_COL = "hostName";
-    public static final String HYPERVISOR_COL = "hypervisor";
-    public static final String RAM_COL = "ram";
-    public static final String IMAGE_ID_COL = "imageId";
-    public static final String LOGIN_PORT_COL = "loginPort";
-    public static final String OS_NAME_COL = "osName";
-    public static final String OS_VERSION_COL = "osVersion";
-    public static final String OS_ARCH_COL = "osArch";
-    public static final String OS_BIT_COL = "is64bitOS";
-    public static final String PRIV_IP_COL = "privateIPAddresses";
-    public static final String PUB_IP_COL = "publicIPAddresses";
-    
-    
-    /**
-     * Properties
-     */
-    public static final String REGION_PROPERTY = "region";
-    public static final String PUBLIC_IP_PROPERTY = "public_ip";
-    public static final String TENANT_ID_PROPERTY = "tenant_id";
-    public static final String ALIAS_PROPERTY = "alias";
-    public static final String AUTO_ASSIGN_IP_PROPERTY = "autoAssignIp";
-    
-    /**
-     * XPath expressions
-     */
-    public static final String IAAS_PROVIDER_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+"/"+
-     IAAS_PROVIDERS_ELEMENT+"/"+IAAS_PROVIDER_ELEMENT;
-    public static final String PROPERTY_ELEMENT_XPATH = "/"+PROPERTY_ELEMENT;
-    public static final String IMAGE_ID_ELEMENT_XPATH = "/"+IMAGE_ID_ELEMENT;
-    public static final String SCALE_UP_ORDER_ELEMENT_XPATH = "/"+SCALE_UP_ORDER_ELEMENT;
-    public static final String SCALE_DOWN_ORDER_ELEMENT_XPATH = "/"+SCALE_DOWN_ORDER_ELEMENT;
-    public static final String PROVIDER_ELEMENT_XPATH = "/"+PROPERTY_ELEMENT;
-    public static final String IDENTITY_ELEMENT_XPATH = "/"+IDENTITY_ELEMENT;
-    public static final String CREDENTIAL_ELEMENT_XPATH = "/"+CREDENTIAL_ELEMENT;
-    public static final String SERVICES_ELEMENT_XPATH = "/"+SERVICES_ELEMENT+"/"+SERVICE_ELEMENT;
-    public static final String SERVICE_ELEMENT_XPATH = "/"+SERVICE_ELEMENT;
-    public static final String CARTRIDGE_ELEMENT_XPATH = "/"+CARTRIDGE_ELEMENT;
-    public static final String PAYLOAD_ELEMENT_XPATH = "/"+PAYLOAD_ELEMENT;
-    public static final String HOST_ELEMENT_XPATH = "/"+HOST_ELEMENT;
-    public static final String CARTRIDGES_ELEMENT_XPATH = "/"+CARTRIDGES_ELEMENT+"/"+CARTRIDGE_ELEMENT;
-    public static final String IAAS_PROVIDER_ELEMENT_XPATH = "/"+IAAS_PROVIDER_ELEMENT;
-    public static final String DEPLOYMENT_ELEMENT_XPATH = "/"+DEPLOYMENT_ELEMENT;
-    public static final String PORT_MAPPING_ELEMENT_XPATH = "/"+PORT_MAPPING_ELEMENT;
-    public static final String APP_TYPES_ELEMENT_XPATH = "/"+APP_TYPES_ELEMENT;
-    
-    public static final String DATA_PUBLISHER_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-            "/"+DATA_PUBLISHER_ELEMENT;
-    public static final String TOPOLOGY_SYNC_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-            "/"+TOPOLOGY_SYNC_ELEMENT;
-    public static final String DATA_PUBLISHER_CRON_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-            "/"+CRON_ELEMENT;
-    public static final String BAM_SERVER_ADMIN_USERNAME_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-            "/"+BAM_SERVER_ADMIN_USERNAME_ELEMENT;
-    public static final String BAM_SERVER_ADMIN_PASSWORD_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-            "/"+BAM_SERVER_ADMIN_PASSWORD_ELEMENT;
-//    public static final String CASSANDRA_HOST_ADDRESS_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-//            "/"+CASSANDRA_HOST_ADDRESS;
-//    public static final String CASSANDRA_HOST_PORT_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
-//            "/"+CASSANDRA_HOST_PORT;
-    
-    
-    /**
-     * Secret Manager related aliases.
-     */
-    public static final String ALIAS_ATTRIBUTE = "svns:secretAlias";
-    
-    /**
-     * Payload related constants
-     */
-    public static final String PAYLOAD_FOLDER = "payload";
-    public static final String ENTRY_SEPARATOR = ",";
-    
-    /**
-     * Publisher task related constants
-     */
-    public static final String DATA_PUB_TASK_TYPE = "CLOUD_CONTROLLER_DATA_PUBLISHER_TASK";
-    // default is : data publisher will run in first second of every minute
-    public static final String PUB_CRON_EXPRESSION = "1 * * * * ? *";
-    public static final String DATA_PUB_TASK_NAME = "CartridgeInstanceDataPublisherTask";
-    public static final String DEFAULT_BAM_SERVER_USER_NAME = "admin";
-    public static final String DEFAULT_BAM_SERVER_PASSWORD = "admin";
-    public static final String DEFAULT_CASSANDRA_URL = "localhost:9160";
-    public static final String DEFAULT_CASSANDRA_USER = "admin";
-    public static final String DEFAULT_CASSANDRA_PASSWORD = "admin";
-    public static final String DEFAULT_CASSANDRA_CLUSTER_NAME = "Test Cluster";
-    public static final String DEFAULT_CASSANDRA_KEY_SPACE = "EVENT_KS";
-    
-	/**
-	 * Directories
-	 */
-	public static final String PAYLOAD_DIR = CarbonUtils.getCarbonHome() + File.separator +
-	                                         "resources" + File.separator + PAYLOAD_FOLDER +
-	                                         File.separator;
-	public static final String SERVICES_DIR = CarbonUtils.getCarbonRepository() 
-    		+ File.separator + "services"+File.separator;
-    
-    /**
-     * Topology sync related constants
-     */
-    public static final String TOPOLOGY_FILE_PATH = CarbonUtils.getCarbonConfigDirPath()+File.separator+"service-topology.conf";
-    public static final String TOPIC_NAME = "cloud-controller-topology";
-	public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
-	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySynchronizerTask";
-	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SYNC_TASK";
-	public static final String MB_SERVER_URL = "localhost:5672";
-    
-	/**
-	 * Persistence
-	 */
-	public static final String CLOUD_CONTROLLER_RESOURCE = "/cloud.controller";
-	public static final String DATA_RESOURCE = "/data";
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java
deleted file mode 100644
index 64169b6..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package org.wso2.carbon.stratos.cloud.controller.util;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.xml.stream.XMLStreamException;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.util.AXIOMUtil;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
-
-public class CloudControllerUtil {
-	private static final Log log = LogFactory.getLog(CloudControllerUtil.class);
-
-	public static OMElement serviceCtxtToOMElement(ServiceContext ctxt) throws XMLStreamException{
-		String xml;
-		
-		xml = ctxt.toXml();
-		
-		return AXIOMUtil.stringToOM(xml);
-	}
-
-	public static byte[] getBytesFromFile(String path) {
-
-		try {
-	        return FileUtils.readFileToByteArray(new File(path));
-        } catch (IOException e) {
-
-        	handleException("Failed to read the file "+path, e);
-        }
-		return new byte[0];
-    }
-	
-	public static CartridgeInfo toCartridgeInfo(Cartridge cartridge) {
-
-		CartridgeInfo carInfo = new CartridgeInfo();
-		carInfo.setType(cartridge.getType());
-		carInfo.setDisplayName(cartridge.getDisplayName());
-		carInfo.setDescription(cartridge.getDescription());
-		carInfo.setHostName(cartridge.getHostName());
-		carInfo.setDeploymentDirs(cartridge.getDeploymentDirs());
-		carInfo.setProvider(cartridge.getProvider());
-		carInfo.setVersion(cartridge.getVersion());
-		carInfo.setMultiTenant(cartridge.isMultiTenant());
-		carInfo.setBaseDir(cartridge.getBaseDir());
-		carInfo.setPortMappings(cartridge.getPortMappings()
-		                                 .toArray(new PortMapping[cartridge.getPortMappings()
-		                                                                   .size()]));
-		carInfo.setAppTypes(cartridge.getAppTypeMappings()
-                                .toArray(new AppType[cartridge.getAppTypeMappings()
-                                                                  .size()]));
-		
-		List<Property> propList = new ArrayList<Property>();
-		
-		for (Iterator<?> iterator = cartridge.getProperties().entrySet().iterator(); iterator.hasNext();) {
-	        @SuppressWarnings("unchecked")
-            Map.Entry<String, String> entry = (Entry<String, String>) iterator.next();
-	        
-	        Property prop = new Property(entry.getKey(), entry.getValue());
-	        propList.add(prop);
-        }
-		Property[] props = new Property[propList.size()];
-		
-		carInfo.setProperties(propList.toArray(props));
-
-		return carInfo;
-	}
-	
-	public static List<Object> getKeysFromValue(Map<?, ?> hm, Object value) {
-		List<Object> list = new ArrayList<Object>();
-		for (Object o : hm.keySet()) {
-			if (hm.get(o).equals(value)) {
-				list.add(o);
-			}
-		}
-		return list;
-	}
-	
-	public static void sleep(long time){
-    	try {
-    		Thread.sleep(time);
-    	} catch (InterruptedException ignore) {}
-    	
-    }
-	
-	public static void handleException(String msg, Exception e){
-		log.error(msg, e);
-		throw new CloudControllerException(msg, e);
-	}
-	
-	public static void handleException(String msg){
-		log.error(msg);
-		throw new CloudControllerException(msg);
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
deleted file mode 100644
index a5efb07..0000000
--- a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. 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.wso2.carbon.stratos.cloud.controller.util;
-
-import org.wso2.carbon.ntask.core.service.TaskService;
-import org.wso2.carbon.registry.core.Registry;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.stratos.cloud.controller.topic.ConfigurationPublisher;
-
-/**
- * Singleton class to hold all the service references.
- */
-public class DeclarativeServiceReferenceHolder {
-
-    private static DeclarativeServiceReferenceHolder instance;
-    private TaskService taskService;
-    private ConfigurationPublisher configPub;
-    private Registry registry;
-    
-    private DeclarativeServiceReferenceHolder() {
-    }
-
-    public static DeclarativeServiceReferenceHolder getInstance() {
-        if (instance == null) {
-            instance = new DeclarativeServiceReferenceHolder();
-        }
-        return instance;
-    }
-    
-    public ConfigurationPublisher getConfigPub(){
-    	return configPub;
-    }
-
-    public TaskService getTaskService() {
-        return taskService;
-    }
-
-    public void setTaskService(TaskService taskService) {
-        this.taskService = taskService;
-    }
-    
-    public void setConfigPub(ConfigurationPublisher configPub) {
-        this.configPub = configPub;
-    }
-
-	public void setRegistry(UserRegistry governanceSystemRegistry) {
-		registry = governanceSystemRegistry;
-    }
-
-	public Registry getRegistry() {
-	    return registry;
-    }
-    
-}


[07/10] Apache Stratos Cloud Controller Component refactoring

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
new file mode 100644
index 0000000..96756f4
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
@@ -0,0 +1,476 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.publisher;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.ComputeMetadata;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.internal.NodeMetadataImpl;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.databridge.agent.thrift.Agent;
+import org.wso2.carbon.databridge.agent.thrift.DataPublisher;
+import org.wso2.carbon.databridge.agent.thrift.conf.AgentConfiguration;
+import org.wso2.carbon.databridge.commons.Event;
+import org.wso2.carbon.databridge.commons.exception.NoStreamDefinitionExistException;
+import org.wso2.carbon.ntask.core.Task;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.CartridgeInstanceData;
+import org.apache.stratos.cloud.controller.util.IaasContext;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import com.google.common.collect.MapDifference;
+import com.google.common.collect.MapDifference.ValueDifference;
+import com.google.common.collect.Maps;
+
+public class CartridgeInstanceDataPublisherTask implements Task{
+    
+    private static final Log log = LogFactory.getLog(CartridgeInstanceDataPublisherTask.class);
+    private static DataPublisher dataPublisher;
+    private static String streamId;
+    private static final String cloudControllerEventStreamVersion = "1.0.0";
+    private static List<CartridgeInstanceData> dataToBePublished ;
+
+    protected enum NodeStatus {
+        PENDING, RUNNING, SUSPENDED, TERMINATED, ERROR, UNRECOGNIZED
+    };   
+
+    @Override
+    public void execute() {
+        
+        publish();
+    }
+    
+    public static void publish(){
+        if(FasterLookUpDataHolder.getInstance().isPublisherRunning() ||
+                // this is a temporary fix to avoid task execution - limitation with ntask
+                !FasterLookUpDataHolder.getInstance().getEnableBAMDataPublisher()){
+            return;
+        }
+        
+        log.debug(CloudControllerConstants.DATA_PUB_TASK_NAME+" cycle started.");
+        FasterLookUpDataHolder.getInstance().setPublisherRunning(true);
+        dataToBePublished = new ArrayList<CartridgeInstanceData>();
+
+        if(dataPublisher==null){
+            createDataPublisher();
+
+            //If we cannot create a data publisher we should give up
+            //this means data will not be published
+            if(dataPublisher == null){
+                log.error("Data Publisher cannot be created or found.");
+                release();
+                return;
+            }
+        }
+
+        if(streamId == null){
+            try{
+                streamId = dataPublisher.findStream(CloudControllerConstants.CLOUD_CONTROLLER_EVENT_STREAM, cloudControllerEventStreamVersion);
+            }catch (NoStreamDefinitionExistException e){
+                log.info("Defining the event stream because it was not found in BAM");
+                try{
+                    defineStream();
+                } catch(Exception ex){
+                    String msg = "Error occurred while defining the event stream for publishing Cloud Controller data. " + ex.getMessage();
+                    log.error(msg, ex);
+                    //We do not want to proceed without an event stream. Therefore we return.
+                    release();
+                    return;
+                }
+            }catch (Exception exc){
+                log.error("Error occurred while searching for stream id. " + exc.getMessage(), exc);
+                //We do not want to proceed without an event stream. Therefore we return.
+                release();
+                return;
+            }
+        }
+        
+        // build the new node - state Map
+        Map<String, String> newNodeToStateMap;
+        try{
+            newNodeToStateMap = getNodeIdToStatusMap();
+        }catch (Exception e) {
+
+            release();
+            throw new CloudControllerException(e.getMessage(), e);
+            
+        } 
+        
+        // compare it with old map and populate data to be published with ones newly added
+        // and once whose state got changed
+        populateNewlyAddedOrStateChangedNodes(newNodeToStateMap);
+        
+        // issue events for the ones obtained from above
+        for (CartridgeInstanceData dataObj : dataToBePublished) {
+            StringBuffer temp = new StringBuffer("");
+            
+            String privateIpAddresses="";
+            // Concatenate private IP addresses
+            for (String ip : dataObj.getMetaData().getPrivateAddresses()) {
+                temp.append(ip+",");
+            }
+            
+            if(!"".equals(temp.toString())){
+                // remove comma at the end of the string
+                privateIpAddresses = temp.toString().substring(0, temp.toString().length()-1);
+            }
+            
+            temp = new StringBuffer("");
+            String publicIpAddresses="";
+            // Concatenate public IP addresses
+            for (String ip : dataObj.getMetaData().getPublicAddresses()) {
+                temp.append(ip+",");
+            }
+            
+            if(!"".equals(temp.toString())){
+                // remove comma at the end of the string
+                publicIpAddresses = temp.toString().substring(0, temp.toString().length()-1);
+            }
+            
+            try {
+
+                Event cloudControllerEvent = new Event(streamId, System.currentTimeMillis(), new Object[]{}, null,
+                                            new Object[]{dataObj.getNodeId(),
+                                                         dataObj.getType(),
+                                                         dataObj.getDomain(),
+                                                         dataObj.getSubDomain(),
+                                                         dataObj.getAlias(),
+                                                         dataObj.getTenantRange(),
+                                                         String.valueOf(dataObj.isMultiTenant()),
+                                                         dataObj.getIaas(),
+                                                         dataObj.getStatus(),
+                                                         dataObj.getMetaData().getHostname(),
+                                                         dataObj.getMetaData().getHardware().getHypervisor(),
+                                                         String.valueOf(dataObj.getMetaData().getHardware().getRam()),
+                                                         dataObj.getMetaData().getImageId(),
+                                                         String.valueOf(dataObj.getMetaData().getLoginPort()),
+                                                         dataObj.getMetaData().getOperatingSystem().getName(),
+                                                         dataObj.getMetaData().getOperatingSystem().getVersion(),
+                                                         dataObj.getMetaData().getOperatingSystem().getArch(),
+                                                         String.valueOf(dataObj.getMetaData().getOperatingSystem().is64Bit()),
+                                                         privateIpAddresses,
+                                                         publicIpAddresses});
+
+                dataPublisher.publish(cloudControllerEvent);
+                
+                log.debug("Data published : "+cloudControllerEvent.toString());
+
+            } catch (Exception e) {
+                String msg = "Error occurred while publishing Cartridge instance event to BAM. ";
+                log.error(msg, e);
+                release();
+                throw new CloudControllerException(msg, e);
+            }
+            
+        }
+        
+        // replace old map with new one only if data is published
+        FasterLookUpDataHolder.getInstance().setNodeIdToStatusMap(newNodeToStateMap);
+        
+        //TODO remove
+//        CassandraDataRetriever.init();
+//        CassandraDataRetriever.connect();
+//        HiveQueryExecutor hive = new HiveQueryExecutor();
+//        hive.createHiveTable();
+//        System.out.println("***********");
+//        for (String str : hive.getRunningNodeIds()) {
+//         
+//            System.out.println(str);
+//        }
+//        System.out.println("***********");
+        release();
+    }
+    
+    private static void release(){
+        FasterLookUpDataHolder.getInstance().setPublisherRunning(false);
+    }
+    
+    private static void defineStream() throws Exception {
+        streamId = dataPublisher.
+                defineStream("{" +
+                        "  'name':'" + CloudControllerConstants.CLOUD_CONTROLLER_EVENT_STREAM +"'," +
+                        "  'version':'" + cloudControllerEventStreamVersion +"'," +
+                        "  'nickName': 'cloud.controller'," +
+                        "  'description': 'Instances booted up by the Cloud Controller '," +
+                        "  'metaData':[]," +
+                        "  'payloadData':[" +
+                        "          {'name':'"+CloudControllerConstants.NODE_ID_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.CARTRIDGE_TYPE_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.DOMAIN_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.SUB_DOMAIN_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.ALIAS_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.TENANT_RANGE_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.IS_MULTI_TENANT_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.IAAS_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.STATUS_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.HOST_NAME_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.HYPERVISOR_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.RAM_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.IMAGE_ID_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.LOGIN_PORT_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_NAME_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_VERSION_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_ARCH_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_BIT_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.PRIV_IP_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.PUB_IP_COL+"','type':'STRING'}" +
+                        "  ]" +
+                        "}");
+        
+    }
+
+    @Override
+    public void init() {
+
+    	// this is a temporary fix to avoid task execution - limitation with ntask
+		if(!FasterLookUpDataHolder.getInstance().getEnableBAMDataPublisher()){
+			log.debug("BAM data publisher is disabled. ");
+			return;
+		}
+		
+        if((dataPublisher = FasterLookUpDataHolder.getInstance().getDataPublisher()) == null){
+            createDataPublisher();
+        }
+        streamId = FasterLookUpDataHolder.getInstance().getStreamId();
+        
+    }
+
+    @Override
+    public void setProperties(Map<String, String> arg0) {}
+    
+    private static void createDataPublisher(){
+        //creating the agent
+        AgentConfiguration agentConfiguration = new AgentConfiguration();
+
+        ServerConfiguration serverConfig =  CarbonUtils.getServerConfiguration();
+        String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
+        String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");
+        String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");
+        String adminUsername = FasterLookUpDataHolder.getInstance().getBamUsername();
+        String adminPassword = FasterLookUpDataHolder.getInstance().getBamPassword();
+
+        System.setProperty("javax.net.ssl.trustStore", trustStorePath);
+        System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
+
+        Agent agent = new Agent(agentConfiguration);
+
+        try {
+            dataPublisher = new DataPublisher(bamServerUrl, adminUsername, adminPassword, agent);
+            FasterLookUpDataHolder.getInstance().setDataPublisher(dataPublisher);
+            
+        } catch (Exception e) {
+            String msg = "Unable to create a data publisher to " + bamServerUrl +
+                    ". Usage Agent will not function properly. ";
+            log.error(msg, e);
+            throw new CloudControllerException(msg, e);
+        }
+        
+    }
+    
+    private static void bundleData(String key, String val, ServiceContext serviceCtxt) {
+        
+        CartridgeInstanceData instanceData = new CartridgeInstanceData();
+        instanceData.setNodeId(key);
+        instanceData.setStatus(val);
+        instanceData.setDomain(serviceCtxt.getDomainName());
+        instanceData.setSubDomain(serviceCtxt.getSubDomainName());
+        instanceData.setAlias("".equals(serviceCtxt.getProperty(CloudControllerConstants.ALIAS_PROPERTY))
+            ? "NULL"
+                : serviceCtxt.getProperty(CloudControllerConstants.ALIAS_PROPERTY));
+        instanceData.setTenantRange("".equals(serviceCtxt.getProperty(CloudControllerConstants.TENANT_ID_PROPERTY))
+            ? serviceCtxt.getTenantRange()
+                : serviceCtxt.getProperty(CloudControllerConstants.TENANT_ID_PROPERTY));
+        
+        if (serviceCtxt.getCartridge() != null) {
+            instanceData.setMultiTenant(serviceCtxt.getCartridge().isMultiTenant());
+
+            for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+                IaasContext ctxt = null;
+                if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
+                    ctxt = serviceCtxt.addIaasContext(iaas.getType());
+                }
+
+                if (ctxt.didISpawn(key)) {
+                    instanceData.setIaas(iaas.getType());
+                    instanceData.setMetaData(ctxt.getNode(key));
+
+                    // clear to be removed data
+                    ctxt.removeToBeRemovedNodeId(key);
+
+                    // if the node is terminated
+                    if (val.equals(NodeStatus.TERMINATED.toString())) {
+                        // since this node is terminated
+                        FasterLookUpDataHolder.getInstance().removeNodeId(key);
+
+                        // remove node meta data
+                        ctxt.removeNodeMetadata(ctxt.getNode(key));
+                    }
+
+                    break;
+                }
+            }
+
+            instanceData.setType(serviceCtxt.getCartridge().getType());
+        } else {
+            log.warn("Cartridge is null for Service Context : (domain: " +
+                serviceCtxt.getDomainName() +
+                    ", sub domain: " +
+                    serviceCtxt.getSubDomainName() +
+                    ")");
+        }
+        
+        dataToBePublished.add(instanceData);
+        
+    }
+    
+    private static Map<String, String> getNodeIdToStatusMap() throws Exception {
+        
+        Map<String, String> statusMap = new HashMap<String, String>();
+        
+        // iterate through all ServiceContexts
+        for (Iterator<?> it1 = FasterLookUpDataHolder.getInstance().getServiceContexts().entrySet().iterator(); it1.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map.Entry<String, Map<String, ServiceContext>> entry = (Map.Entry<String, Map<String, ServiceContext>>) it1.next();
+            
+            Map<String, ServiceContext> map = (Map<String, ServiceContext>) entry.getValue();
+            
+            for (Iterator<ServiceContext> it2 = map.values().iterator(); it2.hasNext();) {
+                ServiceContext subjectedSerCtxt = (ServiceContext) it2.next();
+                
+                if (subjectedSerCtxt != null && subjectedSerCtxt.getCartridge() != null) {
+                    List<IaasProvider> iaases = subjectedSerCtxt.getCartridge().getIaases();
+
+                    for (IaasProvider iaas : iaases) {
+
+                        ComputeService computeService = iaas.getComputeService();
+                        
+                        if(computeService == null){
+                            continue;
+                        }
+                        
+                        IaasContext ctxt = null;
+                        if((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null){
+                        	ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
+                        }
+
+                        // get list of node Ids
+                        List<String> nodeIds = ctxt.getAllNodeIds();
+
+                        if (nodeIds.isEmpty()) {
+                            
+                            continue;
+                        }
+                        
+                        try {
+
+                            // get all the nodes spawned by this IaasContext
+                            Set<? extends ComputeMetadata> set = computeService.listNodes();
+
+                            Iterator<? extends ComputeMetadata> iterator = set.iterator();
+
+                            // traverse through all nodes of this ComputeService object
+                            while (iterator.hasNext()) {
+                                NodeMetadata nodeMetadata = (NodeMetadataImpl) iterator.next();
+
+                                // if this node belongs to the requested domain
+                                if (nodeIds.contains(nodeMetadata.getId())) {
+
+                                    statusMap.put(nodeMetadata.getId(), nodeMetadata.getStatus()
+                                                                                    .toString());
+
+                                    ctxt.addNodeMetadata(nodeMetadata);
+                                }
+
+                            }
+
+                        }catch (Exception e) {
+                            log.error(e.getMessage(), e);
+                            throw e;
+                        }
+
+                    }
+                }
+            }
+            
+            
+        }
+        return statusMap;
+
+    }
+    
+    private static void populateNewlyAddedOrStateChangedNodes(Map<String, String> newMap){
+        
+        MapDifference<String, String> diff = Maps.difference(newMap, 
+                                                             FasterLookUpDataHolder.getInstance().getNodeIdToStatusMap());
+        
+        // adding newly added nodes
+        Map<String, String> newlyAddedNodes = diff.entriesOnlyOnLeft();
+        
+        for (Iterator<?> it = newlyAddedNodes.entrySet().iterator(); it.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
+            String key = entry.getKey();
+            String val = entry.getValue();
+            ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);
+            
+            log.debug("------ Node id: "+key+" --- node status: "+val+" -------- ctxt: "+ctxt);
+            
+            if (ctxt != null && key != null && val != null) {
+                // bundle the data to be published
+                bundleData(key, val, ctxt);
+            }   
+                    
+        }
+        
+        // adding nodes with state changes
+        Map<String, ValueDifference<String>> stateChangedNodes = diff.entriesDiffering();
+        
+        for (Iterator<?> it = stateChangedNodes.entrySet().iterator(); it.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map.Entry<String, ValueDifference<String>> entry = (Map.Entry<String, ValueDifference<String>>) it.next();
+            
+            String key = entry.getKey();
+            String newState = entry.getValue().leftValue();
+            ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);
+            
+            log.debug("------- Node id: "+key+" --- node status: "+newState+" -------- ctxt: "+ctxt);
+            
+            if (ctxt != null && key != null && newState != null) {
+                // bundle the data to be published
+                bundleData(key, newState, ctxt);
+            }  
+            
+        }
+
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java
new file mode 100644
index 0000000..13bb688
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java
@@ -0,0 +1,101 @@
+package org.apache.stratos.cloud.controller.registry;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.persist.Serializer;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException;
+
+/**
+ *
+ */
+public class RegistryManager {
+	private final static Log log = LogFactory.getLog(RegistryManager.class);
+	private static Registry registryService;
+	private static RegistryManager registryManager;
+	
+	public static RegistryManager getInstance() {
+
+		registryService = DeclarativeServiceReferenceHolder.getInstance().getRegistry();
+				
+		if (registryManager == null) {
+			synchronized(RegistryManager.class){
+				if (registryManager == null) {
+					if(registryService == null){
+//						log.warn("Registry Service is null. Hence unable to fetch data from registry.");
+						return registryManager;
+					}
+					registryManager = new RegistryManager();
+				}
+			}
+		}
+
+		return registryManager;
+	}
+	
+	private RegistryManager() {
+		try {
+			if (!registryService.resourceExists(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE)) {
+				registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE,
+				                    registryService.newCollection());
+			}
+		} catch (RegistryException e) {
+			String msg =
+			             "Failed to create the registry resource " +
+			                     CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE;
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+	}
+
+	/**
+     * Persist an object in the local registry.
+     * @param dataObj object to be persisted.
+     */
+	public void persist(FasterLookUpDataHolder dataObj) throws RegistryException {
+		try {
+
+			registryService.beginTransaction();
+			
+			Resource nodeResource = registryService.newResource();
+
+			nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
+
+			registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE, nodeResource);
+			
+			registryService.commitTransaction();
+			
+		} catch (Exception e) {
+			String msg = "Failed to persist the cloud controller data in registry.";
+			registryService.rollbackTransaction();
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+			
+		} 
+	}
+	
+	public Object retrieve(){
+		
+		try {
+	        Resource resource = registryService.get(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE);
+	        
+	        return resource.getContent();
+	        
+        } catch (ResourceNotFoundException ignore) {
+        	// this means, we've never persisted CC info in registry
+        	return null;
+        }catch (RegistryException e) {
+        	String msg = "Failed to retrieve cloud controller data from registry.";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+        }
+		
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java.back
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java.back b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java.back
new file mode 100644
index 0000000..3ab6681
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/registry/RegistryManager.java.back
@@ -0,0 +1,96 @@
+package org.wso2.carbon.stratos.cloud.controller.registry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.persist.Serializer;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerServiceReferenceHolder;
+
+/**
+ *
+ */
+public class RegistryManager {
+	private final static Log log = LogFactory.getLog(RegistryManager.class);
+	private static Registry registryService = CloudControllerServiceReferenceHolder.getInstance().getRegistry();
+	private static RegistryManager registryManager;
+	
+	public static RegistryManager getInstance() {
+
+		if (registryManager == null) {
+			synchronized(RegistryManager.class){
+				if (registryManager == null) {
+					if(registryService == null){
+						log.warn("Registry Service is null. Hence unable to fetch data from registry.");
+						return registryManager;
+					}
+					registryManager = new RegistryManager();
+				}
+			}
+		}
+
+		return registryManager;
+	}
+	
+	private RegistryManager() {
+		try {
+			if (!registryService.resourceExists(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE)) {
+				registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE,
+				                    registryService.newCollection());
+			}
+		} catch (RegistryException e) {
+			String msg =
+			             "Failed to create the registry resource " +
+			                     CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE;
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+	}
+
+	/**
+     * Persist a node id in the local registry.
+     * @param nodeId node id to be persisted.
+     */
+	public void persist(Object dataObj) throws RegistryException {
+		try {
+
+			registryService.beginTransaction();
+			
+			Resource nodeResource = registryService.newResource();
+
+			nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
+
+			registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE, nodeResource);
+			
+			registryService.commitTransaction();
+			
+		} catch (Exception e) {
+			String msg = "Failed to persist the cloud controller data in registry.";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+			
+		} finally{
+			registryService.rollbackTransaction();
+			
+		}
+	}
+	
+	public Object retrieve(){
+		
+		try {
+	        Resource resource = registryService.get(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE);
+	        
+	        return resource.getContent();
+	        
+        } catch (RegistryException e) {
+        	String msg = "Failed to retrieve cloud controller data from registry.";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+        }
+		
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
new file mode 100644
index 0000000..049a068
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
@@ -0,0 +1,425 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.cloud.controller.runtime;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.wso2.carbon.databridge.agent.thrift.DataPublisher;
+import org.apache.stratos.cloud.controller.registry.RegistryManager;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.Cartridge;
+import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
+import org.apache.stratos.cloud.controller.util.ServiceContext;
+
+/**
+ * This object holds all runtime data and provides faster access. This is a Singleton class.
+ */
+public class FasterLookUpDataHolder implements Serializable{
+
+    private static final long serialVersionUID = -2662307358852779897L;
+
+	private static volatile FasterLookUpDataHolder ctxt;
+
+	/* We keep following maps in order to make the look up time, small. */
+
+	/**
+	 * Map of maps.
+	 * Map 1:
+	 * Key - domain
+	 * Value - is another map
+	 * Map 2:
+	 * key - sub domain
+	 * value - {@link ServiceContext}
+	 */
+	private Map<String, Map<String, ServiceContext>> serviceCtxts;
+	
+	/**
+	 * To make data retrieval from registry faster.
+	 */
+	private List<ServiceContext> serviceCtxtList;
+
+	public List<ServiceContext> getServiceCtxtList() {
+    	return serviceCtxtList;
+    }
+
+	/**
+	 * Key - node id
+	 * Value - {@link ServiceContext}
+	 */
+	private Map<String, ServiceContext> nodeIdToServiceCtxt;
+	
+	/**
+	 * List of registered {@link Cartridge}s
+	 */
+	private List<Cartridge> cartridges;
+
+	/**
+	 * List of IaaS Providers.
+	 */
+	private List<IaasProvider> iaasProviders;
+
+	private String serializationDir;
+	private boolean enableBAMDataPublisher;
+	private boolean enableTopologySync;
+	private String bamUsername = CloudControllerConstants.DEFAULT_BAM_SERVER_USER_NAME;
+	private String bamPassword = CloudControllerConstants.DEFAULT_BAM_SERVER_PASSWORD;
+	private String dataPublisherCron = CloudControllerConstants.PUB_CRON_EXPRESSION;
+	private String cassandraConnUrl = CloudControllerConstants.DEFAULT_CASSANDRA_URL;
+	private String cassandraUser = CloudControllerConstants.DEFAULT_CASSANDRA_USER;
+	private String cassandraPassword = CloudControllerConstants.DEFAULT_CASSANDRA_PASSWORD;
+	/**
+	 * Key - node id 
+	 * Value - Status of the instance
+	 * This map is only used by BAM data publisher in CC.
+	 */
+	private Map<String, String> nodeIdToStatusMap = new HashMap<String, String>();
+	private transient DataPublisher dataPublisher;
+	private String streamId;
+	private boolean isPublisherRunning;
+	private boolean isTopologySyncRunning;
+	private String topologySynchronizerCron = CloudControllerConstants.TOPOLOGY_SYNC_CRON;
+
+	private BlockingQueue<List<ServiceContext>> sharedTopologyDiffQueue = new LinkedBlockingQueue<List<ServiceContext>>();
+
+
+	private String mbServerUrl = CloudControllerConstants.MB_SERVER_URL;
+
+	public static FasterLookUpDataHolder getInstance() {
+
+		if (ctxt == null) {
+			synchronized (FasterLookUpDataHolder.class) {
+				if (ctxt == null && RegistryManager.getInstance() != null) {
+
+					Object obj = RegistryManager.getInstance().retrieve();
+					if (obj != null) {
+						if (obj instanceof FasterLookUpDataHolder) {
+							ctxt = (FasterLookUpDataHolder) obj;
+							System.out.println("*********** FasterLookUpDataHolder ********");
+						} else {
+							System.out.println("*********** Not a FasterLookUpDataHolder *******");
+						}
+
+					} 
+					
+				}
+				if(ctxt == null) {
+					ctxt = new FasterLookUpDataHolder();
+				}
+			}
+		}
+
+		return ctxt;
+	}
+
+	private FasterLookUpDataHolder() {
+
+		serviceCtxtList = new ArrayList<ServiceContext>();
+		serviceCtxts = new ConcurrentHashMap<String, Map<String, ServiceContext>>();
+		nodeIdToServiceCtxt = new LinkedHashMap<String, ServiceContext>();
+		cartridges = new ArrayList<Cartridge>();
+
+	}
+
+	public void addServiceContext(ServiceContext ctx) {
+
+		if (ctx == null) {
+			return;
+		}
+
+		String domain = ctx.getDomainName();
+		String subDomain = ctx.getSubDomainName();
+
+		if (domain != null && subDomain != null) {
+			addToServiceCtxts(domain, subDomain, ctx);
+		}
+
+	}
+
+	public void removeServiceContext(ServiceContext ctxt) {
+
+		if (ctxt == null) {
+			return;
+		}
+
+		String domain = ctxt.getDomainName();
+		String subDomain = ctxt.getSubDomainName();
+
+		if (domain != null && subDomain != null) {
+			if (serviceCtxts.containsKey(domain)) {
+				Map<String, ServiceContext> subDomainMap = serviceCtxts.get(domain);
+				subDomainMap.remove(subDomain);
+			}
+		}
+		
+		serviceCtxtList.remove(ctxt);
+
+	}
+
+	public ServiceContext getServiceContext(String domain, String subDomain) {
+
+		if (serviceCtxts.get(domain) != null) {
+			return serviceCtxts.get(domain).get(subDomain);
+		}
+		return null;
+	}
+
+	public ServiceContext getServiceContext(String nodeId) {
+
+		return nodeIdToServiceCtxt.get(nodeId);
+	}
+	
+	public List<Object> getNodeIdsOfServiceCtxt(ServiceContext ctxt){
+		return CloudControllerUtil.getKeysFromValue(nodeIdToServiceCtxt, ctxt);
+	}
+
+	public Map<String, Map<String, ServiceContext>> getServiceContexts() {
+		return serviceCtxts;
+	}
+
+	public void addNodeId(String nodeId, ServiceContext ctxt) {
+		nodeIdToServiceCtxt.put(nodeId, ctxt);
+	}
+
+	public void removeNodeId(String nodeId) {
+		nodeIdToServiceCtxt.remove(nodeId);
+	}
+	
+	public void setNodeIdToServiceContextMap(Map<String, ServiceContext> map) {
+		nodeIdToServiceCtxt = map;
+	}
+
+	public Map<String, ServiceContext> getNodeIdToServiceContextMap() {
+		return nodeIdToServiceCtxt;
+	}
+
+	private void addToServiceCtxts(String domainName, String subDomainName, ServiceContext ctxt) {
+
+		Map<String, ServiceContext> map;
+
+		if (serviceCtxts.get(domainName) == null) {
+			map = new HashMap<String, ServiceContext>();
+
+		} else {
+			map = serviceCtxts.get(domainName);
+		}
+
+		map.put(subDomainName, ctxt);
+		serviceCtxts.put(domainName, map);
+		
+		serviceCtxtList.add(ctxt);
+
+	}
+
+	public List<Cartridge> getCartridges() {
+		return cartridges;
+	}
+
+	public Cartridge getCartridge(String cartridgeType) {
+		for (Cartridge cartridge : cartridges) {
+			if (cartridge.getType().equals(cartridgeType)) {
+				return cartridge;
+			}
+		}
+
+		return null;
+
+	}
+
+//	public void addCartridges(List<Cartridge> newCartridges) {
+//		if (this.cartridges == null) {
+//			this.cartridges = newCartridges;
+//		} else {
+//			for (Cartridge cartridge : newCartridges) {
+//				int idx;
+//				if ((idx = cartridges.indexOf(cartridge)) != -1) {
+//					Cartridge ref = cartridges.get(idx);
+//					ref = cartridge;
+//				} else {
+//					cartridges.add(cartridge);
+//				}
+//			}
+//		}
+//
+//	}
+	
+	public void addCartridge(Cartridge newCartridges) {
+	
+		cartridges.add(newCartridges);
+	}
+
+	public void removeCartridges(List<Cartridge> cartridges) {
+		if (this.cartridges != null) {
+			this.cartridges.removeAll(cartridges);
+		}
+
+	}
+
+	public List<IaasProvider> getIaasProviders() {
+		return iaasProviders;
+	}
+
+	public void setIaasProviders(List<IaasProvider> iaasProviders) {
+		this.iaasProviders = iaasProviders;
+	}
+
+	public String getSerializationDir() {
+		return serializationDir;
+	}
+
+	public void setSerializationDir(String serializationDir) {
+		this.serializationDir = serializationDir;
+	}
+
+	public String getBamUsername() {
+		return bamUsername;
+	}
+
+	public void setBamUsername(String bamUsername) {
+		this.bamUsername = bamUsername;
+	}
+
+	public String getBamPassword() {
+		return bamPassword;
+	}
+
+	public void setBamPassword(String bamPassword) {
+		this.bamPassword = bamPassword;
+	}
+
+	public String getDataPublisherCron() {
+		return dataPublisherCron;
+	}
+
+	public void setDataPublisherCron(String dataPublisherCron) {
+		this.dataPublisherCron = dataPublisherCron;
+	}
+
+	public Map<String, String> getNodeIdToStatusMap() {
+		return nodeIdToStatusMap;
+	}
+
+	public void setNodeIdToStatusMap(Map<String, String> nodeIdToStatusMap) {
+		this.nodeIdToStatusMap = nodeIdToStatusMap;
+	}
+
+	public DataPublisher getDataPublisher() {
+		return dataPublisher;
+	}
+
+	public void setDataPublisher(DataPublisher dataPublisher) {
+		this.dataPublisher = dataPublisher;
+	}
+
+	public String getStreamId() {
+		return streamId;
+	}
+
+	public void setStreamId(String streamId) {
+		this.streamId = streamId;
+	}
+
+	public boolean getEnableBAMDataPublisher() {
+		return enableBAMDataPublisher;
+	}
+
+	public void setEnableBAMDataPublisher(boolean enableBAMDataPublisher) {
+		this.enableBAMDataPublisher = enableBAMDataPublisher;
+	}
+
+	public String getCassandraConnUrl() {
+		return cassandraConnUrl;
+	}
+
+	public void setCassandraConnUrl(String cassandraHostAddr) {
+		this.cassandraConnUrl = cassandraHostAddr;
+	}
+
+	public String getCassandraUser() {
+		return cassandraUser;
+	}
+
+	public void setCassandraUser(String cassandraUser) {
+		this.cassandraUser = cassandraUser;
+	}
+
+	public String getCassandraPassword() {
+		return cassandraPassword;
+	}
+
+	public void setCassandraPassword(String cassandraPassword) {
+		this.cassandraPassword = cassandraPassword;
+	}
+
+	public boolean isPublisherRunning() {
+		return isPublisherRunning;
+	}
+
+	public void setPublisherRunning(boolean isPublisherRunning) {
+		this.isPublisherRunning = isPublisherRunning;
+	}
+
+	public BlockingQueue<List<ServiceContext>> getSharedTopologyDiffQueue() {
+		return sharedTopologyDiffQueue;
+	}
+
+	public void setSharedTopologyDiffQueue(BlockingQueue<List<ServiceContext>> sharedTopologyDiffQueue) {
+		this.sharedTopologyDiffQueue = sharedTopologyDiffQueue;
+	}
+
+	public String getTopologySynchronizerCron() {
+		return topologySynchronizerCron;
+	}
+
+	public void setTopologySynchronizerCron(String topologySynchronizerCron) {
+		this.topologySynchronizerCron = topologySynchronizerCron;
+	}
+
+	public void setMBServerUrl(String ip) {
+		this.mbServerUrl = ip;
+	}
+
+	public String getMBServerUrl() {
+		return mbServerUrl;
+	}
+
+	public boolean getEnableTopologySync() {
+		return enableTopologySync;
+	}
+
+	public void setEnableTopologySync(boolean enableTopologySync) {
+		this.enableTopologySync = enableTopologySync;
+	}
+
+	public boolean isTopologySyncRunning() {
+	    return isTopologySyncRunning;
+    }
+
+	public void setTopologySyncRunning(boolean isTopologySyncRunning) {
+	    this.isTopologySyncRunning = isTopologySyncRunning;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/ConfigurationPublisher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/ConfigurationPublisher.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/ConfigurationPublisher.java
new file mode 100644
index 0000000..0339fd7
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/ConfigurationPublisher.java
@@ -0,0 +1,65 @@
+package org.apache.stratos.cloud.controller.topic;
+
+import java.util.Properties;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class ConfigurationPublisher {
+	private TopicPublisher topicPublisher;
+	private TopicSession topicSession;
+	private TopicConnection topicConnection;
+	private TopicConnectionFactory topicConnectionFactory;
+	private static final Log log = LogFactory.getLog(ConfigurationPublisher.class);
+	
+	
+	public ConfigurationPublisher() {
+	    
+		Properties initialContextProperties = new Properties();
+		initialContextProperties.put("java.naming.factory.initial",
+				"org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
+		String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://"+ FasterLookUpDataHolder.getInstance().getMBServerUrl()+"'";
+		initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
+		
+		try {
+			InitialContext initialContext = new InitialContext(initialContextProperties);
+			topicConnectionFactory =
+					(TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
+			
+//			topicConnection.stop();
+//			topicConnection.close();
+			
+		} catch (NamingException e) {
+			log.error(e.getMessage(), e);
+		} 
+    }
+
+	
+	public void publish(String topicName, String message) {
+		try {
+			topicConnection = topicConnectionFactory.createTopicConnection();
+			topicConnection.start();
+			topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+			Topic topic = topicSession.createTopic(topicName);
+			topicPublisher = topicSession.createPublisher(topic);
+			TextMessage textMessage = topicSession.createTextMessage(message);
+
+			topicPublisher.publish(textMessage);
+			
+			topicPublisher.close();
+			topicSession.close();
+			topicConnection.stop();
+			topicConnection.close();
+			
+		}  catch (JMSException e) {
+			log.error(e.getMessage(), e);
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/TopologySynchronizerTask.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/TopologySynchronizerTask.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/TopologySynchronizerTask.java
new file mode 100644
index 0000000..08a40e4
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/topic/TopologySynchronizerTask.java
@@ -0,0 +1,79 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.topic;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.ntask.core.Task;
+
+public class TopologySynchronizerTask implements Task{
+    
+    private static final Log log = LogFactory.getLog(TopologySynchronizerTask.class);
+    private DeclarativeServiceReferenceHolder data = DeclarativeServiceReferenceHolder.getInstance();
+    private File topologyFile;
+    
+    @Override
+    public void execute() {
+    	if(FasterLookUpDataHolder.getInstance().isTopologySyncRunning()||
+        		// this is a temporary fix to avoid task execution - limitation with ntask
+        		!FasterLookUpDataHolder.getInstance().getEnableTopologySync()){
+            return;
+        }
+    	
+    	log.debug("TopologySynchronizerTask ... ");
+        
+    	// publish to the topic 
+		try {
+			if (topologyFile.exists()) {
+				data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME,
+				                               FileUtils.readFileToString(topologyFile));
+			}
+		} catch (IOException e) {
+        	String msg = "Failed when publishing to the topic "+CloudControllerConstants.TOPIC_NAME+
+        			" - Reason : Failed while reading topology from "+topologyFile.getAbsolutePath();
+        	log.error(msg, e);
+        	throw new CloudControllerException(msg, e);
+        }
+    }
+    
+    @Override
+    public void init() {
+
+    	// this is a temporary fix to avoid task execution - limitation with ntask
+		if(!FasterLookUpDataHolder.getInstance().getEnableTopologySync()){
+			log.debug("Topology Sync is disabled.");
+			return;
+		}
+    	
+    	topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
+        
+    }
+
+    @Override
+    public void setProperties(Map<String, String> arg0) {}
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/AppType.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/AppType.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/AppType.java
new file mode 100644
index 0000000..3ca9bfc
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/AppType.java
@@ -0,0 +1,44 @@
+package org.apache.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+
+/**
+ * domain mapping related data.
+ *
+ */
+public class AppType implements Serializable{
+	
+    private static final long serialVersionUID = 3550489774139807168L;
+	private String name;
+	private boolean appSpecificMapping = true;
+	
+	public AppType(){
+		
+	}
+	
+	public AppType(String name){
+		this.setName(name);
+	}
+	
+	public AppType(String name, boolean appSpecificMapping){
+		this.setName(name);
+		this.setAppSpecificMapping(appSpecificMapping);
+	}
+
+	public String getName() {
+	    return name;
+    }
+
+	public void setName(String name) {
+	    this.name = name;
+    }
+
+	public boolean isAppSpecificMapping() {
+	    return appSpecificMapping;
+    }
+
+	public void setAppSpecificMapping(boolean appSpecificMapping) {
+	    this.appSpecificMapping = appSpecificMapping;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Cartridge.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Cartridge.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Cartridge.java
new file mode 100644
index 0000000..8625965
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/Cartridge.java
@@ -0,0 +1,254 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+
+/**
+ * Holds information regarding a Cartridge.
+ */
+public class Cartridge implements Serializable{
+
+    private static final long serialVersionUID = 6637409027085059072L;
+
+	private String type;
+    
+    private String hostName;
+    
+    private String provider;
+    
+    private String displayName;
+    
+    private String description;
+    
+    private String baseDir;
+    
+    private String version;
+    
+    private boolean multiTenant;
+    
+    private List<PortMapping> portMappings = new ArrayList<PortMapping>();
+    
+    private List<AppType> appTypeMappings = new ArrayList<AppType>();
+    
+    /**
+     * Property map of this Cartridge.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    /**
+     * A Cartridge can have 1..n {@link IaasProvider}s
+     */
+    private List<IaasProvider> iaases = new ArrayList<IaasProvider>();
+    
+    private List<String> deploymentDirs = new ArrayList<String>();
+    
+    private IaasProvider lastlyUsedIaas;
+    
+    public Cartridge(){}
+    
+    public Cartridge(String type, String host, String provider, String version, boolean multiTenant) {
+        this.type = type;
+        this.hostName = host;
+        this.provider = provider;
+        this.version = version;
+        this.multiTenant = multiTenant;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+    
+    public String getProperty(String key) {
+        return properties.get(key);
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public void addIaasProvider(IaasProvider iaas) {
+        for (IaasProvider anIaas : iaases) {
+            if(anIaas.equals(iaas)){
+                int idx = iaases.indexOf(anIaas);
+                iaases.remove(idx);
+                iaases.add(idx, iaas);
+                return;
+            }
+        }
+        this.iaases.add(iaas);
+    }
+    
+    public IaasProvider getIaasProvider(String iaasType){
+    	for (IaasProvider iaas : iaases) {
+	        if(iaas.getType().equals(iaasType)){
+	        	return iaas;
+	        }
+        }
+    	
+    	return null;
+    }
+
+    public List<IaasProvider> getIaases() {
+        return iaases;
+    }
+
+    public void setIaases(List<IaasProvider> iaases) {
+        this.iaases = iaases;
+    }
+    
+	public boolean equals(Object obj) {
+		if (obj instanceof Cartridge) {
+			return this.type.equals(((Cartridge)obj).getType());
+		}
+		return false;
+	}
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(type).
+            toHashCode();
+    }
+
+    public IaasProvider getLastlyUsedIaas() {
+        return lastlyUsedIaas;
+    }
+
+    public void setLastlyUsedIaas(IaasProvider lastlyUsedIaas) {
+        this.lastlyUsedIaas = lastlyUsedIaas;
+    }
+
+//    public boolean isJcloudsObjectsBuilt() {
+//        return isJcloudsObjectsBuilt;
+//    }
+//
+//    public void setJcloudsObjectsBuilt(boolean isJcloudsObjectsBuilt) {
+//        this.isJcloudsObjectsBuilt = isJcloudsObjectsBuilt;
+//    }
+
+	public String getDisplayName() {
+		return displayName;
+	}
+
+	public void setDisplayName(String displayName) {
+		this.displayName = displayName;
+	}
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+	public String getHostName() {
+	    return hostName;
+    }
+
+	public void setHostName(String hostName) {
+	    this.hostName = hostName;
+    }
+	
+	public void reset(){
+//		lastlyUsedIaas = null;
+	}
+
+	public List<String> getDeploymentDirs() {
+	    return deploymentDirs;
+    }
+
+	public void setDeploymentDirs(List<String> deploymentDirs) {
+	    this.deploymentDirs = deploymentDirs;
+    }
+	
+	public void addDeploymentDir(String dir){
+		deploymentDirs.add(dir);
+	}
+	
+	public void addPortMapping(PortMapping mapping){
+		portMappings.add(mapping);
+	}
+	
+	public void addAppType(AppType type){
+		appTypeMappings.add(type);
+	}
+
+	public String getProvider() {
+	    return provider;
+    }
+
+	public void setProvider(String provider) {
+	    this.provider = provider;
+    }
+
+	public String getVersion() {
+		return version;
+	}
+
+	public void setVersion(String version) {
+		this.version = version;
+	}
+
+	public boolean isMultiTenant() {
+		return multiTenant;
+	}
+
+	public void setMultiTenant(boolean multiTenant) {
+		this.multiTenant = multiTenant;
+	}
+
+	public String getBaseDir() {
+	    return baseDir;
+    }
+
+	public void setBaseDir(String baseDir) {
+	    this.baseDir = baseDir;
+    }
+
+	public List<PortMapping> getPortMappings() {
+	    return portMappings;
+    }
+
+	public void setPortMappings(List<PortMapping> portMappings) {
+	    this.portMappings = portMappings;
+    }
+
+	public List<AppType> getAppTypeMappings() {
+    	return appTypeMappings;
+    }
+
+	public void setAppTypeMappings(List<AppType> appTypeMappings) {
+    	this.appTypeMappings = appTypeMappings;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInfo.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInfo.java
new file mode 100644
index 0000000..daeef80
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInfo.java
@@ -0,0 +1,162 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Holds useful information for externals, regarding a Cartridge.
+ */
+public class CartridgeInfo {
+
+    private String type;
+    
+    private String hostName;
+    
+    private String displayName;
+    
+    private String description;
+    
+    private String[] deploymentDirs;
+    
+    private PortMapping[] portMappings;
+    
+    private AppType[] appTypes;
+    
+    private String provider;
+    
+    private String version;
+    
+    private boolean multiTenant;
+    
+    private String baseDir;
+    
+    private Property[] properties;
+    
+    public CartridgeInfo(){
+    	
+    }
+    
+    public CartridgeInfo(String type, String host, String desc, List<String> deploymentDirs, String provider) {
+        this.type = type;
+        this.hostName = host;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getDisplayName() {
+		return displayName;
+	}
+
+	public void setDisplayName(String displayName) {
+		this.displayName = displayName;
+	}
+
+	public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+	public String getHostName() {
+	    return hostName;
+    }
+
+	public void setHostName(String hostName) {
+	    this.hostName = hostName;
+    }
+
+	public String[] getDeploymentDirs() {
+	    return deploymentDirs;
+    }
+
+	public void setDeploymentDirs(List<String> deploymentDirsList) {
+		if(deploymentDirsList == null){
+			deploymentDirsList = new ArrayList<String>();
+		}
+	    this.deploymentDirs = new String[deploymentDirsList.size()];
+	    
+	    deploymentDirsList.toArray(deploymentDirs);
+	    
+    }
+	
+    public String getProvider() {
+	    return provider;
+    }
+
+	public void setProvider(String provider) {
+	    this.provider = provider;
+    }
+
+	public String getVersion() {
+		return version;
+	}
+
+	public void setVersion(String version) {
+		this.version = version;
+	}
+
+	public boolean isMultiTenant() {
+		return multiTenant;
+	}
+
+	public void setMultiTenant(boolean multiTenant) {
+		this.multiTenant = multiTenant;
+	}
+
+	public String getBaseDir() {
+	    return baseDir;
+    }
+
+	public void setBaseDir(String baseDir) {
+	    this.baseDir = baseDir;
+    }
+
+	public PortMapping[] getPortMappings() {
+	    return portMappings;
+    }
+
+	public void setPortMappings(PortMapping[] portMappings) {
+	    this.portMappings = portMappings;
+    }
+
+	public AppType[] getAppTypes() {
+	    return appTypes;
+    }
+
+	public void setAppTypes(AppType[] appTypes) {
+	    this.appTypes = appTypes;
+    }
+
+	public Property[] getProperties() {
+	    return properties;
+    }
+
+	public void setProperties(Property[] properties) {
+	    this.properties = properties;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInstanceData.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInstanceData.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInstanceData.java
new file mode 100644
index 0000000..ee6efee
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CartridgeInstanceData.java
@@ -0,0 +1,129 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import org.jclouds.compute.domain.NodeMetadata;
+
+/**
+ * This class holds the data to be published to BAM.
+ */
+public class CartridgeInstanceData {
+
+    // Cartridge type
+    private String type;
+    
+    private String nodeId;
+    
+    private String domain;
+    
+    private String subDomain;
+    
+    private String iaas;
+    
+    private String status;
+    
+    private String tenantRange;
+    
+    private String alias;
+    
+    private boolean isMultiTenant;
+    
+    private NodeMetadata metaData;
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getNodeId() {
+        return nodeId;
+    }
+
+    public void setNodeId(String nodeId) {
+        this.nodeId = nodeId;
+    }
+
+    public String getDomain() {
+        return domain;
+    }
+
+    public void setDomain(String domain) {
+        this.domain = domain;
+    }
+
+    public String getSubDomain() {
+        return subDomain;
+    }
+
+    public void setSubDomain(String subDomain) {
+        this.subDomain = subDomain;
+    }
+
+    public String getIaas() {
+        return iaas;
+    }
+
+    public void setIaas(String iaas) {
+        this.iaas = iaas;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public NodeMetadata getMetaData() {
+        return metaData;
+    }
+
+    public void setMetaData(NodeMetadata metaData) {
+        this.metaData = metaData;
+    }
+
+    public String getTenantRange() {
+        return tenantRange;
+    }
+
+    public void setTenantRange(String tenantRange) {
+        this.tenantRange = tenantRange;
+    }
+
+    public boolean isMultiTenant() {
+        return isMultiTenant;
+    }
+
+    public void setMultiTenant(boolean isMultiTenant) {
+        this.isMultiTenant = isMultiTenant;
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    public void setAlias(String alias) {
+        this.alias = alias;
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerConstants.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerConstants.java
new file mode 100644
index 0000000..534b896
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerConstants.java
@@ -0,0 +1,216 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import java.io.File;
+
+import org.wso2.carbon.utils.CarbonUtils;
+
+public final class CloudControllerConstants {
+
+    /**
+     * cloud-controller XML file's elements
+     */
+    public static final String CLOUD_CONTROLLER_ELEMENT = "cloudController";
+    public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
+    public static final String IAAS_PROVIDERS_ELEMENT = "iaasProviders";
+    public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
+    public static final String DEPLOYMENT_ELEMENT = "deployment";
+    public static final String PORT_MAPPING_ELEMENT = "portMapping";
+    public static final String APP_TYPES_ELEMENT = "appTypes";
+    public static final String TYPE_ATTR = "type";
+    public static final String HOST_ATTR = "host";
+    public static final String BASE_DIR_ATTR = "baseDir";
+    public static final String PROVIDER_ATTR = "provider";
+    public static final String VERSION_ATTR = "version";
+    public static final String MULTI_TENANT_ATTR = "multiTenant";
+    public static final String PORT_ATTR = "port";
+    public static final String PROXY_PORT_ATTR = "proxyPort";
+    public static final String NAME_ATTR = "name";
+    public static final String APP_SPECIFIC_MAPPING_ATTR = "appSpecificMapping";
+    
+    public static final String CARTRIDGES_ELEMENT = "cartridges";
+    public static final String CARTRIDGE_ELEMENT = "cartridge";
+    
+    public static final String DISPLAY_NAME_ELEMENT = "displayName";
+    public static final String DESCRIPTION_ELEMENT = "description";
+    public static final String PROPERTY_ELEMENT = "property";
+    public static final String PROPERTY_NAME_ATTR= "name";
+    public static final String PROPERTY_VALUE_ATTR = "value";
+    public static final String IMAGE_ID_ELEMENT = "imageId";
+    public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
+    public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
+    public static final String CLASS_NAME_ELEMENT = "className";
+    public static final String MAX_INSTANCE_LIMIT_ELEMENT = "maxInstanceLimit";
+    public static final String PROVIDER_ELEMENT = "provider";
+    public static final String IDENTITY_ELEMENT = "identity";
+    public static final String CREDENTIAL_ELEMENT = "credential";
+    public static final String DEFAULT_SERVICE_ELEMENT = "default";
+    public static final String SERVICE_ELEMENT = "service";
+    public static final String SERVICES_ELEMENT = "services";
+    public static final String DIRECTORY_ELEMENT = "dir";
+    public static final String HTTP_ELEMENT = "http";
+    public static final String HTTPS_ELEMENT = "https";
+    public static final String APP_TYPE_ELEMENT = "appType";
+    public static final String SERVICE_DOMAIN_ATTR = "domain";
+    public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
+    public static final String SERVICE_TENANT_RANGE_ATTR = "tenantRange";
+    public static final String PAYLOAD_ELEMENT = "payload";
+    public static final String DATA_PUBLISHER_ELEMENT = "dataPublisher";
+    public static final String TOPOLOGY_SYNC_ELEMENT = "topologySync";
+    public static final String ENABLE_ATTR = "enable";
+    public static final String BAM_SERVER_ELEMENT = "bamServer";
+    public static final String MB_SERVER_ELEMENT = "mbServerUrl";
+    public static final String CRON_ELEMENT = "cron";
+    public static final String BAM_SERVER_ADMIN_USERNAME_ELEMENT = "adminUserName";
+    public static final String BAM_SERVER_ADMIN_PASSWORD_ELEMENT = "adminPassword";
+    public static final String CASSANDRA_INFO_ELEMENT = "cassandraInfo";
+    public static final String HOST_ELEMENT = "host";
+    public static final String CONNECTION_URL_ELEMENT = "connectionUrl";
+    public static final String HOST_PORT_ELEMENT = "port";
+    public static final String USER_NAME_ELEMENT = "userName";
+    public static final String PASSWORD_ELEMENT = "password";
+    public static final String CLOUD_CONTROLLER_EVENT_STREAM = "org.wso2.stratos.cloud.controller";
+    public static final String CLOUD_CONTROLLER_COL_FAMILY = CLOUD_CONTROLLER_EVENT_STREAM.replaceAll("[/.]", "_");
+    
+    /**
+     * column names
+     */
+    public static final String PAYLOAD_PREFIX = "payload_";
+    public static final String NODE_ID_COL = "nodeId";
+    public static final String CARTRIDGE_TYPE_COL = "cartridgeType";
+    public static final String DOMAIN_COL = "domain";
+    public static final String SUB_DOMAIN_COL = "subDomain";
+    public static final String ALIAS_COL = "alias";
+    public static final String TENANT_RANGE_COL = "tenantRange";
+    public static final String IS_MULTI_TENANT_COL = "isMultiTenant";
+    public static final String IAAS_COL = "iaas";
+    public static final String STATUS_COL = "status";
+    public static final String HOST_NAME_COL = "hostName";
+    public static final String HYPERVISOR_COL = "hypervisor";
+    public static final String RAM_COL = "ram";
+    public static final String IMAGE_ID_COL = "imageId";
+    public static final String LOGIN_PORT_COL = "loginPort";
+    public static final String OS_NAME_COL = "osName";
+    public static final String OS_VERSION_COL = "osVersion";
+    public static final String OS_ARCH_COL = "osArch";
+    public static final String OS_BIT_COL = "is64bitOS";
+    public static final String PRIV_IP_COL = "privateIPAddresses";
+    public static final String PUB_IP_COL = "publicIPAddresses";
+    
+    
+    /**
+     * Properties
+     */
+    public static final String REGION_PROPERTY = "region";
+    public static final String PUBLIC_IP_PROPERTY = "public_ip";
+    public static final String TENANT_ID_PROPERTY = "tenant_id";
+    public static final String ALIAS_PROPERTY = "alias";
+    public static final String AUTO_ASSIGN_IP_PROPERTY = "autoAssignIp";
+    
+    /**
+     * XPath expressions
+     */
+    public static final String IAAS_PROVIDER_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+"/"+
+     IAAS_PROVIDERS_ELEMENT+"/"+IAAS_PROVIDER_ELEMENT;
+    public static final String PROPERTY_ELEMENT_XPATH = "/"+PROPERTY_ELEMENT;
+    public static final String IMAGE_ID_ELEMENT_XPATH = "/"+IMAGE_ID_ELEMENT;
+    public static final String SCALE_UP_ORDER_ELEMENT_XPATH = "/"+SCALE_UP_ORDER_ELEMENT;
+    public static final String SCALE_DOWN_ORDER_ELEMENT_XPATH = "/"+SCALE_DOWN_ORDER_ELEMENT;
+    public static final String PROVIDER_ELEMENT_XPATH = "/"+PROPERTY_ELEMENT;
+    public static final String IDENTITY_ELEMENT_XPATH = "/"+IDENTITY_ELEMENT;
+    public static final String CREDENTIAL_ELEMENT_XPATH = "/"+CREDENTIAL_ELEMENT;
+    public static final String SERVICES_ELEMENT_XPATH = "/"+SERVICES_ELEMENT+"/"+SERVICE_ELEMENT;
+    public static final String SERVICE_ELEMENT_XPATH = "/"+SERVICE_ELEMENT;
+    public static final String CARTRIDGE_ELEMENT_XPATH = "/"+CARTRIDGE_ELEMENT;
+    public static final String PAYLOAD_ELEMENT_XPATH = "/"+PAYLOAD_ELEMENT;
+    public static final String HOST_ELEMENT_XPATH = "/"+HOST_ELEMENT;
+    public static final String CARTRIDGES_ELEMENT_XPATH = "/"+CARTRIDGES_ELEMENT+"/"+CARTRIDGE_ELEMENT;
+    public static final String IAAS_PROVIDER_ELEMENT_XPATH = "/"+IAAS_PROVIDER_ELEMENT;
+    public static final String DEPLOYMENT_ELEMENT_XPATH = "/"+DEPLOYMENT_ELEMENT;
+    public static final String PORT_MAPPING_ELEMENT_XPATH = "/"+PORT_MAPPING_ELEMENT;
+    public static final String APP_TYPES_ELEMENT_XPATH = "/"+APP_TYPES_ELEMENT;
+    
+    public static final String DATA_PUBLISHER_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+DATA_PUBLISHER_ELEMENT;
+    public static final String TOPOLOGY_SYNC_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+TOPOLOGY_SYNC_ELEMENT;
+    public static final String DATA_PUBLISHER_CRON_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+CRON_ELEMENT;
+    public static final String BAM_SERVER_ADMIN_USERNAME_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+BAM_SERVER_ADMIN_USERNAME_ELEMENT;
+    public static final String BAM_SERVER_ADMIN_PASSWORD_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+BAM_SERVER_ADMIN_PASSWORD_ELEMENT;
+//    public static final String CASSANDRA_HOST_ADDRESS_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+//            "/"+CASSANDRA_HOST_ADDRESS;
+//    public static final String CASSANDRA_HOST_PORT_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+//            "/"+CASSANDRA_HOST_PORT;
+    
+    
+    /**
+     * Secret Manager related aliases.
+     */
+    public static final String ALIAS_ATTRIBUTE = "svns:secretAlias";
+    
+    /**
+     * Payload related constants
+     */
+    public static final String PAYLOAD_FOLDER = "payload";
+    public static final String ENTRY_SEPARATOR = ",";
+    
+    /**
+     * Publisher task related constants
+     */
+    public static final String DATA_PUB_TASK_TYPE = "CLOUD_CONTROLLER_DATA_PUBLISHER_TASK";
+    // default is : data publisher will run in first second of every minute
+    public static final String PUB_CRON_EXPRESSION = "1 * * * * ? *";
+    public static final String DATA_PUB_TASK_NAME = "CartridgeInstanceDataPublisherTask";
+    public static final String DEFAULT_BAM_SERVER_USER_NAME = "admin";
+    public static final String DEFAULT_BAM_SERVER_PASSWORD = "admin";
+    public static final String DEFAULT_CASSANDRA_URL = "localhost:9160";
+    public static final String DEFAULT_CASSANDRA_USER = "admin";
+    public static final String DEFAULT_CASSANDRA_PASSWORD = "admin";
+    public static final String DEFAULT_CASSANDRA_CLUSTER_NAME = "Test Cluster";
+    public static final String DEFAULT_CASSANDRA_KEY_SPACE = "EVENT_KS";
+    
+	/**
+	 * Directories
+	 */
+	public static final String PAYLOAD_DIR = CarbonUtils.getCarbonHome() + File.separator +
+	                                         "resources" + File.separator + PAYLOAD_FOLDER +
+	                                         File.separator;
+	public static final String SERVICES_DIR = CarbonUtils.getCarbonRepository() 
+    		+ File.separator + "services"+File.separator;
+    
+    /**
+     * Topology sync related constants
+     */
+    public static final String TOPOLOGY_FILE_PATH = CarbonUtils.getCarbonConfigDirPath()+File.separator+"service-topology.conf";
+    public static final String TOPIC_NAME = "cloud-controller-topology";
+	public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
+	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySynchronizerTask";
+	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SYNC_TASK";
+	public static final String MB_SERVER_URL = "localhost:5672";
+    
+	/**
+	 * Persistence
+	 */
+	public static final String CLOUD_CONTROLLER_RESOURCE = "/cloud.controller";
+	public static final String DATA_RESOURCE = "/data";
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerUtil.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerUtil.java
new file mode 100644
index 0000000..a1f5551
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/CloudControllerUtil.java
@@ -0,0 +1,102 @@
+package org.apache.stratos.cloud.controller.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import javax.xml.stream.XMLStreamException;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class CloudControllerUtil {
+	private static final Log log = LogFactory.getLog(CloudControllerUtil.class);
+
+	public static OMElement serviceCtxtToOMElement(ServiceContext ctxt) throws XMLStreamException{
+		String xml;
+		
+		xml = ctxt.toXml();
+		
+		return AXIOMUtil.stringToOM(xml);
+	}
+
+	public static byte[] getBytesFromFile(String path) {
+
+		try {
+	        return FileUtils.readFileToByteArray(new File(path));
+        } catch (IOException e) {
+
+        	handleException("Failed to read the file "+path, e);
+        }
+		return new byte[0];
+    }
+	
+	public static CartridgeInfo toCartridgeInfo(Cartridge cartridge) {
+
+		CartridgeInfo carInfo = new CartridgeInfo();
+		carInfo.setType(cartridge.getType());
+		carInfo.setDisplayName(cartridge.getDisplayName());
+		carInfo.setDescription(cartridge.getDescription());
+		carInfo.setHostName(cartridge.getHostName());
+		carInfo.setDeploymentDirs(cartridge.getDeploymentDirs());
+		carInfo.setProvider(cartridge.getProvider());
+		carInfo.setVersion(cartridge.getVersion());
+		carInfo.setMultiTenant(cartridge.isMultiTenant());
+		carInfo.setBaseDir(cartridge.getBaseDir());
+		carInfo.setPortMappings(cartridge.getPortMappings()
+		                                 .toArray(new PortMapping[cartridge.getPortMappings()
+		                                                                   .size()]));
+		carInfo.setAppTypes(cartridge.getAppTypeMappings()
+                                .toArray(new AppType[cartridge.getAppTypeMappings()
+                                                                  .size()]));
+		
+		List<Property> propList = new ArrayList<Property>();
+		
+		for (Iterator<?> iterator = cartridge.getProperties().entrySet().iterator(); iterator.hasNext();) {
+	        @SuppressWarnings("unchecked")
+            Map.Entry<String, String> entry = (Entry<String, String>) iterator.next();
+	        
+	        Property prop = new Property(entry.getKey(), entry.getValue());
+	        propList.add(prop);
+        }
+		Property[] props = new Property[propList.size()];
+		
+		carInfo.setProperties(propList.toArray(props));
+
+		return carInfo;
+	}
+	
+	public static List<Object> getKeysFromValue(Map<?, ?> hm, Object value) {
+		List<Object> list = new ArrayList<Object>();
+		for (Object o : hm.keySet()) {
+			if (hm.get(o).equals(value)) {
+				list.add(o);
+			}
+		}
+		return list;
+	}
+	
+	public static void sleep(long time){
+    	try {
+    		Thread.sleep(time);
+    	} catch (InterruptedException ignore) {}
+    	
+    }
+	
+	public static void handleException(String msg, Exception e){
+		log.error(msg, e);
+		throw new CloudControllerException(msg, e);
+	}
+	
+	public static void handleException(String msg){
+		log.error(msg);
+		throw new CloudControllerException(msg);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/35006acc/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
new file mode 100644
index 0000000..bf38da7
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/2.1.3/src/main/java/org/apache/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
@@ -0,0 +1,69 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.cloud.controller.util;
+
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.cloud.controller.topic.ConfigurationPublisher;
+
+/**
+ * Singleton class to hold all the service references.
+ */
+public class DeclarativeServiceReferenceHolder {
+
+    private static DeclarativeServiceReferenceHolder instance;
+    private TaskService taskService;
+    private ConfigurationPublisher configPub;
+    private Registry registry;
+    
+    private DeclarativeServiceReferenceHolder() {
+    }
+
+    public static DeclarativeServiceReferenceHolder getInstance() {
+        if (instance == null) {
+            instance = new DeclarativeServiceReferenceHolder();
+        }
+        return instance;
+    }
+    
+    public ConfigurationPublisher getConfigPub(){
+    	return configPub;
+    }
+
+    public TaskService getTaskService() {
+        return taskService;
+    }
+
+    public void setTaskService(TaskService taskService) {
+        this.taskService = taskService;
+    }
+    
+    public void setConfigPub(ConfigurationPublisher configPub) {
+        this.configPub = configPub;
+    }
+
+	public void setRegistry(UserRegistry governanceSystemRegistry) {
+		registry = governanceSystemRegistry;
+    }
+
+	public Registry getRegistry() {
+	    return registry;
+    }
+    
+}