You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mu...@apache.org on 2013/11/08 12:19:44 UTC

[2/3] Squashed merge of Ssl Termination feature

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
index fe072e1..e48d31d 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
@@ -25,6 +25,10 @@ import java.util.Map;
 
 import javax.naming.ConfigurationException;
 
+import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey;
+import com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding;
+import com.cloud.network.lb.LoadBalancingRule.LbSslCert;
+import com.cloud.utils.ssh.SshHelper;
 import org.apache.log4j.Logger;
 
 import com.citrix.netscaler.nitro.exception.nitro_exception;
@@ -235,6 +239,7 @@ public class NetscalerResource implements ServerResource {
 
             //enable load balancing feature
             enableLoadBalancingFeature();
+            SSL.enableSslFeature(_netscalerService);
 
             //if the the device is cloud stack provisioned then make it part of the public network
             if (_cloudManaged) {
@@ -550,6 +555,8 @@ public class NetscalerResource implements ServerResource {
                 String lbAlgorithm = loadBalancer.getAlgorithm();
                 String nsVirtualServerName  = generateNSVirtualServerName(srcIp, srcPort);
                 String nsMonitorName = generateNSMonitorName(srcIp, srcPort);
+                LbSslCert sslCert = loadBalancer.getSslCert();
+
                 if(loadBalancer.isAutoScaleVmGroupTO()) {
                     applyAutoScaleConfig(loadBalancer);
                    // Continue to process all the rules.
@@ -558,6 +565,7 @@ public class NetscalerResource implements ServerResource {
                 boolean hasMonitor = false;
                 boolean deleteMonitor = false;
                 boolean destinationsToAdd = false;
+                boolean deleteCert = false;
                 for (DestinationTO destination : loadBalancer.getDestinations()) {
                     if (!destination.isRevoked()) {
                         destinationsToAdd = true;
@@ -655,9 +663,35 @@ public class NetscalerResource implements ServerResource {
                                 }
 
                             }
+
+
+                            if(sslCert != null && lbProtocol.equals(NetUtils.SSL_PROTO)) {
+                                if ( sslCert.isRevoked() ){
+                                    deleteCert = true;
+                                } else{
+
+                                    String certName = generateSslCertName(srcIp, srcPort);
+                                    String keyName = generateSslKeyName(srcIp, srcPort);
+                                    String certKeyName = generateSslCertKeyName(srcIp, srcPort);
+
+                                    if ( SSL.isSslCertKeyPresent(_netscalerService, certKeyName)){
+                                        SSL.deleteSslCertKey(_netscalerService, certKeyName);
+                                    }
+
+
+                                    SSL.uploadCert(_ip, _username, _password, certName, sslCert.getCert().getBytes());
+                                    SSL.uploadKey(_ip, _username, _password, keyName, sslCert.getKey().getBytes());
+
+                                    SSL.createSslCertKey(_netscalerService, certName, keyName, certKeyName, sslCert.getPassword());
+                                    SSL.bindCertKeyToVserver(_netscalerService, certKeyName, nsVirtualServerName);
+                                }
+
+                            }
+
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug("Successfully added LB destination: " + destination.getDestIp() + ":" + destination.getDestPort() + " to load balancer " + srcIp + ":" + srcPort);
                             }
+
                         } else {
                             // remove a destination from the deployed load balancing rule
                             com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, nsVirtualServerName);
@@ -731,11 +765,27 @@ public class NetscalerResource implements ServerResource {
                         }
                         removeLBVirtualServer(nsVirtualServerName);
                         deleteMonitor = true;
+                        deleteCert = true;
                     }
                 }
                 if(deleteMonitor) {
                     removeLBMonitor(nsMonitorName);
                 }
+                if ( sslCert != null && deleteCert){
+
+                    String certName = generateSslCertName(srcIp, srcPort);
+                    String keyName = generateSslKeyName(srcIp, srcPort);
+                    String certKeyName = generateSslCertKeyName(srcIp, srcPort);
+
+                    // unbind before deleting
+                    if ( nsVirtualServerExists(nsVirtualServerName) ){
+                        SSL.unbindCertKeyFromVserver(_netscalerService, certKeyName, nsVirtualServerName);
+                    }
+
+                    SSL.deleteSslCertKey(_netscalerService, certKeyName);
+                    SSL.deleteCertFile(_ip, _username, _password, certName);
+                    SSL.deleteKeyFile(_ip, _username, _password, keyName);
+                }
 
             }
 
@@ -1666,6 +1716,173 @@ public class NetscalerResource implements ServerResource {
         }
     }
 
+    /* SSL Termination */
+    private static class SSL {
+
+        private static  final String SSL_CERT_PATH = "/nsconfig/ssl/";
+        private static  final int SSH_PORT = 22;
+
+        private static boolean isSslCertKeyPresent(nitro_service ns, String certKeyName) throws ExecutionException {
+
+            String filter = "certkey:" + certKeyName;
+
+            try {
+                if (sslcertkey.count_filtered(ns, filter) > 0) return true;
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to get certkey " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to get certkey " + e.getMessage());
+            }
+
+            return false;
+        }
+
+        private static void deleteSslCertKey(nitro_service ns, String certKeyName) throws ExecutionException {
+            try {
+
+                sslcertkey certkey = new sslcertkey();
+                certkey.set_certkey(certKeyName);
+                sslcertkey.delete(ns, certkey);
+
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to delete certkey " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to delete certkey " + e.getMessage());
+            }
+
+        }
+
+        private static void deleteCertFile(String nsIp, String username, String password, String certName) throws Exception {
+            SshHelper.sshExecute(nsIp,SSH_PORT,username,null,password,"shell rm " + SSL_CERT_PATH + certName);
+        }
+
+        private static void deleteKeyFile(String nsIp, String username, String password, String keyName) throws Exception {
+            SshHelper.sshExecute(nsIp,SSH_PORT,username,null,password,"shell rm " + SSL_CERT_PATH + keyName);
+        }
+
+        private static void createSslCertKey(nitro_service ns, String certName, String keyName, String certKeyName, String password) throws ExecutionException {
+            s_logger.debug("Adding cert to netscaler");
+            try {
+                sslcertkey certkey = new sslcertkey();
+                certkey.set_certkey(certKeyName);
+                certkey.set_cert(SSL_CERT_PATH + certName);
+                certkey.set_key(SSL_CERT_PATH + keyName);
+
+                if( password != null ) {
+                    certkey.set_passplain(password);
+                }
+
+                certkey.perform_operation(ns);
+
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to add certkey binding " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to add certkey binding " + e.getMessage());
+            }
+
+        }
+
+        public static void updateCertKey(nitro_service ns, String certKeyName, String cert, String key, String password) throws ExecutionException {
+            try{
+                sslcertkey certkey = sslcertkey.get(ns, certKeyName);
+                if ( cert != null )
+                    certkey.set_cert(cert);
+                if ( key != null )
+                    certkey.set_key(cert);
+                if ( password != null )
+                    certkey.set_passplain(cert);
+
+                sslcertkey.change(ns,certkey);
+
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to update ssl on load balancer due to " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to update ssl on load balancer due to " + e.getMessage());
+            }
+        }
+
+        private static void bindCertKeyToVserver(nitro_service ns, String certKeyName, String vserver) throws ExecutionException {
+            s_logger.debug("Adding cert to netscaler");
+
+            try {
+                sslvserver_sslcertkey_binding cert_binding = new sslvserver_sslcertkey_binding();
+                cert_binding.set_certkeyname(certKeyName);
+                cert_binding.set_vservername(vserver);
+                cert_binding.perform_operation(ns);
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to bind certkey to vserver due to " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to bind certkey to vserver due to " + e.getMessage());
+            }
+        }
+
+        private static void unbindCertKeyFromVserver(nitro_service ns, String certKeyName, String vserver) throws ExecutionException {
+            try {
+
+                sslvserver_sslcertkey_binding cert_binding = new sslvserver_sslcertkey_binding();
+                cert_binding.set_certkeyname(certKeyName);
+                cert_binding.set_vservername(vserver);
+                sslvserver_sslcertkey_binding.delete(ns,cert_binding);
+
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to unbind certkey to vserver due to " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to unbind certkey to vserver due to " + e.getMessage());
+            }
+
+        }
+
+
+        private static void uploadCert(String nsIp, String user, String password, String certName, byte[] certData) throws ExecutionException {
+            try {
+                SshHelper.scpTo(nsIp,SSH_PORT,user,null,password, SSL_CERT_PATH, certData, certName, null);
+            } catch (Exception e){
+                throw new ExecutionException("Failed to copy private key to device " + e.getMessage());
+            }
+        }
+
+        private static void uploadKey(String nsIp, String user, String password, String keyName, byte[] keyData) throws ExecutionException {
+            try {
+                SshHelper.scpTo(nsIp, SSH_PORT, user, null, password, SSL_CERT_PATH, keyData, keyName, null);
+            }  catch (Exception e){
+                throw new ExecutionException("Failed to copy private key to device " + e.getMessage());
+            }
+        }
+
+
+        private static void enableSslFeature(nitro_service ns) throws ExecutionException {
+            try {
+                base_response result = ns.enable_features(new String[]{"SSL"});
+                if( result.errorcode != 0 )
+                    throw new ExecutionException("Unable to enable SSL on LB");
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to enable ssl feature on load balancer due to " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to enable ssl feature on load balancer due to " + e.getMessage());
+            }
+        }
+
+        public static boolean checkSslFeature(nitro_service ns) throws ExecutionException {
+            try {
+                String[] features = ns.get_enabled_features();
+                if (features != null) {
+                    for (String feature : features) {
+                        if (feature.equalsIgnoreCase("SSL")) {
+                            return true;
+                        }
+                    }
+                }
+                return false;
+            } catch (nitro_exception e){
+                throw new ExecutionException("Failed to check ssl feature on load balancer due to " + e.getMessage());
+            } catch (Exception e){
+                throw new ExecutionException("Failed to check ssl feature on load balancer due to " + e.getMessage());
+            }
+        }
+
+
+    }
+
 
     private void enableVPXInterfaces(String publicIf, String privateIf, ns ns_obj) {
         // enable VPX to use 10 gigabit Ethernet interfaces if public/private interface
@@ -2110,6 +2327,25 @@ public class NetscalerResource implements ServerResource {
         }
     }
 
+    private boolean nsVirtualServerExists(String vserverName) throws ExecutionException {
+        try {
+            if (com.citrix.netscaler.nitro.resource.config.lb.lbvserver.get(_netscalerService, vserverName) != null) {
+                return true;
+            } else {
+                return false;
+            }
+        } catch (nitro_exception e) {
+            if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) {
+                return false;
+            } else {
+                throw new ExecutionException("Failed to verify VServer " + vserverName + " exists on the NetScaler device due to " + e.getMessage());
+            }
+        } catch (Exception e) {
+            throw new ExecutionException("Failed to verify VServer " + vserverName + " exists on the NetScaler device due to " + e.getMessage());
+        }
+    }
+
+
     private boolean nsVlanNsipBindingExists(long vlanTag, String vlanSelfIp) throws ExecutionException {
         try {
             vlan_nsip_binding[] vlanNsipBindings = vlan_nsip_binding.get(_netscalerService, vlanTag);
@@ -2308,11 +2544,14 @@ public class NetscalerResource implements ServerResource {
 
     private String getNetScalerProtocol(LoadBalancerTO loadBalancer) throws ExecutionException {
         String port = Integer.toString(loadBalancer.getSrcPort());
-        String lbProtocol = loadBalancer.getProtocol();
+        String lbProtocol = loadBalancer.getLbProtocol();
         StickinessPolicyTO[] stickyPolicies = loadBalancer.getStickinessPolicies();
         String nsProtocol = "TCP";
 
-        if ((stickyPolicies != null) && (stickyPolicies.length > 0) && (stickyPolicies[0] != null)){
+        if(lbProtocol == null)
+            lbProtocol = loadBalancer.getProtocol();
+
+       if ((stickyPolicies != null) && (stickyPolicies.length > 0) && (stickyPolicies[0] != null)){
             StickinessPolicyTO stickinessPolicy = stickyPolicies[0];
             if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName()) ||
                     (StickinessMethodType.AppCookieBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName()))) {
@@ -2321,6 +2560,10 @@ public class NetscalerResource implements ServerResource {
             }
         }
 
+
+        if( lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO) || lbProtocol.equalsIgnoreCase(NetUtils.HTTP_PROTO))
+            return lbProtocol.toUpperCase();
+
         if (port.equals(NetUtils.HTTP_PORT)) {
             nsProtocol = "HTTP";
         } else if (NetUtils.TCP_PROTO.equalsIgnoreCase(lbProtocol)) {
@@ -3381,6 +3624,18 @@ public class NetscalerResource implements ServerResource {
         return counterName.replace(' ', '_');
     }
 
+    private String generateSslCertName(String srcIp, long srcPort) {
+        // maximum length supported by NS is 31
+        return genObjectName("Cloud-Cert", srcIp, srcPort);
+    }
+
+    private String generateSslKeyName(String srcIp, long srcPort) {
+        return genObjectName("Cloud-Key", srcIp, srcPort);
+    }
+    private String generateSslCertKeyName(String srcIp, long srcPort) {
+        return genObjectName("Cloud-CertKey", srcIp, srcPort);
+    }
+
     private String genObjectName(Object... args) {
         String objectName = "";
         for (int i = 0; i < args.length; i++) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
----------------------------------------------------------------------
diff --git a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
index 5e37908..f7a8d67 100644
--- a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
+++ b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
@@ -223,4 +223,6 @@
     <bean id="GlobalLoadBalancingRulesServiceImpl"
         class="org.apache.cloudstack.region.gslb.GlobalLoadBalancingRulesServiceImpl" />
 
+    <bean id="certServiceImpl" class="org.apache.cloudstack.network.lb.CertServiceImpl" />
+
 </beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
index 6ca40c0..8d54541 100644
--- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
+++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
@@ -899,7 +899,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
             if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) {
                 boolean inline = _networkMgr.isNetworkInlineMode(network);
                 LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(),
-                        rule.getHealthCheckPolicies());
+                        rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol());
                 if (rule.isAutoScaleConfig()) {
                     loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup());
                 }
@@ -1184,7 +1184,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
             if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) {
                 boolean inline = _networkMgr.isNetworkInlineMode(network);
                 LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked,
-                        false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies());
+                        false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol());
                 loadBalancersToApply.add(loadBalancer);
             }
         }
@@ -1218,5 +1218,5 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
             }
         }
         return null;
-    }
+   }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
index 0d43478..a1650e0 100755
--- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
+++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
@@ -107,6 +107,9 @@ import com.cloud.network.dao.LoadBalancerVO;
 import com.cloud.network.dao.NetworkDao;
 import com.cloud.network.dao.NetworkServiceMapDao;
 import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.LoadBalancerCertMapDao;
+import com.cloud.network.dao.LoadBalancerCertMapVO;
+import com.cloud.network.dao.SslCertVO;
 import com.cloud.network.element.LoadBalancingServiceProvider;
 import com.cloud.network.lb.LoadBalancingRule.LbAutoScalePolicy;
 import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup;
@@ -115,6 +118,7 @@ import com.cloud.network.lb.LoadBalancingRule.LbCondition;
 import com.cloud.network.lb.LoadBalancingRule.LbDestination;
 import com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy;
 import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
+import com.cloud.network.lb.LoadBalancingRule.LbSslCert;
 import com.cloud.network.rules.FirewallManager;
 import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.FirewallRule.FirewallRuleType;
@@ -253,6 +257,9 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
     IpAddressManager _ipAddrMgr;
     @Inject
     EntityManager _entityMgr;
+    @Inject
+    LoadBalancerCertMapDao _lbCertMapDao;
+
 
     // Will return a string. For LB Stickiness this will be a json, for
     // autoscale this will be "," separated values
@@ -350,7 +357,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
          */
         List<LbStickinessPolicy> policyList = getStickinessPolicies(lb.getId());
         Ip sourceIp = getSourceIp(lb);
-        LoadBalancingRule rule = new LoadBalancingRule(lb, null, policyList, null, sourceIp);
+        LoadBalancingRule rule = new LoadBalancingRule(lb, null, policyList, null, sourceIp, null, lb.getLbProtocol());
         rule.setAutoScaleVmGroup(lbAutoScaleVmGroup);
 
         if (!isRollBackAllowedForProvider(lb)) {
@@ -558,7 +565,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         policyList.add(new LbStickinessPolicy(cmd.getStickinessMethodName(), lbpolicy.getParams()));
         Ip sourceIp = getSourceIp(loadBalancer);
         LoadBalancingRule lbRule = new LoadBalancingRule(loadBalancer, getExistingDestinations(lbpolicy.getId()),
-                policyList, null, sourceIp);
+                policyList, null, sourceIp,null, loadBalancer.getLbProtocol());
         if (!validateLbRule(lbRule)) {
             throw new InvalidParameterValueException("Failed to create Stickiness policy: Validation Failed "
                     + cmd.getLbRuleId());
@@ -905,7 +912,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
                         // hashealtChecks
                         if (hcPolicyList != null && hcPolicyList.size() > 0) {
                             Ip sourceIp = getSourceIp(lb);
-                            LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, null, hcPolicyList, sourceIp);
+                            LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, null, hcPolicyList, sourceIp, null, lb.getLbProtocol());
                             lbrules.add(loadBalancing);
                         }
                     }
@@ -1088,11 +1095,160 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
     }
 
     @Override
+    public boolean assignSSLCertToLoadBalancerRule(Long lbId, String certName, String publicCert, String privateKey) {
+        s_logger.error("Calling the manager for LB");
+        LoadBalancerVO loadBalancer = _lbDao.findById(lbId);
+
+        return false;  //TODO
+    }
+
+    @Override
     @ActionEvent(eventType = EventTypes.EVENT_REMOVE_FROM_LOAD_BALANCER_RULE, eventDescription = "removing from load balancer", async = true)
     public boolean removeFromLoadBalancer(long loadBalancerId, List<Long> instanceIds) {
         return removeFromLoadBalancerInternal(loadBalancerId, instanceIds, true);
     }
 
+    @Override
+    public LbSslCert getLbSslCert(long lbRuleId) {
+        LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
+
+        if ( lbCertMap == null)
+            return null;
+
+        SslCertVO certVO = _entityMgr.findById(SslCertVO.class, lbCertMap.getCertId());
+        if ( certVO == null) {
+            s_logger.warn("Cert rule with cert ID " + lbCertMap.getCertId() + " but Cert is not found");
+            return null;
+        }
+
+        return  new LbSslCert(certVO.getCertificate(), certVO.getKey(),
+                                    certVO.getChain(), certVO.getPassword(), lbCertMap.isRevoke());
+    }
+
+    @Override
+    @DB
+    @ActionEvent(eventType = EventTypes.EVENT_LB_CERT_ASSIGN, eventDescription = "assigning certificate to load balancer", async = true)
+    public boolean assignCertToLoadBalancer(long lbRuleId, Long certId) {
+        CallContext caller = CallContext.current();
+
+        LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(lbRuleId));
+        if (loadBalancer == null) {
+            throw new InvalidParameterException("Invalid load balancer id: " + lbRuleId);
+        }
+
+        SslCertVO certVO = _entityMgr.findById(SslCertVO.class,certId);
+        if (certVO == null) {
+            throw new InvalidParameterException("Invalid certificate id: " + certId);
+        }
+
+        _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
+
+        // check if LB and Cert belong to the same account
+        if( loadBalancer.getAccountId() != certVO.getAccountId() ){
+            throw new InvalidParameterValueException("Access denied for account " + certVO.getAccountId());
+        }
+
+
+        String capability = getLBCapability(loadBalancer.getNetworkId(), Capability.SslTermination.getName());
+        if ( capability == null){
+            throw new InvalidParameterValueException("Ssl termination not supported by the loadbalancer");
+        }
+
+        //check if the lb is already bound
+        LoadBalancerCertMapVO certMapRule = _lbCertMapDao.findByLbRuleId(loadBalancer.getId());
+        if (certMapRule != null)
+            throw new InvalidParameterValueException("Another certificate is already bound to the LB");
+
+        //check for correct port
+        if ( loadBalancer.getLbProtocol() == null || !(loadBalancer.getLbProtocol().equals(NetUtils.SSL_PROTO)))
+            throw new InvalidParameterValueException("Bad LB protocol: Expected ssl got " + loadBalancer.getLbProtocol());
+
+
+        boolean success = false;
+        FirewallRule.State backupState = loadBalancer.getState();
+
+        try {
+
+            loadBalancer.setState(FirewallRule.State.Add);
+            _lbDao.persist(loadBalancer);
+            LoadBalancerCertMapVO certMap = new LoadBalancerCertMapVO(lbRuleId,certId,false);
+            _lbCertMapDao.persist(certMap);
+            applyLoadBalancerConfig(loadBalancer.getId());
+                /*s_logger.warn("Failed to apply Ssl Cert to LB " + loadBalancer.getId());
+                CloudRuntimeException ex = new CloudRuntimeException(
+                        "Failed to apply Ssl Cert to LB " + loadBalancer.getId());
+                ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
+                throw ex;*/
+            success = true;
+        } catch (ResourceUnavailableException e) {
+            if (isRollBackAllowedForProvider(loadBalancer)) {
+
+                loadBalancer.setState(backupState);
+                _lbDao.persist(loadBalancer);
+                LoadBalancerCertMapVO certMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
+                _lbCertMapDao.remove(certMap.getId());
+                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while adding cert");
+            }
+            s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
+        }
+        return success;
+    }
+
+    @Override
+    @DB
+    @ActionEvent(eventType = EventTypes.EVENT_LB_CERT_REMOVE, eventDescription = "removing certificate from load balancer", async = true)
+    public boolean removeCertFromLoadBalancer(long lbRuleId) {
+        CallContext caller = CallContext.current();
+
+        LoadBalancerVO loadBalancer = _lbDao.findById(lbRuleId);
+        LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
+
+        if (loadBalancer == null) {
+            throw new InvalidParameterException("Invalid load balancer value: " + lbRuleId);
+        }
+
+        if( lbCertMap == null ) {
+            throw new InvalidParameterException("No certificate is bound to lb with id: " + lbRuleId);
+        }
+
+        _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
+
+        boolean success = false;
+        FirewallRule.State backupState = loadBalancer.getState();
+        try {
+
+            loadBalancer.setState(FirewallRule.State.Add);
+            _lbDao.persist(loadBalancer);
+            lbCertMap.setRevoke(true);
+            _lbCertMapDao.persist(lbCertMap);
+
+            if (!applyLoadBalancerConfig(lbRuleId)) {
+                s_logger.warn("Failed to remove cert from load balancer rule id " + lbRuleId);
+                CloudRuntimeException ex = new CloudRuntimeException(
+                        "Failed to remove certificate load balancer rule id " + lbRuleId);
+                ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
+                throw ex;
+            }
+            success = true;
+        } catch (ResourceUnavailableException e) {
+            if (isRollBackAllowedForProvider(loadBalancer)) {
+                lbCertMap.setRevoke(false);
+                _lbCertMapDao.persist(lbCertMap);
+                loadBalancer.setState(backupState);
+                _lbDao.persist(loadBalancer);
+                s_logger.debug("Rolled back certificate removal lb id " + lbRuleId);
+            }
+            s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
+            if (!success) {
+                CloudRuntimeException ex = new CloudRuntimeException(
+                        "Failed to remove certificate from load balancer rule id " + lbRuleId);
+                ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
+                throw ex;
+            }
+        }
+        return success;
+    }
+
     private boolean removeFromLoadBalancerInternal(long loadBalancerId, List<Long> instanceIds, boolean rollBack) {
         CallContext caller = CallContext.current();
 
@@ -1317,7 +1473,8 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer")
     public LoadBalancer createPublicLoadBalancerRule(String xId, String name, String description,
-            int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, Long ipAddrId, String protocol, String algorithm, long networkId, long lbOwnerId, boolean openFirewall)
+            int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, Long ipAddrId, String protocol, String algorithm,
+            long networkId, long lbOwnerId, boolean openFirewall, String lbProtocol)
             throws NetworkRuleConflictException, InsufficientAddressCapacityException {
         Account lbOwner = _accountMgr.getAccount(lbOwnerId);
         
@@ -1377,7 +1534,8 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
                             + network);
                 }
 
-                result = createPublicLoadBalancer(xId, name, description, srcPortStart, defPortStart, ipVO.getId(), protocol, algorithm, openFirewall, CallContext.current());
+                result = createPublicLoadBalancer(xId, name, description, srcPortStart, defPortStart, ipVO.getId(), protocol,
+                                    algorithm, openFirewall, CallContext.current(), lbProtocol);
             } catch (Exception ex) {
                 s_logger.warn("Failed to create load balancer due to ", ex);
                 if (ex instanceof NetworkRuleConflictException) {
@@ -1407,13 +1565,14 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
     @DB
     @Override
     public LoadBalancer createPublicLoadBalancer(final String xId, final String name, final String description,
-            final int srcPort, final int destPort, final long sourceIpId, final String protocol, final String algorithm, final boolean openFirewall, final CallContext caller)
+            final int srcPort, final int destPort, final long sourceIpId, final String protocol,
+                final String algorithm, final boolean openFirewall, final CallContext caller, final String lbProtocol)
             throws NetworkRuleConflictException {
         
         if (!NetUtils.isValidPort(destPort)) {
             throw new InvalidParameterValueException("privatePort is an invalid value: " + destPort);
         }
-       
+
         if ((algorithm == null) || !NetUtils.isValidAlgorithm(algorithm)) {
             throw new InvalidParameterValueException("Invalid algorithm: " + algorithm);
         }
@@ -1454,18 +1613,29 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         _firewallMgr.validateFirewallRule(caller.getCallingAccount(), ipAddr, srcPort, srcPort, protocol,
                 Purpose.LoadBalancing, FirewallRuleType.User, networkId, null);
 
+        LoadBalancerVO newRule = new LoadBalancerVO(xId, name, description,
+                sourceIpId, srcPort, destPort, algorithm,
+                networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId(), lbProtocol);
+
+        // verify rule is supported by Lb provider of the network
+        Ip sourceIp = getSourceIp(newRule);
+        LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(),
+                new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp, null, lbProtocol);
+        if (!validateLbRule(loadBalancing)) {
+            throw new InvalidParameterValueException("LB service provider cannot support this rule");
+        }
 
         return Transaction.execute(new TransactionCallbackWithException<LoadBalancerVO,NetworkRuleConflictException>() {
             @Override
             public LoadBalancerVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
                 LoadBalancerVO newRule = new LoadBalancerVO(xId, name, description,
                         sourceIpId, srcPort, destPort, algorithm,
-                        networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId());
+                        networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId(), lbProtocol);
 
                 // verify rule is supported by Lb provider of the network
                 Ip sourceIp = getSourceIp(newRule);
                 LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(),
-                        new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp);
+                        new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp, null, lbProtocol);
                 if (!validateLbRule(loadBalancing)) {
                     throw new InvalidParameterValueException("LB service provider cannot support this rule");
                 }
@@ -1510,7 +1680,6 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
 
     }
 
-    @Override
     public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException {
         LoadBalancerVO lb = _lbDao.findById(lbRuleId);
         List<LoadBalancerVO> lbs;
@@ -1576,7 +1745,8 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
 
         List<LbStickinessPolicy> policyList = getStickinessPolicies(lb.getId());
         Ip sourceIp = getSourceIp(lb);
-        LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, null, policyList, null, sourceIp);
+        LbSslCert sslCert = getLbSslCert(lb.getId());
+        LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, null, policyList, null, sourceIp, sslCert, lb.getLbProtocol());
 
         if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(lb.getId())) {
             // Get the associated VmGroup
@@ -1659,7 +1829,13 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
                             _lb2healthcheckDao.remove(lb.getId(), true);
                             s_logger.debug("Load balancer rule id " + lb.getId() + " is removed health check monitors policies");
                         }
-                        
+
+                        LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(lb.getId());
+                        if (lbCertMap != null && lbCertMap.isRevoke())  {
+                            _lbCertMapDao.remove(lbCertMap.getId());
+                            s_logger.debug("Load balancer rule id " + lb.getId() + " removed certificate mapping");
+                        }
+
                         return checkForReleaseElasticIp;
                     }
                 });

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index 617d6ac..b8d0bab 100755
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -187,6 +187,7 @@ import com.cloud.network.lb.LoadBalancingRule;
 import com.cloud.network.lb.LoadBalancingRule.LbDestination;
 import com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy;
 import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
+import com.cloud.network.lb.LoadBalancingRule.LbSslCert;
 import com.cloud.network.lb.LoadBalancingRulesManager;
 import com.cloud.network.router.VirtualRouter.RedundantState;
 import com.cloud.network.router.VirtualRouter.Role;
@@ -2544,7 +2545,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                     List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
                     List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
                     Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
-                    LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp);
+                    LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId());
+                    LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
                     lbRules.add(loadBalancing);
                 }
             }
@@ -3680,8 +3682,11 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                         List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
                         List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
                         List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
+                        LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId());
                         Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
-                        LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp);
+                        LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp,
+                                sslCert, lb.getLbProtocol());
+
                         lbRules.add(loadBalancing);
                     }
                     return sendLBRules(router, lbRules, network.getId());
@@ -3716,8 +3721,9 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                     List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
                     List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
                     List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
+                    LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId());
                     Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
-                    LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp);
+                    LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
                     lbRules.add(loadBalancing);
                 }
                 return sendLBRules(router, lbRules, network.getId());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java
index 35bc681..d083c11 100755
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -287,6 +287,11 @@ import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRuleI
 import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRulesCmd;
 import org.apache.cloudstack.api.command.user.loadbalancer.RemoveFromLoadBalancerRuleCmd;
 import org.apache.cloudstack.api.command.user.loadbalancer.UpdateLoadBalancerRuleCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.UploadSslCertCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.DeleteSslCertCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.ListSslCertsCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.AssignCertToLoadBalancerCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.RemoveCertFromLoadBalancerCmd;
 import org.apache.cloudstack.api.command.user.nat.CreateIpForwardingRuleCmd;
 import org.apache.cloudstack.api.command.user.nat.DeleteIpForwardingRuleCmd;
 import org.apache.cloudstack.api.command.user.nat.DisableStaticNatCmd;
@@ -2876,6 +2881,11 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
         cmdList.add(UpdateNetworkACLItemCmd.class);
         cmdList.add(CleanVMReservationsCmd.class);
         cmdList.add(UpgradeRouterTemplateCmd.class);
+        cmdList.add(UploadSslCertCmd.class);
+        cmdList.add(DeleteSslCertCmd.class);
+        cmdList.add(ListSslCertsCmd.class);
+        cmdList.add(AssignCertToLoadBalancerCmd.class);
+        cmdList.add(RemoveCertFromLoadBalancerCmd.class);
         return cmdList;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
index b7cd231..f0f0a6e 100644
--- a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
+++ b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
@@ -146,7 +146,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A
         
         //4) Validate Load Balancing rule on the providers
         LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(),
-                new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIpAddr);
+                new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIpAddr, null, null);
         if (!_lbMgr.validateLbRule(loadBalancing)) {
             throw new InvalidParameterValueException("LB service provider cannot support this rule");
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java b/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java
new file mode 100644
index 0000000..53dae50
--- /dev/null
+++ b/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java
@@ -0,0 +1,477 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package org.apache.cloudstack.network.lb;
+
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.network.dao.*;
+import com.cloud.network.lb.CertService;
+import com.cloud.network.rules.LoadBalancer;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.utils.db.EntityManager;
+import com.cloud.utils.exception.CloudRuntimeException;
+import org.apache.cloudstack.api.command.user.loadbalancer.DeleteSslCertCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.ListSslCertsCmd;
+import org.apache.cloudstack.api.command.user.loadbalancer.UploadSslCertCmd;
+import org.apache.cloudstack.api.response.SslCertResponse;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.db.DB;
+import org.apache.cloudstack.acl.SecurityChecker;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.openssl.PEMReader;
+import org.bouncycastle.openssl.PasswordFinder;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.ejb.Local;
+import javax.inject.Inject;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.security.*;
+import java.security.cert.*;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+@Local(value = {CertService.class})
+public class CertServiceImpl implements  CertService {
+
+    private static final Logger s_logger = Logger.getLogger(CertServiceImpl.class);
+
+    @Inject AccountManager _accountMgr;
+    @Inject AccountDao _accountDao;
+    @Inject SslCertDao _sslCertDao;
+    @Inject LoadBalancerCertMapDao _lbCertDao;
+    @Inject EntityManager _entityMgr;
+
+
+
+    public CertServiceImpl() {
+        Security.addProvider(new BouncyCastleProvider());
+    }
+
+    @DB
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_LB_CERT_UPLOAD, eventDescription = "Uploading a certificate to cloudstack", async = false)
+    public SslCertResponse uploadSslCert(UploadSslCertCmd certCmd) {
+        try {
+
+            String cert = URLDecoder.decode(certCmd.getCert(), "UTF-8");
+            String key = URLDecoder.decode(certCmd.getKey(), "UTF-8");
+            String password = certCmd.getPassword();
+            String chain = certCmd.getChain() == null ? null: URLDecoder.decode(certCmd.getChain(), "UTF-8");
+
+            validate(cert, key, password, chain);
+            s_logger.debug("Certificate Validation succeeded");
+            String fingerPrint = generateFingerPrint(parseCertificate(cert));
+
+            Long accountId = CallContext.current().getCallingAccount().getId();
+            Long domainId = CallContext.current().getCallingAccount().getDomainId();
+
+
+            SslCertVO certVO = new SslCertVO(cert, key, password, chain, accountId, domainId, fingerPrint);
+            _sslCertDao.persist(certVO);
+
+
+            return createCertResponse(certVO, null);
+
+        } catch (UnsupportedEncodingException e) {
+            throw new CloudRuntimeException("Error decoding certificate data");
+        }
+
+    }
+
+    @DB
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_LB_CERT_DELETE, eventDescription = "Deleting a certificate to cloudstack", async = false)
+    public void deleteSslCert(DeleteSslCertCmd deleteSslCertCmd) {
+
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
+
+        Long certId = deleteSslCertCmd.getId();
+        SslCertVO certVO = _sslCertDao.findById(certId);
+
+        if (certVO == null) {
+            throw new InvalidParameterValueException("Invalid certificate id: " + certId);
+        }
+        _accountMgr.checkAccess(caller, SecurityChecker.AccessType.ModifyEntry, true, certVO);
+
+        List<LoadBalancerCertMapVO> lbCertRule = _lbCertDao.listByCertId(certId);
+
+        if ( (lbCertRule != null) && (!lbCertRule.isEmpty()) ){
+            String lbUuids = "";
+
+            for( LoadBalancerCertMapVO rule : lbCertRule ){
+                LoadBalancerVO lb = _entityMgr.findById(LoadBalancerVO.class, rule.getLbId());
+                lbUuids += " " + lb.getUuid();
+            }
+
+            throw new CloudRuntimeException("Certificate in use by a loadbalancer(s)" + lbUuids);
+        }
+
+        _sslCertDao.remove(certId);
+    }
+
+    @Override
+    public List<SslCertResponse> listSslCerts(ListSslCertsCmd listSslCertCmd) {
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
+
+        Long certId= listSslCertCmd.getCertId();
+        Long accountId = listSslCertCmd.getAccountId();
+        Long lbRuleId = listSslCertCmd.getLbId();
+
+        List<SslCertResponse> certResponseList = new ArrayList<SslCertResponse>();
+
+        if (certId == null && accountId == null && lbRuleId == null ) {
+            throw new InvalidParameterValueException("Invalid parameters either certificate ID or Account ID or Loadbalancer ID required");
+        }
+
+        List<LoadBalancerCertMapVO> certLbMap = null;
+        SslCertVO certVO = null;
+
+
+        if(certId != null) {
+
+            certVO = _sslCertDao.findById(certId);
+
+            if (certVO == null) {
+                throw new InvalidParameterValueException("Invalid certificate id: " + certId);
+            }
+
+
+            _accountMgr.checkAccess(caller, SecurityChecker.AccessType.ListEntry, true, certVO);
+
+            certLbMap = _lbCertDao.listByCertId(certId);
+
+            certResponseList.add(createCertResponse(certVO, certLbMap));
+            return certResponseList;
+        }
+
+        if ( lbRuleId != null) {
+            LoadBalancer lb = _entityMgr.findById(LoadBalancerVO.class, lbRuleId);
+
+            if ( lb == null ){
+                throw new InvalidParameterValueException("found no loadbalancer  wth id: " + lbRuleId);
+            }
+
+            _accountMgr.checkAccess(caller, SecurityChecker.AccessType.ListEntry, true, lb);
+
+            // get the cert id
+            LoadBalancerCertMapVO lbCertMapRule;
+            lbCertMapRule = _lbCertDao.findByLbRuleId(lbRuleId);
+
+            if (lbCertMapRule == null) {
+                throw new InvalidParameterValueException("No certificate bound to loadbalancer id: " + lbRuleId);
+            }
+
+            certVO = _sslCertDao.findById(lbCertMapRule.getCertId());
+            certLbMap = _lbCertDao.listByCertId(lbCertMapRule.getCertId());
+
+            certResponseList.add(createCertResponse(certVO, certLbMap));
+            return certResponseList;
+
+        }
+
+        //reached here look by accountId
+        List<SslCertVO> certVOList = _sslCertDao.listByAccountId(accountId);
+        if ( certVOList == null || certVOList.isEmpty())
+            return certResponseList;
+        _accountMgr.checkAccess(caller, SecurityChecker.AccessType.ListEntry, true, certVOList.get(0));
+
+        for( SslCertVO cert : certVOList ){
+                   certLbMap = _lbCertDao.listByCertId(cert.getId());
+                   certResponseList.add(createCertResponse(cert, certLbMap));
+        }
+
+        return certResponseList;
+    }
+
+
+    private void validate(String _cert, String _key, String _password, String _chain) {
+        Certificate cert;
+        PrivateKey key;
+        List<Certificate> chain=null;
+
+
+        try {
+            cert = parseCertificate(_cert);
+            key = parsePrivateKey(_key, _password);
+
+            if ( _chain != null) {
+                chain = parseChain(_chain);
+            }
+
+        } catch (IOException e) {
+            throw new IllegalArgumentException("Parsing certificate/key failed: " + e.getMessage());
+        }
+
+        validateCert(cert, _chain != null? true: false);
+        validateKeys(cert.getPublicKey(), key);
+
+        if ( _chain != null )
+            validateChain(chain, cert);
+    }
+
+    public SslCertResponse createCertResponse(SslCertVO cert, List<LoadBalancerCertMapVO> lbCertMap) {
+        SslCertResponse response = new SslCertResponse();
+
+        Account account = _accountDao.findByIdIncludingRemoved(cert.getAccountId());
+
+        response.setObjectName("sslcert");
+        response.setId(cert.getUuid());
+        response.setCertificate(cert.getCertificate());
+        response.setPrivatekey(cert.getKey());
+        response.setFingerprint(cert.getFingerPrint());
+        response.setAccountName(account.getAccountName());
+
+        if ( cert.getChain() != null)
+            response.setCertchain(cert.getChain());
+
+        if ( lbCertMap != null && !lbCertMap.isEmpty()){
+            List<String> lbIds = new ArrayList<String>();
+            for ( LoadBalancerCertMapVO mapVO : lbCertMap ) {
+                LoadBalancer lb = _entityMgr.findById(LoadBalancerVO.class, mapVO.getLbId());
+                lbIds.add(lb.getUuid());
+            }
+            response.setLbIds(lbIds);
+        }
+
+        return response;
+    }
+
+    private void validateCert(Certificate cert, boolean chain_present) {
+
+        if ( !( cert instanceof X509Certificate))
+            throw new IllegalArgumentException("Invalid certificate format. Expected X509 certificate");
+
+        try {
+            ((X509Certificate)cert).checkValidity();
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Certificate expired or not valid");
+        }
+
+        if( !chain_present ) {
+            PublicKey pubKey = cert.getPublicKey();
+            try {
+                cert.verify(pubKey);
+            } catch (Exception e) {
+                throw new IllegalArgumentException("No chain given and certificate not self signed");
+            }
+        }
+    }
+
+    private void validateKeys(PublicKey pubKey, PrivateKey privKey) {
+
+        if (pubKey.getAlgorithm() != privKey.getAlgorithm())
+            throw new IllegalArgumentException("Public and private key have different algorithms");
+
+        // No encryption for DSA
+        if ( pubKey.getAlgorithm() != "RSA")
+            return;
+
+        try {
+
+            String data = "ENCRYPT_DATA";
+            SecureRandom random = new SecureRandom();
+            Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
+            cipher.init(Cipher.ENCRYPT_MODE,privKey,random);
+            byte[] encryptedData = cipher.doFinal(data.getBytes());
+
+            cipher.init(Cipher.DECRYPT_MODE,pubKey,random);
+            String decreptedData = new String(cipher.doFinal(encryptedData));
+            if (!decreptedData.equals(data))
+                throw new IllegalArgumentException("Bad public-private key");
+
+        } catch (BadPaddingException e) {
+            throw new IllegalArgumentException("Bad public-private key");
+        } catch (IllegalBlockSizeException e) {
+            throw new IllegalArgumentException("Bad public-private key");
+        } catch (NoSuchPaddingException e) {
+            throw new IllegalArgumentException("Bad public-private key");
+        } catch (InvalidKeyException e) {
+            throw new IllegalArgumentException("Invalid public-private key");
+        } catch (NoSuchAlgorithmException e) {
+            throw new IllegalArgumentException("Invalid algorithm for public-private key");
+        }
+    }
+
+
+    private void validateChain(List<Certificate> chain, Certificate cert) {
+
+        List<Certificate> certs = new ArrayList<Certificate>();
+        List<Certificate> root = new ArrayList<Certificate>();
+
+        Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
+
+
+        certs.add(cert); // adding for self signed certs
+        certs.addAll(chain);
+
+        for( Certificate c : certs) {
+            if ( !( c instanceof X509Certificate))
+                throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
+
+            X509Certificate xCert = (X509Certificate)c;
+
+            Principal subject = xCert.getSubjectDN();
+            Principal issuer = xCert.getIssuerDN();
+
+            if( issuer != null &&  subject.equals(issuer) ) {
+                root.add(c);
+                anchors.add(new TrustAnchor(xCert,null));
+            }
+        }
+
+        if ( root.size() == 0 )
+            throw new IllegalArgumentException("No root certificates found for certificate chain",null);
+
+
+        X509CertSelector target = new X509CertSelector();
+        target.setCertificate((X509Certificate)cert);
+
+        PKIXBuilderParameters params = null;
+        try {
+            params = new PKIXBuilderParameters(anchors, target);
+            params.setRevocationEnabled(false);
+            params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
+            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
+            builder.build(params);
+        } catch (InvalidAlgorithmParameterException e) {
+            throw new IllegalArgumentException("Invalid certificate chain",null);
+        } catch (CertPathBuilderException e) {
+            throw new IllegalArgumentException("Invalid certificate chain",null);
+        } catch (NoSuchAlgorithmException e) {
+            throw new IllegalArgumentException("Invalid certificate chain",null);
+        }
+
+    }
+
+    public PrivateKey parsePrivateKey(String key, String password) throws IOException {
+
+        PasswordFinder pGet = null;
+
+        if( password != null )
+               pGet = new KeyPassword(password.toCharArray());
+
+          PEMReader privateKey = new PEMReader(new StringReader(key), pGet);
+          Object obj = privateKey.readObject();
+
+        try {
+
+            if ( obj instanceof KeyPair )
+                return ((KeyPair)obj).getPrivate();
+
+            return (PrivateKey) obj;
+
+        }catch (Exception e){
+            e.printStackTrace();
+            throw new IOException("Invalid Key format or invalid password.");
+        }
+    }
+
+
+    public Certificate parseCertificate(String cert) {
+        PEMReader certPem = new PEMReader(new StringReader(cert));
+        try {
+            return (Certificate) certPem.readObject();
+        } catch (Exception e) {
+            throw new InvalidParameterValueException("Invalid Certificate format. Expected X509 certificate");
+        }
+    }
+
+
+    public List<Certificate> parseChain(String chain) throws IOException {
+
+        List<Certificate> certs = new ArrayList<Certificate>();
+        PEMReader reader = new PEMReader(new StringReader(chain));
+
+        Certificate crt = null;
+
+        while ( ( crt = (Certificate) reader.readObject()) != null ) {
+            if ( crt instanceof X509Certificate) {
+                certs.add(crt);
+            }
+        }
+        if ( certs.size() == 0 )
+            throw new IllegalArgumentException("Unable to decode certificate chain",null);
+
+        return certs;
+    }
+
+
+    String generateFingerPrint(Certificate cert) {
+
+        final char[] HEX =
+                {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+        StringBuilder buffer = new StringBuilder(60);
+        try {
+
+            MessageDigest md = MessageDigest.getInstance("SHA-1");
+            byte[] data = md.digest(cert.getEncoded());
+
+            for ( int i = 0 ; i < data.length ; i++ ) {
+                if ( buffer.length() > 0 ) {
+                    buffer.append(":");
+                }
+
+                buffer.append(HEX[(0xF0 & data[i]) >>> 4]);
+                buffer.append(HEX[0x0F & data[i]]);
+            }
+
+        } catch (CertificateEncodingException e) {
+            throw new InvalidParameterValueException("Bad certificate encoding");
+        } catch (NoSuchAlgorithmException e) {
+            throw new InvalidParameterValueException("Bad certificate algorithm");
+        }
+
+        return buffer.toString();
+    }
+
+
+    public static class KeyPassword implements PasswordFinder {
+
+        boolean password_requested=false;
+        char[]  password;
+
+
+        KeyPassword(char[] word){
+            this.password = word;
+        }
+
+        public char[] getPassword() {
+            password_requested=true;
+            return password;
+        }
+
+        public boolean getPasswordRequested(){
+            return password_requested;
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/00763078/server/test/org/apache/cloudstack/lb/ApplicationLoadBalancerTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/apache/cloudstack/lb/ApplicationLoadBalancerTest.java b/server/test/org/apache/cloudstack/lb/ApplicationLoadBalancerTest.java
deleted file mode 100644
index 9b46e68..0000000
--- a/server/test/org/apache/cloudstack/lb/ApplicationLoadBalancerTest.java
+++ /dev/null
@@ -1,380 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package org.apache.cloudstack.lb;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.inject.Inject;
-
-import junit.framework.TestCase;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.ComponentScan.Filter;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.FilterType;
-import org.springframework.core.type.classreading.MetadataReader;
-import org.springframework.core.type.classreading.MetadataReaderFactory;
-import org.springframework.core.type.filter.TypeFilter;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-import org.apache.cloudstack.context.CallContext;
-import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
-import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao;
-import org.apache.cloudstack.network.lb.ApplicationLoadBalancerManagerImpl;
-import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule;
-import org.apache.cloudstack.test.utils.SpringUtils;
-
-import com.cloud.event.dao.UsageEventDao;
-import com.cloud.exception.InsufficientAddressCapacityException;
-import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.NetworkRuleConflictException;
-import com.cloud.exception.UnsupportedServiceException;
-import com.cloud.network.IpAddressManager;
-import com.cloud.network.Network;
-import com.cloud.network.Network.Capability;
-import com.cloud.network.Network.Service;
-import com.cloud.network.NetworkModel;
-import com.cloud.network.Networks.TrafficType;
-import com.cloud.network.dao.FirewallRulesDao;
-import com.cloud.network.dao.NetworkVO;
-import com.cloud.network.lb.LoadBalancingRule;
-import com.cloud.network.lb.LoadBalancingRulesManager;
-import com.cloud.network.lb.LoadBalancingRulesService;
-import com.cloud.network.rules.FirewallRuleVO;
-import com.cloud.network.rules.LoadBalancerContainer.Scheme;
-import com.cloud.tags.dao.ResourceTagDao;
-import com.cloud.user.AccountManager;
-import com.cloud.user.AccountVO;
-import com.cloud.user.UserVO;
-import com.cloud.utils.component.ComponentContext;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.net.Ip;
-import com.cloud.utils.net.NetUtils;
-
-/**
- * This class is responsible for unittesting the methods defined in ApplicationLoadBalancerService
- *
- */
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
-public class ApplicationLoadBalancerTest extends TestCase {
-    //The interface to test
-    @Inject
-    ApplicationLoadBalancerManagerImpl _appLbSvc;
-
-    //The interfaces below are mocked
-    @Inject
-    ApplicationLoadBalancerRuleDao _lbDao;
-    @Inject
-    LoadBalancingRulesManager _lbMgr;
-    @Inject
-    NetworkModel _ntwkModel;
-    @Inject
-    AccountManager _accountMgr;
-    @Inject
-    FirewallRulesDao _firewallDao;
-    @Inject
-    UsageEventDao _usageEventDao;
-    @Inject
-    LoadBalancingRulesService _lbService;
-
-    public static long existingLbId = 1L;
-    public static long nonExistingLbId = 2L;
-
-    public static long validGuestNetworkId = 1L;
-    public static long invalidGuestNetworkId = 2L;
-    public static long validPublicNetworkId = 3L;
-
-    public static long validAccountId = 1L;
-    public static long invalidAccountId = 2L;
-
-    public String validRequestedIp = "10.1.1.1";
-
-    @Override
-    @Before
-    public void setUp() {
-        ComponentContext.initComponentsLifeCycle();
-        //mockito for .getApplicationLoadBalancer tests
-        Mockito.when(_lbDao.findById(1L)).thenReturn(new ApplicationLoadBalancerRuleVO());
-        Mockito.when(_lbDao.findById(2L)).thenReturn(null);
-
-        //mockito for .deleteApplicationLoadBalancer tests
-        Mockito.when(_lbService.deleteLoadBalancerRule(existingLbId, true)).thenReturn(true);
-        Mockito.when(_lbService.deleteLoadBalancerRule(nonExistingLbId, true)).thenReturn(false);
-
-        //mockito for .createApplicationLoadBalancer tests
-        NetworkVO guestNetwork = new NetworkVO(TrafficType.Guest, null, null, 1, null, 1, 1L);
-        setId(guestNetwork, validGuestNetworkId);
-        guestNetwork.setCidr("10.1.1.1/24");
-
-        NetworkVO publicNetwork = new NetworkVO(TrafficType.Public, null, null, 1, null, 1, 1L);
-
-        Mockito.when(_ntwkModel.getNetwork(validGuestNetworkId)).thenReturn(guestNetwork);
-        Mockito.when(_ntwkModel.getNetwork(invalidGuestNetworkId)).thenReturn(null);
-        Mockito.when(_ntwkModel.getNetwork(validPublicNetworkId)).thenReturn(publicNetwork);
-
-        Mockito.when(_accountMgr.getAccount(validAccountId)).thenReturn(new AccountVO());
-        Mockito.when(_accountMgr.getAccount(invalidAccountId)).thenReturn(null);
-        Mockito.when(_ntwkModel.areServicesSupportedInNetwork(validGuestNetworkId, Service.Lb)).thenReturn(true);
-        Mockito.when(_ntwkModel.areServicesSupportedInNetwork(invalidGuestNetworkId, Service.Lb)).thenReturn(false);
-
-        ApplicationLoadBalancerRuleVO lbRule = new ApplicationLoadBalancerRuleVO("new", "new", 22, 22, "roundrobin", validGuestNetworkId, validAccountId, 1L, new Ip(
-            validRequestedIp), validGuestNetworkId, Scheme.Internal);
-        Mockito.when(_lbDao.persist(Mockito.any(ApplicationLoadBalancerRuleVO.class))).thenReturn(lbRule);
-
-        Mockito.when(_lbMgr.validateLbRule(Mockito.any(LoadBalancingRule.class))).thenReturn(true);
-
-        Mockito.when(_firewallDao.setStateToAdd(Mockito.any(FirewallRuleVO.class))).thenReturn(true);
-
-        Mockito.when(_accountMgr.getSystemUser()).thenReturn(new UserVO(1));
-        Mockito.when(_accountMgr.getSystemAccount()).thenReturn(new AccountVO(2));
-        CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
-
-        Mockito.when(_ntwkModel.areServicesSupportedInNetwork(Mockito.anyLong(), Mockito.any(Network.Service.class))).thenReturn(true);
-
-        Map<Network.Capability, String> caps = new HashMap<Network.Capability, String>();
-        caps.put(Capability.SupportedProtocols, NetUtils.TCP_PROTO);
-        Mockito.when(_ntwkModel.getNetworkServiceCapabilities(Mockito.anyLong(), Mockito.any(Network.Service.class))).thenReturn(caps);
-
-        Mockito.when(_lbDao.countBySourceIp(new Ip(validRequestedIp), validGuestNetworkId)).thenReturn(1L);
-
-    }
-
-    @Override
-    @After
-    public void tearDown() {
-        CallContext.unregister();
-    }
-
-    /**
-     * TESTS FOR .getApplicationLoadBalancer
-     */
-
-    @Test
-    //Positive test - retrieve existing lb
-        public
-        void searchForExistingLoadBalancer() {
-        ApplicationLoadBalancerRule rule = _appLbSvc.getApplicationLoadBalancer(existingLbId);
-        assertNotNull("Couldn't find existing application load balancer", rule);
-    }
-
-    @Test
-    //Negative test - try to retrieve non-existing lb
-        public
-        void searchForNonExistingLoadBalancer() {
-        boolean notFound = false;
-        ApplicationLoadBalancerRule rule = null;
-        try {
-            rule = _appLbSvc.getApplicationLoadBalancer(nonExistingLbId);
-            if (rule != null) {
-                notFound = false;
-            }
-        } catch (InvalidParameterValueException ex) {
-            notFound = true;
-        }
-
-        assertTrue("Found non-existing load balancer; no invalid parameter value exception was thrown", notFound);
-    }
-
-    /**
-     * TESTS FOR .deleteApplicationLoadBalancer
-     */
-
-    @Test
-    //Positive test - delete existing lb
-        public
-        void deleteExistingLoadBalancer() {
-        boolean result = false;
-        try {
-            result = _appLbSvc.deleteApplicationLoadBalancer(existingLbId);
-        } finally {
-            assertTrue("Couldn't delete existing application load balancer", result);
-        }
-    }
-
-    @Test
-    //Negative test - try to delete non-existing lb
-        public
-        void deleteNonExistingLoadBalancer() {
-        boolean result = true;
-        try {
-            result = _appLbSvc.deleteApplicationLoadBalancer(nonExistingLbId);
-        } finally {
-            assertFalse("Didn't fail when try to delete non-existing load balancer", result);
-        }
-    }
-
-    /**
-     * TESTS FOR .createApplicationLoadBalancer
-     * @throws NetworkRuleConflictException
-     * @throws InsufficientVirtualNetworkCapcityException
-     * @throws InsufficientAddressCapacityException
-     */
-
-    @Test(expected = CloudRuntimeException.class)
-    //Positive test
-        public
-        void createValidLoadBalancer() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Internal, validGuestNetworkId, validRequestedIp, 22, 22, "roundrobin", validGuestNetworkId, validAccountId);
-    }
-
-    @Test(expected = UnsupportedServiceException.class)
-    //Negative test - only internal scheme value is supported in the current release
-        public
-        void createPublicLoadBalancer() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Public, validGuestNetworkId, validRequestedIp, 22, 22, "roundrobin", validGuestNetworkId, validAccountId);
-    }
-
-    @Test(expected = InvalidParameterValueException.class)
-    //Negative test - invalid SourcePort
-        public
-        void createWithInvalidSourcePort() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Internal, validGuestNetworkId, validRequestedIp, 65536, 22, "roundrobin", validGuestNetworkId,
-            validAccountId);
-    }
-
-    @Test(expected = InvalidParameterValueException.class)
-    //Negative test - invalid instancePort
-        public
-        void createWithInvalidInstandePort() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Internal, validGuestNetworkId, validRequestedIp, 22, 65536, "roundrobin", validGuestNetworkId,
-            validAccountId);
-
-    }
-
-    @Test(expected = InvalidParameterValueException.class)
-    //Negative test - invalid algorithm
-        public
-        void createWithInvalidAlgorithm() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-        String expectedExcText = null;
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Internal, validGuestNetworkId, validRequestedIp, 22, 22, "invalidalgorithm", validGuestNetworkId,
-            validAccountId);
-
-    }
-
-    @Test(expected = InvalidParameterValueException.class)
-    //Negative test - invalid sourceNetworkId (of Public type, which is not supported)
-        public
-        void createWithInvalidSourceIpNtwk() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Internal, validPublicNetworkId, validRequestedIp, 22, 22, "roundrobin", validGuestNetworkId,
-            validAccountId);
-
-    }
-
-    @Test(expected = InvalidParameterValueException.class)
-    //Negative test - invalid requested IP (outside of guest network cidr range)
-        public
-        void createWithInvalidRequestedIp() throws InsufficientAddressCapacityException, InsufficientVirtualNetworkCapcityException, NetworkRuleConflictException {
-
-        _appLbSvc.createApplicationLoadBalancer("alena", "alena", Scheme.Internal, validGuestNetworkId, "10.2.1.1", 22, 22, "roundrobin", validGuestNetworkId, validAccountId);
-    }
-
-    private static NetworkVO setId(NetworkVO vo, long id) {
-        NetworkVO voToReturn = vo;
-        Class<?> c = voToReturn.getClass();
-        try {
-            Field f = c.getDeclaredField("id");
-            f.setAccessible(true);
-            f.setLong(voToReturn, id);
-        } catch (NoSuchFieldException ex) {
-            return null;
-        } catch (IllegalAccessException ex) {
-            return null;
-        }
-
-        return voToReturn;
-    }
-
-    @Configuration
-    @ComponentScan(basePackageClasses = {NetUtils.class, ApplicationLoadBalancerManagerImpl.class}, includeFilters = {@Filter(value = TestConfiguration.Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false)
-    public static class TestConfiguration extends SpringUtils.CloudStackTestConfiguration {
-
-        @Bean
-        public ApplicationLoadBalancerRuleDao applicationLoadBalancerDao() {
-            return Mockito.mock(ApplicationLoadBalancerRuleDao.class);
-        }
-
-        @Bean
-        IpAddressManager ipAddressManager() {
-            return Mockito.mock(IpAddressManager.class);
-        }
-
-        @Bean
-        public NetworkModel networkModel() {
-            return Mockito.mock(NetworkModel.class);
-        }
-
-        @Bean
-        public AccountManager accountManager() {
-            return Mockito.mock(AccountManager.class);
-        }
-        
-
-        @Bean
-        public LoadBalancingRulesManager loadBalancingRulesManager() {
-            return Mockito.mock(LoadBalancingRulesManager.class);
-        }
-
-        @Bean
-        public LoadBalancingRulesService loadBalancingRulesService() {
-            return Mockito.mock(LoadBalancingRulesService.class);
-        }
-
-        @Bean
-        public FirewallRulesDao firewallRulesDao() {
-            return Mockito.mock(FirewallRulesDao.class);
-        }
-
-        @Bean
-        public ResourceTagDao resourceTagDao() {
-            return Mockito.mock(ResourceTagDao.class);
-        }
-
-        @Bean
-        public NetworkOrchestrationService networkManager() {
-            return Mockito.mock(NetworkOrchestrationService.class);
-        }
-
-        @Bean
-        public UsageEventDao UsageEventDao() {
-            return Mockito.mock(UsageEventDao.class);
-        }
-
-        public static class Library implements TypeFilter {
-            @Override
-            public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException {
-                mdr.getClassMetadata().getClassName();
-                ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class);
-                return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs);
-            }
-        }
-    }
-
-}